简体   繁体   English

Net_SSH2无法在PHP中切换用户

[英]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. 我在通过SSH进入linux系统然后尝试从该会话中以其他用户身份登录时遇到问题。 In PHP it always hangs. 在PHP中,它总是挂起。

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. 总而言之,我正在使用一个pem文件连接到服务器。 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. 我可以使用exec来运行命令,但是当我尝试切换用户“ sudo su”时,它将挂在SSH2中,但这可以在常规控制台上使用。 Why does this happen and how can I get around it? 为什么会发生这种情况,我该如何解决?

$ssh->exec() isn't a "regular console". $ ssh-> exec()不是“常规控制台”。 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. 您应该改用$ ssh-> write()/ $ ssh-> read()。 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:~$');
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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