SSH2 change a user password

2019-02-28 09:46发布

I've been playing around with SSH and now I need to change a user's password via the PHP's ssh2,

Here's my code:

$stream = ssh2_exec($ssh, 'passwd test1234');
stream_set_blocking($stream, true);
$data = '';
while($buffer = fread($stream, 4096)) {
    $data .= $buffer;
}
fclose($stream);
echo $data."<hr/>";

$stream = ssh2_exec($ssh, 'saulius123');
stream_set_blocking($stream, true);
$data = '';
while($buffer = fread($stream, 4096)) {
    $data .= $buffer;
}
echo $data."<hr/>";
$stream = ssh2_exec($ssh, 'saulius123');
    stream_set_blocking($stream, true);
    $data = '';
    while($buffer = fread($stream, 4096)) {
        $data .= $buffer;
    }
    echo $data."<hr/>";

However this just make's my PHP script hang, any ideas?

2条回答
Root(大扎)
2楼-- · 2019-02-28 09:59

ssh2_exec invokes the command; to send input, you'll need to write to the stream.

That is, $stream gives you access to standard input and standard output. So you'll need to write the password you wish to set using fwrite on $stream before trying to read back the output.

Since you've put the stream in blocking mode, passwd is awaiting your input (the password) at the same time your script is waiting for passwd. As a result, the script hangs.

查看更多
Lonely孤独者°
3楼-- · 2019-02-28 10:13

Personally, I'd use phpseclib, a pure PHP SSH implementation. Example:

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

$key = new Crypt_RSA();
//$key->setPassword('whatever');
$key->loadKey(file_get_contents('privatekey'));

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

echo $ssh->read('username@username:~$');
$ssh->write("ls -la\n");
echo $ssh->read('username@username:~$');
?>

The biggest advantage of it over libssh2 is portability. We use Amazon Web Services were I work and sometimes we move over to new prod servers or dev servers and the most difficult part in setting them up is installing all the PECL extensions and what not.

phpseclib, in contrast, doesn't have any requirements.

查看更多
登录 后发表回答