Our minds cannot repel logic of that magnitude!
Using expect to execute SSH commands in PHP
Okay, so let’s say you want one of your PHP scripts to do something that PHP doesn’t necessarially have access to do – such as removing a file owned by you when PHP runs as nobody. Well, instead of poking a ton of holes in your server’s configuration and leaving yourself wide open to a bunch of exploits and attacks, why not just have the PHP script log in as you to localhost via SSH and then do what you desire? Sounds great, huh? Yeah, sure, PHP has built-in SSH2 functions – but what if you don’t have access to add the extension to your server’s configuration? Simple! Use the built-in PHP function exec and the command-line program expect! As in the example below, we let expect spawn up ssh, let it tell ssh that we accept the host verification crap (remove that if you need to), let it pass the password, and then echo out the result of the command. In this case, the command is ls ~/.
exec("echo 'spawn ssh username@localhost ls ~/; expect \"(yes/no)?\"; sleep 1; send \"yes\\r\"; expect \"password:\"; sleep 1; send \"password\\r\"; expect eof;' | expect",$str); foreach ($str as $strstr) { print_r($strstr); echo "\n\r"; }
Now obviously you do not need to echo out the results if you don’t care. That part is just in this example just so you can see how it works. If you’re doing something like removing a file, you can just run the exec command and then use the built-in PHP functions to check to see if the file was actually removed. Perty nifty, huh?
| Print article | This entry was posted by JonnyFunFun on 4 Apr 2008 at 11:55, and is filed under PHP, Programming. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |
