我是一名 Java 開發人員,正在嘗試以痛苦的嬰兒步驟學習 HTML。當用戶單擊按鈕或超鏈接時,我希望我的新網站運行一個簡單的 bash shell 腳本(或者更好的是一個 PHP 腳本)。很難找到一個簡單的例子!
我在 StackOverflow 上找到了這個例子。該帖子的第二個答案列出了一個分步示例,其中 HTML 代碼呼叫 PHP 腳本;PHP 腳本呼叫 bash shell 腳本。我試圖在我自己的 Web 服務器上復制該示例。(僅供參考,我正在運行 Apache2 的 Ubuntu 機器上開發。)
這是我的index.html:
<!DOCTYPE html>
<html>
<head></head>
<body>
<form action="/testexec.php">
<input type="submit" value="Run My Script">
</form>
</body>
</html>
為簡單起見,這將創建一個用于呼叫的按鈕,該按鈕testexec.php位于 Apache 主目錄 ( /var/www/html/) 中,該腳本也沒有太多內容:
<?php
shell_exec("/var/www/html/myBashScript.sh");
header('Location: http://10.10.10.10/myBashScript.sh?success=true');
?>
我不確定這些檔案路徑名。嚴格來說,myBashScript.sh是在目錄中/var/www/html/(雖然我想我可以稍后移動它)。當我進行故障排除時,我無法判斷路徑名是否搞砸了。另外,我真的很討厭我必須通過它的 IP 地址來參考服務器(這里,10.10.10.10。)總有一種方法可以說localhost,對吧?
這是 myBashScript.sh:
#!/bin/bash
echo "HELLO WORLD"
...應該這樣做。所以我認為。這兩個腳本都使用chmodandchown和正確設定chgrp,我可以手動運行它們而不會從命令列出錯。
但是當我瀏覽我的網頁并單擊“運行我的腳本”時,我在我的網路瀏覽器中看到了這個:
#!/bin/bash
echo "HELLO WORLD"
In other words, the text of the script is printed to the screen. But I want the script to run and the output of the script to appear on screen. Gah! FWIW, I see no errors entered into the Apache2 error log (/var/log/apache2/error.log), either.
Soooooo... anyone spot my error? Thank you in advance.
uj5u.com熱心網友回復:
我認為這可以在您的網路服務器中啟用 CGI 腳本,將腳本發送到 /cgi-bin/ 檔案夾,將其重命名為 myscript.cgi (記得放適當的 Shebang),設定 0755 權限,正確的所有者/組并放入非常腳本的開頭:
#!/bin/bash
echo "Content-Type: text/html"
... more code...
第一個 echo 行告訴瀏覽器 CGI 腳本的輸出必須呈現為 HTML(您可以根據您的特定需要修改 MIME 型別)。有一個功能示例:
#!/bin/bash
echo -e "Content-type: text/html\r\n\r\n"
echo "<html>"
echo "<head>"
echo "<title>TEST</title>"
echo "</head>"
echo "<body>"
echo "<h1>It Works!, Bash script running as CGI</h1>"
echo "</body>"
echo "</html>"
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/451502.html
