Php ssh2_exec does not execute su command

I have a lot of fun with ssh2 for php. (!)

I am testing ssh-ing in localhost (running ubuntu). I managed to connect and authenticate with my username (not root), and some commands (for example, "ls" return some information that is promising. Definitely, somewhere.

What I want to do next is issue the command "su" and then specify the root password.

I do not receive an error message and the resource is returned, but there is no data in the stream. (I kind of expect the "Password:" prompt). I cannot authenticate directly with root password because it is disabled for ssh.

Is there a reason why su will come back with some text, what do you think?

Should I expect a Password: request back?

Here is 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 username 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

+4
source share
3 answers

You should try the latest version of SVN phpseclib - a pure PHP SSH implementation - instead. Here's how you handle it:

 <?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]'); ?> 
+5
source

Perhaps try something like bash -c su or su root and bash -c "su root" ?

+2
source

All you have to do is add the superuser password at the time the su command is executed. You can make the following changes to your code.

 $cmd = "su"; $cmd = "echo '" . $sshPassword . "' | sudo -S " . $cmd; if (!($stream = ssh2_exec($con, $cmd))) { ... } 
0
source

All Articles