外部VPSサーバーからさくらレンタルサーバーのDBに接続する方法。

20201204

Logging

外部VPSサーバーからさくらレンタルサーバーのDB(データベース)に接続する方法は下記のコードだけでは上手く動かない。だけど、tmpファイルを生成時にパーティションにu+xの権限を与えればこのコードは要件をみたします。因みにプロセスが残ったままになるので接続が終わったら、プロセスを削除してあげてください。なのでどのプロセスを削除する機能として追加しないと使えないかな?、時間があれば完成したコードをアップします。

なお、変数の初期値はご自身で入れてください。あとポート開放expectが入っていない場合はyumなどでインストールする必要もあります。

<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<meta name="Description" content="Enter your description here" />
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.min.css">
	<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.0/css/all.min.css">
	<link rel="stylesheet" href="assets/css/style.css">
	<title>ssh sqli</title>
</head>

<body>
	<?php
	print ssh_sqli_connect();
	?>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>

</html>
<?php
function ssh_sqli_connect()
{
	global $dblink,$dbname,$sshuser, $sshhost, $sshpassword,$host,$sshport;
	$ret = null;
	$cmd = "#!/usr/bin/expect -f
set timeout 3
expect -c \"spawn ssh -f -N -L $sshport:$host:3306 $sshuser@$sshhost -oStrictHostKeyChecking=no
expect \\\"$sshuser@$sshhost's password:\\\"
send \\\"$sshpassword\\n\\\"
\"
";

	$tmpfname = tempnam(sys_get_temp_dir(), 'ssh');

	$handle = fopen($tmpfname, "w");
	fwrite($handle, $cmd);
   	shell_exec("sh $tmpfname");
	sleep(3);
	$dblink = db_connect();
	try{
		for($id = 1 ;$id<=99;$id++){
			$ret = $dblink->query("SELECT * FROM $dbname.X.xtbl where $dbname.X.xtbl.id=$id;");
			if ($cnt = (int) mysqli_num_rows($ret)) {
			  $row = mysqli_fetch_assoc($ret);
			  print ($row["id"].", ".$row["name"]);
			}
		}
	}catch(PDOException $e){
		echo "失敗: " . $e->getMessage() . "\n";
	}

	fclose($handle);
	unlink($tmpfname);

	db_close();
	return "未完成";
}

function db_connect()
{
	global $dblink, $host, $user, $password, $dbname,$sshport;
	try {
		$dblink = new  mysqli("127.0.0.1", "$user", $password, $dbname ,$sshport);
		//$dblink->set_charset("utf8");
		return $dblink;
	} catch (PDOException $e) {
		echo "接続失敗: " . $e->getMessage() . "\n";
	}
}

function db_close()
{
	global $dblink;
	$dblink->close();
}

タグ

8, charset, db, DOCTYPE, en, expect, gt, head, html, lang, lt, meta, name, quot, tmp, UTF-, vie, VPS, yum, アップ, インストール, コード, ご自身, サーバー, さくら, データベース, パーティション, ファイル, プロセス, ポート, まま, レンタル, 下記, 初期, 削除, 場合, 変数, 外部, 完成, 必要, 接続, 方法, 時間, 権限, 機能, 生成, 要件, 追加, 開放,