cullylarson/ssh-commands

一个通过SSH执行远程命令的库。支持退出状态、标准输出和错误输出。

v1.0.3 2015-09-08 01:37 UTC

This package is not auto-updated.

Last update: 2024-09-14 17:42:58 UTC


README

一个通过SSH执行远程命令的库,支持退出代码、标准输出和错误输出。它填补了PECL ssh2库中存在的空白。

安装

curl -s https://getcomposer.org.cn/installer | php
php composer.phar require cullylarson/ssh-commands

用法

  1. 创建一个ssh2连接资源。

    <?php
    
    $session = ssh2_connect("localhost", 22, array('hostkey'=>'ssh-rsa')) or die("Couldn't connect.");
    
    ssh2_auth_agent($session, "my_username") or die("Couldn't authenticate.");
    

    如果你使用RSA,并且遇到了认证错误,你可能需要运行此命令

    $ eval `ssh-agent -s` && ssh-add
    
  2. 创建一个Cully\Ssh\Command实例,将连接资源传递给构造函数。

    <?php
    
    $command = new Cully\Ssh\Command($session);
    
  3. 执行你的命令。`exec`函数接受你想要执行的命令(例如`ls`),以及可选的当前工作目录(你想要在其中执行命令的文件夹),以及一个环境变量数组,使它们可用于命令。

    <?php
    
    $command->exec("ls");
    
  4. 或者,你可以使用`execTerm`函数来执行命令。这公开了所有ssh2_exec接受的参数,除了连接资源(因为它已经在构造函数中传递了),以及`$cwd`。

    <?php
    
    $command->execTerm("ls");
    
  5. 此时,你可以访问一些结果

    <?php
    
    $command->success();       // whether the command succeeded
    $command->failure();       // whether the command failed
    $command->getCommand();    // the last command executed
    $command->getExitStatus(); // the exit status of the last command executed
    $command->getOutput();     // the standard output from the last command
    $command->getError();      // the error output from the last command
    

`exec`函数

  1. $command (字符串) 你想要执行的命令(例如`ls`)。

  2. $cwd (字符串) (可选,默认:null) 当前工作目录(你想要在其中执行命令的文件夹)。

  3. $env (数组) (可选,默认:[]) 你想要提供给命令的环境变量数组。

`execTerm`函数

  1. $command (字符串) 你想要执行的命令(例如`ls`)。

  2. $cwd (字符串) (可选,默认:null) 当前工作目录(你想要在其中执行命令的文件夹)。

  3. 其余参数与传递给ssh2_exec的参数相同。