0

我有一个 SSH 命令,我想在 PHP 中使用 libssh2 执行:

sh -c '
  rm -f /tmp/command.log
  sleep 3 &
  screen -p 0 -X stuff "\
script -a -c \"ls -l\" /tmp/command.log; kill -USR1 $!
"
  wait
  cat /tmp/command.log
'

不过,我似乎无法正确地转义它,所以 SSH 完全按照上面的方式接收它。我需要将它用双引号括起来,这样我也可以在其中获取 PHP 变量(ls -l 将变为 $command)。

我努力了:

"sh -c '
  rm -f /tmp/command.log
  sleep 3 &
  screen -p 0 -X stuff \"\
script -a -c \\"ls -l\\" /tmp/command.log; kill -USR1 $!
\"
  wait
  cat /tmp/command.log
'"

也:

"sh -c '
  rm -f /tmp/command.log
  sleep 3 &
  screen -p 0 -X stuff \"\
script -a -c \\\"ls -l\\\" /tmp/command.log; kill -USR1 $!
\"
  wait
  cat /tmp/command.log
'"

第一个返回 PHP 错误,第二个不运行命令。

整个功能(在摩根王尔德建议的编辑之后):

    function runShellCommand($command, $host, $user, $pass, $port){
        if (!function_exists("ssh2_connect")) die("Fail: function ssh2_connect doesn't exist");
        if(!($con = ssh2_connect($host, $port))){
            return "Unable to establish connection. Is your server offline?";
        } else {
            if(!ssh2_auth_password($con, $user, $pass)) {
                return "Failed to authenticate. Please ensure your server's password matches our records.";
            } else {
                $run = <<<HEREDOC
sh -c '
rm -f /tmp/command.log
sleep 3 &
screen -p 0 -X stuff "\
script -a -c \"touch /root/test234\" /tmp/command.log; kill -USR1 $!
"
wait
cat /tmp/command.log
'
HEREDOC;
                if (!($stream = ssh2_exec($con,  $run ))) {
                    return "Could not run command.";
                } else {
                    stream_set_blocking($stream, true);
                    $data = "";
                    while ($buf = fread($stream,4096)) {
                        $data .= $buf;
                    }
                    fclose($stream);
                    if(empty($data)){
                        return "sh-4.1# $command\n\n";
                    } else {
                        return "sh-4.1# $command\n$data\n";
                    }
                }
            }
        }
    }
4

2 回答 2

1

How about using the HEREDOC string quoting? I haven't tried it, but it works for other use cases.

$command = <<<HEREDOC
sh -c '
rm -f /tmp/command.log
sleep 3 &
screen -p 0 -X stuff "\
script -a -c \"ls -l\" /tmp/command.log; kill -USR1 $!
"
wait
cat /tmp/command.log
'
HEREDOC;

More on that here - http://php.net/manual/en/language.types.string.php

于 2012-12-03T01:22:25.047 回答
0

试试phpseclib,一个纯 PHP SSH 实现。例如。

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

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

echo $ssh->read('username@username:~$');
$ssh->write("rm -f /tmp/command.log\n");
echo $ssh->read('username@username:~$');
$ssh->write("sleep 3 &\n");
echo $ssh->read('username@username:~$');
$ssh->write("screen -p 0 -X stuff \"\
script -a -c \\\"ls -l\\\" /tmp/command.log; kill -USR1 $!
\"");
...
?>
于 2012-12-05T06:51:21.953 回答