开发者

How to do SSH from PHP?

开发者 https://www.devze.com 2023-03-17 19:01 出处:网络
I have a database of [server, username, password] records and I need to programatically connect to those machines via 开发者_C百科SSH, execute a remote sudo command (install some applications using ap

I have a database of [server, username, password] records and I need to programatically connect to those machines via 开发者_C百科SSH, execute a remote sudo command (install some applications using apt-get or whatever is available on the server) and retrieve the output (exitcode would be nice, but output is enough). How can I do this from PHP?


sudo is a bit tricky but phpseclib, a pure PHP SSH implementation, makes it a ton easier:

<?php
include('Net/SSH2.php');

$sftp = new Net_SSH2('www.domain.tld');
$sftp->login('username', 'password');

echo $sftp->read('username@username:~$');
$sftp->write("sudo ls -la\n");
$output = $sftp->read('#Password:|username@username:~\$#', NET_SSH2_READ_REGEX);
echo $output;
if (preg_match('#Password:#', $lines)) {
    $ssh->write("password\n");
    echo $sftp->read('username@username:~$');
}
?>

I just copy / pasted that from the phpseclib docs actually:

http://phpseclib.sourceforge.net/documentation/net.html#net_ssh_sudo


PHP has a native SSH client (a good tutorial was originally mentioned by another poster) but it requires that you have the authority to install and run libssh2 under Linux. I've never gotten it to work under Windows, but I haven't really tried in a couple of years, so it might be easier than it was.

When I last needed to do something like that I used phpseclib. It is a good, reliable package which has SSH and SFTP support (it is also PHP4 compatible).


Check out the php function exec(). Try setting up a bash script to SSH using public/private keys and do what you need it to do, then just execute the script with exec() in PHP.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号