我在ssh2 for php中有很多乐趣。(!)
我正在通过ssh-ing进入localhost(运行ubuntu)进行测试。我已经设法用我的用户名(不是root)连接和验证,并且一些命令(比如'ls'返回一些信息,这很有希望。绝对可以到达某个地方。
我希望接下来要做的是发出'su'命令,然后提供root密码。
我没有收到错误,并且返回了资源,但流中似乎没有数据。 (我有点期待'密码:'提示)。我无法直接使用root密码进行身份验证,因为ssh已禁用该密码。
你觉得“su”有什么理由会带回一些文字吗?
我应该期待'密码:'提示回来吗?
这是我的代码:
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);
}
}
}
}
借鉴http://kevin.vanzonneveld.net/techblog/article/make_ssh_connections_with_php/ 尊重。
我得到的输出是:
okay: logged in...
Resource id #3
after stream_set_blocking
data len: 0
提前感谢您的任何帮助:)
乔
答案 0 :(得分:5)
您应该尝试使用phpseclib - a pure PHP SSH implementation的最新SVN版本。以下是你如何做到这一点:
<?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]');
?>
答案 1 :(得分:2)
也许尝试类似bash -c su
或su root
和bash -c "su root"
的内容?
答案 2 :(得分:0)
您只需在执行“su”命令时附加超级用户密码即可。您可以对代码进行以下修改。
$cmd = "su";
$cmd = "echo '" . $sshPassword . "' | sudo -S " . $cmd;
if (!($stream = ssh2_exec($con, $cmd))) {
...
}