加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > PHP > 正文

如何通过ssh在PHP中执行远程命令?

发布时间:2020-05-25 09:06:02 所属栏目:PHP 来源:互联网
导读:我试图通过ssh在php脚本中执行远程命令,我希望将命令(stdout和stderr)的输出流式传输到原始主机. 我知道在Perl和Ruby中这是可能的.我在php中找不到任何这样的例子. 码: $ip = kssotest.yakabod.net;$user = tester;$pass = kmoon77;$connection = ssh2_conne

我试图通过ssh在php脚本中执行远程命令,我希望将命令(stdout和stderr)的输出流式传输到原始主机.

我知道在Perl和Ruby中这是可能的.我在php中找不到任何这样的例子.

码:

$ip = 'kssotest.yakabod.net';
$user = 'tester';
$pass = 'kmoon77';

$connection = ssh2_connect($ip);
ssh2_auth_password($connection,$user,$pass);
$shell = ssh2_shell($connection,"bash");

$cmd = "echo '[start]';your commands here;echo '[end]'";
$output = user_exec($shell,$cmd);

fclose($shell);

function user_exec($shell,$cmd) {
  fwrite($shell,$cmd . "n");
  $output = "";
  $start = false;
  $start_time = time();
  $max_time = 2; //time in seconds
  while(((time()-$start_time) < $max_time)) {
    $line = fgets($shell);
    if(!strstr($line,$cmd)) {
      if(preg_match('/[start]/',$line)) {
        $start = true;
      }elseif(preg_match('/[end]/',$line)) {
        return $output;
      }elseif($start){
        $output[] = $line;
      }
    }
  }
}

但是当我像这个$php remote.php一样执行它时,我收到一个错误:

PHP Fatal error:  Call to undefined function ssh2_connect() 
in /home/tester/PHP_SSH2/remote.php on line 6

通过ssh在PHP中执行远程命令的最佳方法是什么?

如果由于繁文缛节而无法添加php包,这里有一个简单的类可以解决问题
class ExecuteRemote
{
    private static $host;
    private static $username;
    private static $password;
    private static $error;
    private static $output;

    public static function setup($host,$username=NULL,$password=NULL)
    {
        self::$host = $host;
        self::$username = $username;
        self::$password = $password;
    }

    public static function executeScriptSSH($script)
    {
        // Setup connection string
        $connectionString = self::$host;
        $connectionString = (empty(self::$username) ? $connectionString : self::$username.'@'.$connectionString);

        // Execute script
        $cmd = "ssh $connectionString $script 2>&1";
        self::$output['command'] = $cmd;
        exec($cmd,self::$output,self::$error);

        if (self::$error) {
            throw new Exception ("nError sshing: ".print_r(self::$output,true));
        }

        return self::$output;
    }
}

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读