php远程执行shell,ssh2_exec,ssh2_shell,php远程执行命令

ssh2拓展中ssh2_exec和php自带的exec区别是:
exec执行的命令仅仅在php所部属的服务器上生效
ssh2_exec执行的命令是可以在远程任意一台机器上生效

ssh2_exec实例

<?php
$con = ssh2_connect('192.168.2.20', 22);
ssh2_auth_password($con, 'root', 'password');

$stream = ssh2_exec($con, 'ls -l'); // do some cmd
stream_set_blocking($stream, true);
$output = stream_get_contents($stream);

echo '<pre>';
echo $output;
echo '</pre>';

ssh2_shell实例

$con = ssh2_connect('192.168.2.20', 22);
ssh2_auth_password($con, 'root', 'password');

$cmds[0] = "ls -l";
$cmds[1] = "ls -l /tmp";
$out = '';
$shell = ssh2_shell($con);
usleep(500000); // sleep 0.5 seconds
for ($i = 0; $i < count($cmds); $i ++) {
    fwrite($shell, $cmds[$i] . PHP_EOL);
    usleep(200000); // sleep 0.2 seconds
    while ($buffer = fgets($shell)) {
        flush();
        $out .= $buffer;
    }
}
echo $out;

手册参考
http://www.php.net/manual/en/function.ssh2-exec.php
http://www.php.net/manual/en/function.ssh2-shell.php