简体   繁体   中英

SSH2 change a user password

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?

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.

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.

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