running sudo commands with phpseclib PHP library
phpseclib makes running SSH commands easy. Unfortunately, running sudo commands is not easy because ALL the documentation is WRONG (official site, blogs, stackoverflow, etc.). This is what finally worked for me:
$ssh->read('/.*@.*[$|#]/', NET_SSH2_READ_REGEX);
$ssh->write("sudo YOUR COMMAND HERE\n");
$ssh->setTimeout(10);
$output = $ssh->read('/.*@.*[$|#]|.*[pP]assword.*/', NET_SSH2_READ_REGEX);
if (preg_match('/.*[pP]assword.*/', $output)) {
$ssh->write($sudo_password."\n");
$ssh->read('/.*@.*[$|#]/', NET_SSH2_READ_REGEX);
}
$ssh->read('/.*@.*[$|#]/', NET_SSH2_READ_REGEX);
$ssh->write("sudo YOUR COMMAND HERE\n");
$ssh->setTimeout(10);
$output = $ssh->read('/.*@.*[$|#]|.*[pP]assword.*/', NET_SSH2_READ_REGEX);
if (preg_match('/.*[pP]assword.*/', $output)) {
$ssh->write($sudo_password."\n");
$ssh->read('/.*@.*[$|#]/', NET_SSH2_READ_REGEX);
}
Thanks to this post for pointing me in the right direction.
That page on the official site is pretty out of date and not linked to anywhere from the root page. It says the latest version is 0.2.2 when in fact it's 0.3.6.
ReplyDeleteHere's a more up-to-date version:
http://phpseclib.sourceforge.net/ssh/examples.html#sudo,
That said, there don't seem to be too many differences. Mainly just that it's using [pP] instead of P.
That seems to pretty much be what you're script is trying to do but you're doing [P|p] instead of [Pp]. I think the phpseclib example is better tho as I think your example would match |assword whereas phpseclib wouldn't. Not that that's a huge issue I suppose.
Also, I don't think the $ssh->setTimeout(10) that you're doing is necessary.
Good points! I've updated the regex to remove the unnecessary pipe symbol. Also, my timeout was due to my use case where occasionally my sudo command was hanging. I still like this version, though, because the ssh-read regex is more robust.
ReplyDelete