php ssh2_exec not executing 'su' command
I'm having lots of fun with ssh2 for php.(!)
I am testing by ssh-ing into localhost (running ubuntu). I have managed to connect and authenticate with my username( not root ), and some commands (like 'ls' return some info, which is promising. Definitely getting somewhere.
What I want to be able to do next is issue an 'su' command and then give the root password.
I don't get an error, and a resource is returned, but there seems to be no data in the stream. (I'm kind of expecting a 'Password:' prompt). I can't authenticate directly with the root password, because that is disabled for ssh.
Is there any reason why 'su' would return with some text, do you think?
Should I be expecting the 'Password:' prompt back?
Here's my code:
function changeServerPassword( $ip, $port, $sshUser, $sshPassword, $rootPassword, $newRootPassword, $newSSHPassword = false) {
// login to server using $sshUser and $sshPassword
// su as root and enter $rootPassword
// if any of the above steps fail, return with appropriate error message
if (!function_exists("ssh2_connect")) die("function ssh2_connect doesn't exist");
// log in
// Do I have to make sure that port is a number?
if(!($con = ssh2_connect($ip, $port))){
echo "fail: unable to establish connection\n";
} else {
// try to authenticate with user开发者_如何学Pythonname root, password secretpassword
if(!ssh2_auth_password($con, $sshUser, $sshPassword)) {
echo "fail: unable to authenticate\n";
} else {
// alright, we're in!
echo "okay: logged in...<br />";
//
if (!($stream = ssh2_exec($con, "su"))) {
echo "fail: unable to execute command\n";
} else {
echo $stream."<br />";
// collect returning data from command
stream_set_blocking($stream, true);
echo "after stream_set_blocking<br />";
$data = "";
while ($buf = fread($stream,4096)) {
$data .= $buf;
}
echo "data len: " . strlen($data) . "<br />";
echo $data."<br />";
fclose($stream);
}
}
}
}
borrowed from http://kevin.vanzonneveld.net/techblog/article/make_ssh_connections_with_php/ respect.
The output I get is:
okay: logged in...
Resource id #3
after stream_set_blocking
data len: 0
Thanks in advance for any help :)
Joe
You should try the latest SVN version of phpseclib - a pure PHP SSH implementation - instead. Here's how you'd do su with that:
<?php
include('Net/SSH2.php');
$ssh = new Net_SSH2('localhost', 22);
$ssh->login('username', 'password');
$ssh->read('[prompt]');
$ssh->write("su - user\n");
$ssh->read('Password:');
$ssh->write("Password\n");
echo $ssh->read('[prompt]');
?>
Maybe try something like bash -c su
or su root
and bash -c "su root"
?
All you have to do is append your superuser password at the moment you execute the "su" command. You can make the following modification to your code.
$cmd = "su";
$cmd = "echo '" . $sshPassword . "' | sudo -S " . $cmd;
if (!($stream = ssh2_exec($con, $cmd))) {
...
}
精彩评论