簡體   English   中英

從 php 執行 shell 腳本

[英]execute shell script from a php

我正在嘗試在遠程設備上執行一些命令。 我正在使用公鑰和私鑰連接到遠程設備。

在我的服務器中,我只需要輸入:ssh username@distant_device 命令,我就會得到它的結果。 所以我想通過一個 php 頁面來做到這一點。

我嘗試了不同的方法,但對我不起作用。

1 -

 $cmdline = escapeshellcmd("ssh username@distant_device command");
 system($cmdline);

2 - 在服務器中執行 shell 腳本

腳本.sh :

#!/bin/bash

output=$(ssh username@distant_device command)
echo "$output" >> test.txt

exit 0

代碼:

passthru('./script.sh',$result);
echo $result ;

我得到了我的腳本發送的結果,但不是其中的 ssh 命令的結果。 當我直接執行腳本時,我得到了結果。

3-

system ("ssh username@distant_device command > test.txt");
system ("ssh -i /home/nagios/.ssh/id_rsa -o 'StrictHostKeyChecking no' username@distant_device command' > test.txt");

文本文件保持為空

我做錯了什么?

我找到了一個解決方案,這里是:

$host = "ip_address"; 
$port = 22; 
$conn = ssh2_connect($host, $port); 
$username = "username"; 
$pub_key = "/path/to/key/.ssh/id_rsa.pub"; 
$pri_key = "/path/to/key/.ssh/id_rsa"; 
if(ssh2_auth_pubkey_file( 
    $conn, 
    $username, 
    $pub_key, 
    $pri_key)) 
{ 
    echo "Authentication succeeded";
    $stdout_stream = ssh2_exec($conn, 'ping ip_address rapid routing-instance XXXXXXXXX');
    sleep(1);
    stream_set_blocking($stdout_stream, true);
    $stream_out = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDIO);
    echo '<pre>';
    echo stream_get_contents($stream_out);
    echo '</pre>';

} 
else 
{ 
   echo "Authentication failed "; 
} 

例如,您可以使用shell_exec()

$output = shell_exec('./deploy.sh');
echo "<pre>".$output."</pre>";

Php 有一個很好的文檔http://php.net/manual/en/function.shell-exec.php希望它有幫助:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM