通过 SSH 连接到动态远程服务器并运行命令 - Laravel 5.8

kyo*_*kyo 5 php ssh laravel laravel-5 laravel-5.8

我正在使用 L 5.8,并且我有一个包含 3 个输入的表单

在此输入图像描述

现在,我可以使用此软件包通过 SSH 连接到特定服务器laravelcollective/remote": "~5.8。我需要预先 配置IP、UN、PW 等config/remote.php

'connections' => [
    'production' => [
        'host'      => '1.1.1.1',
        'username'  => 'code',
        'password'  => '8888',
        'key'       => '',
        'keytext'   => '',
        'keyphrase' => '',
        'agent'     => '',
        'timeout'   => 10,
    ],
],
Run Code Online (Sandbox Code Playgroud)

然后,我可以轻松运行任何命令,甚至链接它们

$commands = ['cd /home/code && ./runMe.sh'];
SSH::run($commands, function($line)
{
    echo $line.PHP_EOL;
});
Run Code Online (Sandbox Code Playgroud)

结果

我的门户将连接到该服务器并成功运行该命令,并且我已经验证了它。


现在

我需要从表单输入中读取它。是否可以使用相同的插件并动态设置该文件remote.php

或者

我是否应该开始寻找其他东西,因为这是一条死胡同?

请指教,

NVR*_*VRM 0

此示例需要该包php-ssh2,并提供多种方法以流形式检索远程 shell STDOUT。控制当前机器外壳并获得响应也很棒。

sudo apt install php-ssh2
Run Code Online (Sandbox Code Playgroud)

或者按版本:

sudo apt install php7.4-ssh2
Run Code Online (Sandbox Code Playgroud)

ssh2_exec()和的用法示例ssh2_fetch_stream()

<?php
$ssh = ssh2_connect('192.162.68.212', 22); // Remote address
ssh2_auth_password($ssh, 'root', 'XQA8DCamdEm'); // Credentials
$shell = ssh2_shell($ssh, 'xterm'); // Choose remote shell
$stream = ssh2_exec($ssh, 'cd /home/code && ./runMe.sh'); // Remote command
stream_set_blocking($stream, true); // Wait for multiline output, till EOF
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO); // SSH2_STREAM_STDERR
echo stream_get_contents($stream_out); // Print in real-time
Run Code Online (Sandbox Code Playgroud)

通过使用 flag 可以仅检索错误,这对于仅进行监视而不解析整个输出非常有用SSH2_STREAM_STDERR

要仅从远程PHP 写入字符串,我们可以使用STDERR

fwrite(STDERR, "Some logs, from machine (...)\n"); 
Run Code Online (Sandbox Code Playgroud)

或者我们可以直接在远程 shell 命令中传递错误:

cd /home/code && ./runMe.sh 2>

https://www.php.net/manual/en/ref.ssh2.php