connect to the mysql database using phpseclib libr

2019-05-31 09:38发布

I have successfully connect to the My VPS using phpscelib library.Now i want to connect to my existing database.Please help me for this ?

<?php
set_include_path(get_include_path() . PATH_SEPARATOR . 'phpseclib');

include('Net/SSH2.php');


$ssh = new Net_SSH2('192.ccc.ccc.ccc');
if (!$ssh->login('ccc', 'cccc')) {
exit('Login Failed');
}

echo $ssh->exec("I need to put MySql commands here");
?>

2条回答
乱世女痞
2楼-- · 2019-05-31 10:00

short and simple

echo $ssh->exec('echo "select * from table where company_id=\"15\";" | mysql -u username -password=password database');
查看更多
3楼-- · 2019-05-31 10:14

First, wouldn't it be better to allow remote access for that user to mysql? However, I don't know your reasons.

The most common an transparent way would be create a ssh tunnel. This can be done in two different ways. If the mysql port (3306) isn't open on the mysql machine, you'll need a reverse ssh tunnel which has to be opened by the remote machine. Log into the mysql machine and issue the following command:

ssh -R 12345:localhost:3306 user@php_machine -N

If the mysql port is open on the remote machine then the tunnel can be opened by the php machine:

ssh -f user@mysql_machine -L 12345:mysql_machine:3306 -N

Regardless of the way the tunnels has been created, the PHP application can now just use PDO and connect to localhost port 12345.

$pdo = new PDO('mysql:host=localhost;port=12345;dbname=test', $user, $password);

All traffic will get crypted through the tunnel.


If you just want to issue a couple of simple commands you might use the following alternative.

The simplest but unsecure way would be to use the following command:

echo $ssh->exec('mysql -uUSER -pPASSWORD DATABASE -e "SQL COMMAND"');

This is insecure because other users on the system could see the password.

You can workaround the security issue using expect. expect is a program which can pass the password to mysql in a more secure way. Make sure that expect is installed on the remote system. Here comes an example using the SHOW TABLES command on database test:

include('Net/SSH2.php');

$ssh = new Net_SSH2('192.xxx.xxx.xxx');
if (!$ssh->login('ssh_user', 'ssh_password')) {
exit('Login Failed');
}

echo $ssh->exec('expect <<EOF
# disable command output
log_user 0
# start the mysqldump process
spawn mysql -uTHE_USER -p test -e "SHOW TABLES"
# wait for the password prompt
expect "password:"
# send the password (mind the \r)
send "THE_PASSWORD\r"
# enable output again
log_user 1
# echo all outout until the end
expect eof
EOF
');

To further understand what's going, I've recently wrote a my blog article about that.

查看更多
登录 后发表回答