问题
I tried to parse "passwd" command to my machine with phpseclib but it can't go through the first password typing. Look at the code below.
$ssh->write("
passwd $new_user\n
$new_user_pw\n
$new_user_pw\n
");
$ssh->setTimeout(5);
echo $ssh->read('root@machine:~$');
Output i got is:
Last login: Tue Jun 17 12:23:01 2014 from 109.175.60.43 [root@machine ~]# [root@machine ~]# [root@machine ~]# passwd 8917f498 Changing password for user 8917f498. New password:
Or can I do this with another way?
Thanks
回答1:
If you do passwd on yourself you'll be prompted for the old pw before being allowed to set the new pw. And on my Linux system I wasn't able to do passwd on another user without doing root. That may result in you being for your prompted for your password as well.
As a general rule, the way I found out what the prompt is is by doing $ssh->setTimeout() with an empty $ssh->read() call. eg.
$ssh->enablePTY();
$ssh->exec('sudo passwd testuser');
$ssh->setTimeout(3);
echo $ssh->read();
That outputs Enter new UNIX password:
. So I rewrite my program thusly:
$ssh->enablePTY();
$ssh->exec('sudo passwd testuser');
$ssh->setTimeout(3);
$ssh->read('password:');
$ssh->write("newpw\n");
echo $ssh->read();
That outputs Retype new UNIX password:
. So I then revise my program accordingly:
$ssh->enablePTY();
$ssh->exec('sudo passwd testuser');
$ssh->setTimeout(3);
$ssh->read('password:');
$ssh->write("newpw\n");
$ssh->read('password:');
$ssh->write("newpw\n");
echo $ssh->read();
That outputs passwd: password updated successfully
. Now that I know it works I remove the $ssh->setTimeout(3) and update the last $ssh->read() to get this:
$ssh->enablePTY();
$ssh->exec('sudo passwd testuser');
$ssh->read('password:');
$ssh->write("newpw\n");
$ssh->read('password:');
$ssh->write("newpw\n");
$ssh->read('passwd:');
And that's it! It'll change the password without waiting for six seconds like your version does. That last $ssh->read() may not be necessary though. I'll let you play around with that.
回答2:
Ok, I fixed it.
This code works:
$ssh->enablePTY();
$ssh->exec('passwd $new_user');
echo $ssh->read('password:');
$ssh->write("$new_pw\n");
$ssh->setTimeout(3);
$ssh->write("$new_pw\n");
$ssh->setTimeout(3);
echo $ssh->read('password changed');
回答3:
Using a single liner is a better option. I prefer using this:
$username = 'root';
$password = 'myReallySecurePassword';
$ssh->exec(sprintf('echo "%s" | sudo passwd --stdin %s', $password, $username));
Above will work on most modern Linux distros. If you aren't able to change the password somehow and running an older Linux distro, try this:
$username = 'root';
$password = 'myReallySecurePassword';
$ssh->exec(sprintf('echo -e "%s\n%s" | passwd %s', $password, $password, $username));
来源:https://stackoverflow.com/questions/24269189/parse-passwd-command-with-phpseclib