How To Execute SSH Commands Via PHP

Justin picture Justin · Jun 7, 2011 · Viewed 176k times · Source

I am looking to SSH out via PHP. What is the best/most secure way to go about this? I know I can do:

shell_exec("SSH [email protected] mkdir /testing");

Anything better? That feels so 'naughty' :).

Answer

user734976 picture user734976 · Jun 13, 2011

I would use phpseclib, a pure PHP SSH implementation. An example:

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

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

echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');
?>