我想建立一個ssh腳本在主機上運行多個命令。我的目標是獲得每個命令的輸出。我的目標主機是一個思科路由器,併爲以下腳本執行更多的命令我需要運行它爲我要執行每個命令這不是一個非常優雅的解決方案。PHP SSH多個命令
$cmd = array ('sh run int te 1/1', 'sh run int te 1/2');
for ($i = 0; $i <= 1; $i++) {
$connection = ssh2_connect('10.1.1.1', 22);
ssh2_auth_password($connection, 'user', 'pass');
$stream = ssh2_exec($connection, $cmd[$i]);
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
echo stream_get_contents($stream_out); }
我創建了一個循環,因爲我無法獲得每個命令的輸出相同的流。因爲我猜php是在每個流結束時終止ssh連接。
我想實現的是執行幾個命令並獲取輸出在同一個流(如果posible)。
我在編輯帖子以回答@Melvin Koopmans和@LSerni所提出的要求。
如果我改變代碼作爲sugested(這是someting我也試過)第二個命令返回一個錯誤。這裏是CLI輸出: 腳本改爲:
$cmds = array ('sh run int te 1/1', 'sh run int te 1/2');
$connection = ssh2_connect('10.1.1.1', 22);
ssh2_auth_password($connection, 'user', 'pass');
foreach ($cmds as $cmd) {
$stream = ssh2_exec($connection, $cmd);
stream_set_blocking($stream, true);
$stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO);
echo stream_get_contents($stream_out);}
輸出從CLI
interface TenGigabitEthernet1/1
description trunk
switchport trunk allowed vlan 1,2,3,4,5,6,10
switchport mode trunk
auto qos trust
storm-control broadcast include multicast
storm-control broadcast level 1.00
spanning-tree guard loop
service-policy input AutoQos-4.0-Input-Policy
service-policy output AutoQos-4.0-Output-Policy
ip dhcp snooping trust
end
PHP Warning: ssh2_exec(): Unable to request a channel from remote host in C:\Users\SMS\Downloads\php_scripts\ssh.php on line 13
PHP Warning: stream_set_blocking() expects parameter 1 to be resource, boolean given in C:\Users\SMS\Downloads\php_scripts\ssh.php on line 14
PHP Warning: ssh2_fetch_stream() expects parameter 1 to be resource, boolean given in C:\Users\SMS\Downloads\php_scripts\ssh.php on line 15
PHP Warning: stream_get_contents() expects parameter 1 to be resource, null given in C:\Users\SMS\Downloads\php_scripts\ssh.php on line 16
我只得到第一個命令 「SH運行INT TE 1/1」 輸出。
莫非你不會用「&&」撞擊數組,以便它自動執行一個接一個的所有命令? –