使用phpseclib通过SSH连接到MySQL的PHP​​代码

时间:2014-01-21 07:46:48

标签: php mysql windows ssh phpseclib

我想在服务器上连接MySQL,但服务器只能通过SSH访问。 我用phpseclib连接SSH。它是成功的。 但是当尝试连接到MySQL时,它说:访问被拒绝。 所以,我有这些代码。有人请帮帮我..

<?php

//data for connection to SSH
//host : 10.81.229.31
//user : root
//pass : abcde

//here's data for connection to MySQL
//host = 10.81.229.31
//username = root
//password = abcde
//database name = testing


include('Net/SSH2.php');

//connecting to server with SSH
$ssh = new Net_SSH2('10.81.229.31');

if (!$ssh->login('root', 'abcde')) {
    exit('Login Failed');
}else{
    echo "Login Success";
}

//connecting to MySQL
echo $ssh->exec('mysql -h 10.81.229.31 -u root -p testing');

?>

3 个答案:

答案 0 :(得分:1)

如果您在框中使用ssh,则应将数据库引用为localhost

echo $ssh->exec('mysql -h localhost -u root -ptesting');

答案 1 :(得分:0)

尝试没有空间。例如

echo $ssh->exec('mysql -h localhost -u root -ptesting');

引自“man mysql”:

  

- 密码[=密码], - p [密码]

答案 2 :(得分:0)

<?php

//data for connection to SSH
//host : 10.81.229.31
//user : root
//pass : abcde

//here's data for connection to MySQL
//host = 10.81.229.31
//username = root
//password = abcde
//database name = testing


include('Net/SSH2.php');

//connecting to server with SSH
$ssh = new Net_SSH2('10.81.229.31');

if (!$ssh->login('root', 'abcde')) {
    exit('Login to Server Failed');
}else{
    echo "Login to Server Success";
}

//connecting to MySQL
if (!$ssh->exec('mysql -u root -ptesting \r\n')){
    exit('Login to MySQL Failed');
}else{
    echo "Login to MySQL Success";
}

?>

\ r \ n用于ENTER 结果:

Login to Server SuccessLogin to MySQL Success

非常感谢大家,他们已经帮助过我了。