美文网首页
通过 SSH 连接执行命令的轻量级包

通过 SSH 连接执行命令的轻量级包

作者: zlchen | 来源:发表于2023-04-22 21:53 被阅读0次

安装

通过composer安装软件包:

composer require spatie/ssh

用法

您可以像这样执行 SSH 命令:

$process = Ssh::create('user', 'example.com')->execute('your favorite command');

它将返回SymfonyProcess的一个实例。

如果你不想等到执行命令完成,你可以调用executeAsync

$process = Ssh::create('user', 'example.com')->executeAsync('your favorite command');

获取命令的结果

检查您的命令是否运行正常

$process->isSuccessful();

这就是您获得输出的方式

$process->getOutput();

运行多个命令

要运行多个命令,请将一个数组传递给 execute 方法。

$process = Ssh::create('user', 'example.com')->execute([
   'first command',
   'second command',
]);

选择一个端口

您可以通过将端口传递给构造函数来选择端口。

$port = 123;

Ssh::create('user', 'host', $port);

或者,您可以使用以下usePort功能:

Ssh::create('user', 'host')->usePort($port);

指定跳转主机

如果使用跳转/代理/堡垒主机,该useJumpHost函数允许您设置跳转主机的详细信息:

Ssh::create('user', 'host')->useJumpHost("$jumpuser@$jumphost:$jumpport");

使用 SSH 多路复用

如果与同一主机建立多个连接,SSH 多路复用可以重复使用一个 TCP 连接。调用useMultiplexing函数来设置控制主选项:

Ssh::create('user', 'host')->useMultiplexing($controlPath, $controlPersist);

// Ssh::create('user', 'host')->useMultiplexing('/home/.ssh/control_masters/%C', '15m');

指定要使用的私钥

您可以使用usePrivateKey指定要使用的 SSH 私钥的路径。

Ssh::create('user', 'host')->usePrivateKey('/home/user/.ssh/id_rsa');

禁用严格的主机密钥检查

默认情况下,启用严格的主机密钥检查。您可以使用禁用严格的主机密钥检查disableStrictHostKeyChecking

Ssh::create('user', 'host')->disableStrictHostKeyChecking();

启用安静模式

默认情况下,安静模式是禁用的。您可以使用启用安静模式enableQuietMode

Ssh::create('user', 'host')->enableQuietMode();

禁用密码验证

默认情况下,密码认证是开启的。您可以使用禁用密码验证disablePasswordAuthentication

Ssh::create('user', 'host')->disablePasswordAuthentication();

上传和下载文件和目录

您可以使用以下方式将文件和目录上传到主机:

Ssh::create('user', 'host')->upload('path/to/local/file', 'path/to/host/file');

或者下载它们:

Ssh::create('user', 'host')->download('path/to/host/file', 'path/to/local/file');

在底层,该过程将使用scp.

修改 Symfony 进程

在幕后,所有命令都将使用SymfonysProcess执行。

Process您可以使用方法配置configureProcess。这是我们禁用超时的示例。

Ssh::create('user', 'host')->configureProcess(fn (Process $process) => $process->setTimeout(null));

立即响应输出

通过将闭包传递给 ,您可以在命令产生输出时得到通知onOutput

Ssh::create('user', 'host')->onOutput(function($type, $line) {echo $line;})->execute('whoami');

每当有输出时,都会使用两个参数调用闭包:

  • type:这可以用于Symfony\Component\Process\Process::OUT常规输出和Symfony\Component\Process\Process::ERR错误输出
  • line: 输出本身

相关文章

网友评论

      本文标题:通过 SSH 连接执行命令的轻量级包

      本文链接:https://www.haomeiwen.com/subject/qahejdtx.html