我有一个 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";
}
}
}
}
}