Devin Dixon
Devin Dixon

Reputation: 12403

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?

Upvotes: 0

Views: 628

Answers (1)

neubert
neubert

Reputation: 16802

$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:~$');
?>

Upvotes: 1

Related Questions