簡體   English   中英

PHP 如何執行命令並獲取其 output

[英]PHP How to execute a command and get its output

我需要對我的服務器執行命令並在 php 中獲得 output 的結果

<?php
    $socket = fsockopen("ip", 22); 
    ($socket ? null : die("<p>Failed to connect"));
 
    fwrite($socket, " username\n"); 
    fwrite($socket, " password\n");
 
    $command = " netstat -anp | grep :650 | grep ESTABLISHED | wc -l\n";
    fwrite($socket, $command . "\n");
    echo "<pre>$result</pre>";
    
    sleep(1); 
    // Close connection
    fclose($socket);    
?>

在你的服務器上運行?

需要控制台 output? 你可以使用:

exec() 只返回生成的 output 的最后一行。

當命令完成運行時,shell_exec() 返回命令的完整 output。

system() 立即顯示所有 output,用於顯示文本。

對於ssh連接,需要安裝php-ssh2。 然后這段代碼可以工作,但需要一些改進:

$ssh = ssh2_connect($host); //default port is 22
if (false === $ssh) {
    die('connection failed');
}

$auth = @ssh2_auth_password($ssh, $user, $pwd); // with user and password
if (false === $auth) {
    die('authentication failed');
}


$command = "ls\r\n";

$shell=ssh2_shell($ssh, 'xterm');
fwrite( $shell, 'ls'.PHP_EOL);

while (!feof($shell)){
    echo fgets($shell).PHP_EOL; // this return all the lines since the begining of the session
 }

ssh2_disconnect();

或者,如果您在服務器上安裝了 ssh,您可以使用 shell_exec 執行 ssh 命令。

因此,如果您有 ssh 密鑰(或制作它們),請將它們移入項目但移出 webroot

cp ~/.ssh/id_rsa /path/to/script/ssh_keys/id_rsa
cp ~/.ssh/id_rsa.pub /path/to/script/ssh_keys/id_rsa.pub

# make .htaccess (or dont put in webroot)
echo "deny from all" > /path/to/script/ssh_keys/.htaccess

然后你可以做一個像下面這樣的簡單腳本,如果你沒有 ssh 鍵(eek),然后使用密碼:

<?php
// with ssh key
echo `ssh -i ./ssh_keys/id_rsa username@<IP> /bin/bash << EOF
netstat -anp | grep :650 | grep ESTABLISHED | wc -l
EOF`;

// with password (requires passh)
echo `passh -p password ssh username@<IP> /bin/bash << EOF
netstat -anp | grep :650 | grep ESTABLISHED | wc -l
EOF`;

你已經給出了一個硬編碼腳本的例子,我假設它是一個硬編碼腳本,如果不是,並且值或命令是用戶定義的,那么你不應該運行 SSH cmds,因為它的風險太大,而是考慮制作一個 rest API 或使用 RPC。

暫無
暫無

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

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