查询

ssh2_exec()函数—用法及示例

「 在远程服务器上执行命令 」


函数名:ssh2_exec()

适用版本:PHP 5 >= 5.2.0, PECL ssh2 >= 0.9.0

函数描述:ssh2_exec()函数用于在远程服务器上执行命令。

用法:

resource ssh2_exec ( resource $session , string $command [, string $pty [, array $env [, int $width = 80 [, int $height = 25 [, int $width_height_type = SSH2_TERM_UNIT_CHARS ]]]]] )

参数解释:

  • $session: SSH会话的资源标识符,通过ssh2_connect()或ssh2_shell()函数创建。
  • $command: 要在远程服务器上执行的命令。
  • $pty (可选): 伪终端类型,通常为"vanilla"或"vt102"。
  • $env (可选): 一个关联数组,用于设置远程环境变量。
  • $width (可选): 终端宽度,以字符为单位,默认为80。
  • $height (可选): 终端高度,以字符为单位,默认为25。
  • $width_height_type (可选): 终端宽度和高度的单位类型,可选值为SSH2_TERM_UNIT_CHARS(字符单位)或SSH2_TERM_UNIT_PIXELS(像素单位),默认为SSH2_TERM_UNIT_CHARS。

返回值:

  • 成功时返回一个资源标识符,用于进一步处理命令的输入、输出和错误。
  • 失败时返回false。

示例:

// 建立SSH连接
$connection = ssh2_connect('example.com', 22);
ssh2_auth_password($connection, 'username', 'password');

// 执行远程命令
$stream = ssh2_exec($connection, 'ls -l');
stream_set_blocking($stream, true);

// 读取命令输出
$output = stream_get_contents($stream);

// 关闭流和连接
fclose($stream);
ssh2_disconnect($connection);

// 输出命令输出
echo $output;

以上示例中,首先使用ssh2_connect()函数建立SSH连接,然后使用ssh2_auth_password()函数进行身份验证。接下来,使用ssh2_exec()函数执行远程命令,并使用stream_set_blocking()函数设置流为阻塞模式。然后,使用stream_get_contents()函数读取命令的输出内容。最后,使用fclose()函数关闭流和ssh2_disconnect()函数关闭连接。最后,将命令的输出内容输出到页面上。

注意:在使用ssh2_exec()函数执行命令时,需要确保远程服务器已经安装了ssh2扩展。

补充纠错
上一个函数: ssh2_fetch_stream()函数
下一个函数: ssh2_disconnect()函数
热门PHP函数
分享链接