从PHP启动交互式SSH bash会话

时间:2015-12-22 03:50:45

标签: php bash shell

我使用PHP编写常见服务器管理任务的快捷方式(我使用deployer.org,但这不重要)。我想在SSH连接到服务器后添加一个用于启动交互式bash提示的任务。例如,你可以运行" ./ dep ssh" (其中" dep"是PHP脚本),这与运行例如效果相同" ssh user @ server"从终端。有没有办法在PHP中执行此操作?对于上下文,我有大约5台服务器,我经常想要SSH,或读取日志,或复制文件等。所以我想要快捷方式。

我能够得到的最接近的是:

$ph = popen("bash","w");
  while(($line = fgets(STDIN)) !== false){
      fputs($ph,$line);
 }
 pclose($ph);

这允许您向bash发送命令以及从bash发送命令但是您没有看到正常的bash提示或获取标签完成。我需要这样的东西,但所有正常的bash功能都可以正常工作。

3 个答案:

答案 0 :(得分:1)

如果您只是想在网络浏览器中使用SSH,那么您可能正在寻找以下产品之一:

  • Google针对Chrome和Chromium的Secure Shell扩展程序
  • Anyterm
  • Ajaxterm
  • Gate One
  • 的WebMux
  • 的WebShell
  • EC2Box
  • 钥匙箱
  • 钥匙箱-OpenShift
  • Mist.io

您可能希望看一下is a link

答案 1 :(得分:0)

#!/usr/bin/php
# This doesn't work, but it might lead you in the right direction.
<?
$ph = popen("bash","w");

function getCharacter() {
    $cmd = '
        read -n 1 char;
        if [ "$char"==" " ]; then
            echo space
        elif [ "$char"=="\n" ]; then
            echo newline
        else 
            echo "$char"
        fi
    ';
    return trim(shell_exec($cmd));
}

$command = "";

while (false !== ($char = getCharacter())) {
    if ($char === "space") {
        $command .= ' ';
    } elseif ($char === "newline") {
        fputs($ph, $command);
        $command = "";
    } elseif ($char === "\t") {
        # Do something fancy with the `compgen` bash utility.
        echo shell_exec("compgen -d $command");
    } else {
        $command .= $char;
    }
}

不幸的是,它已经迟到了所以我无法完成它= D.这里的主要问题是读取输入(fgets仅在用户输入换行符后发生,因此无法检测&#34; \ t&#34;)。我尝试用read伪造它,但它确实是错误的。

fgetc也无法工作,这需要完成用户输入。

我的下一步是研究tty的工作方式,并尝试以这种方式破解它。但是,当然,您仍然需要做很多工作才能尝试使compgen的输出相关。这将涉及确定要发送给compgen的参数和选项(即,用户输入命令或文件名)。

答案 2 :(得分:-1)

在PHP中查看this ssh2模块,文档为here

这是您连接和执行命令的方法:

<?php

/* Notify the user if the server terminates the connection */
function my_ssh_disconnect($reason, $message, $language) {
  printf("Server disconnected with reason code [%d] and message: %s\n",
         $reason, $message);
}

public function my_exec_cmd($connection, $cmd) {
    if (!($stream = ssh2_exec($connection, $cmd))) {
        throw new Exception('SSH command failed');
    }
    stream_set_blocking($stream, true);
    $data = "";
    while ($buf = fread($stream, 4096)) {
        $data .= $buf;
    }
    fclose($stream);
    return $data;
} 

$methods = array(
  'kex' => 'diffie-hellman-group1-sha1',
  'client_to_server' => array(
    'crypt' => '3des-cbc',
    'comp' => 'none'),
  'server_to_client' => array(
    'crypt' => 'aes256-cbc,aes192-cbc,aes128-cbc',
    'comp' => 'none'));

$callbacks = array('disconnect' => 'my_ssh_disconnect');

$connection = ssh2_connect('shell.example.com', 22, $methods, $callbacks);
if (!$connection){
 die('Connection failed');
}else{

   my_exec_cmd($connection, "ls -la");

}

?>
相关问题