如何使用php模擬實(shí)現(xiàn)ssh方式登錄執(zhí)行mysql語(yǔ)句輸出結(jié)果?類似于navicat的SSH連接數(shù)據(jù)庫(kù)
查詢php.net SSH文檔先驗(yàn)證SSH:
$conn=ssh2_connect('SSH IP',22);
ssh2_auth_password($conn,'SSH USER','SSH PASS');
然后看網(wǎng)上幾種不知道是否正確的寫(xiě)法:
1.使用ssh2_tunnel
$tunnel = ssh2_tunnel($conn, 'REMOTE MYSQL IP', 3307);
$mysqli=new mysqli('127.0.0.1','MYSQL USER','MYSQL PASS','MYSQL DB',3307,$tunnel);
$result=$mysqli->query($SQL);
2.使用ssh2_exec
$stream=ssh2_exec($connection,'echo "select * from db.table where id=\"1\";" | mysql');
3.使用shell_exec
shell_exec("ssh -f -L 127.0.0.1:3307:127.0.0.1:3306 user@remote.rjmetrics.com sleep 60 >> logfile");
$db = mysqli_connect('127.0.0.1', 'MYSQL USER','MYSQL PASS','MYSQL DB', 3307);
...好像還有使用ssh2_shell的,在不知道數(shù)據(jù)庫(kù)服務(wù)器可以執(zhí)行那些腳本的情況下怎么寫(xiě)這個(gè)連接?
走同樣的路,發(fā)現(xiàn)不同的人生
可以參看我的筆記介紹SSH2的
$connection = ssh2_connect('example.com', 22);
if (ssh2_auth_password($connection, 'root', 'password')) {
echo "Authentication Successful!\n";
} else {
die('Authentication Failed...');
}
$stream = ssh2_exec($connection, 'mysql -uroot -p密碼;use 數(shù)據(jù)庫(kù)名;select * from table_name');
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
echo stream_get_contents($stream_out);