PHP執行shell腳本或者Bash腳本檔案實體,
system和exec函式可能被組態檔禁用,可以通過修改php組態檔洗掉被禁用的函式,
1.通過system函式執行
使用實體:
<?php
$shell = "dig www.afengblog.com";
echo "<pre>";
system($shell, $status);
echo "</pre>";
//shell命令執行結果和執行回傳的狀態值的對應關系
$shell = "<font color='red'>$shell</font>";
if ($status) {
echo "shell命令{$shell}執行失敗";
} else {
echo "shell命令{$shell}成功執行";
}
?>
運行結果:

2.批量執行Shell命令
為了方便管理,可以將所需執行的命令寫入至sh檔案,然后通過system執行即可,
sh檔案以#!/bin/bash開頭,指示命令解釋器,需要執行的命令每行一個,以;結尾,內容結尾可不帶換行,否則status獲取的是換行執行的結果(即空),if判斷為空值則會輸出命令執行失敗,但實際上結尾換行符以上的命令是實際執行成功的,
#!/bin/bash
dig www.afengblog.com;
dig afengblog.com;
dig cdn.afengblog.com;
可以將shell 值改為:bash dig.sh
dig.sh改為以上sh檔案的相對或絕對路徑
如下:
<?php
$shell = "bash dig.sh";
echo "<pre>";
system($shell, $status);
echo "</pre>";
//注意shell命令的執行結果和執行回傳的狀態值的對應關系
$shell = "<font color='red'>$shell</font>";
if ($status) {
echo "shell命令{$shell}執行失敗";
} else {
echo "shell命令{$shell}成功執行";
}
?>
執行效果如下:

3.通過exec函式執行
shell執行的命令可以根據以上方法自行diy,
使用實體:
<?php
$shell = "bash dig.sh";
exec($shell, $result, $status);
$shell = "<font color='red'>$shell</font>";
echo "<pre>";
if( $status ){
echo "shell命令{$shell}執行失敗";
} else {
echo "shell命令{$shell}成功執行, 結果如下<hr>";
print_r( $result );
}
echo "</pre>";
?>
執行效果如下:

原文地址:https://www.afengblog.com/php-executes-shell-script-or-bash-script.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/523078.html
標籤:PHP
