connect to the mysql database using phpseclib library

百般思念 提交于 2020-01-03 01:35:07

问题


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");
?>

回答1:


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.




回答2:


short and simple

echo $ssh->exec('echo "select * from table where company_id=\"15\";" | mysql -u username -password=password database');


来源:https://stackoverflow.com/questions/18270960/connect-to-the-mysql-database-using-phpseclib-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!