简体   繁体   中英

Net_SSH2 Cannot Switch Users in PHP

I'm having a problem when I SSH into a linux box and then try to login as another user from that session. In PHP it always hangs.

Example:
//Connect to server using pem files
$key = new Crypt_RSA();
$key->loadKey($options['pem_file']);
$ssh = new Net_SSH2($host);
$ssh->login($user, $key);

//This command works
$ssh -> exec("cd /var/www/site1");

//This hangs indefinitely but will work on the command line
$ssh -> exec("sudo suo www-data");

To summarize, I am using a pem file to connect to a server. I can run commands on using the exec but when I try to switch users "sudo su", it will hang in SSH2 but this will work on a regular console. Why does this happen and how can I get around it?

$ssh->exec() isn't a "regular console". It returns the output of the command when the command has finished running. But what if the command doesn't finish?

You should try $ssh->write() / $ssh->read() instead. eg.

An example:

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

$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

echo $ssh->read('username@username:~$');
$ssh->write("cd /var/www/site1\n");
echo $ssh->read('username@username:~$');
$ssh->write("sudo suo www-data\n");
echo $ssh->read('newuser@newuser:~$');
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM