从HTML执行shell脚本

时间:2017-06-08 18:32:11

标签: html bash shell

我编写了一个简单的HTML代码,在提交后,它会执行一个bash脚本。 该脚本位于正确的文件夹(cgi-bin)中。 当我在firefox上加载此页面时。它给出了一个错误

/somePATH/cgi-bin/script.sh could not be opened because an unknown error occurred.

是否有关于脚本权限的问题?我试过了:

chmod 777

以下是HTML代码的一部分。

<form action="cgi-bin/script.sh" method="post">
<input type="submit" value="Call my Shell Script">
</form>

编辑: 该脚本基本上只打印日期:

#!/bin/bash    
# get today's date
OUTPUT=$(date)
# script
echo "Content-type: text/html"
echo ""
echo "<html><head><title>Demo</title></head><body>"
echo "Today is $OUTPUT <br>"
echo "You can do anything with this Schell Script"
echo "</body></html>"

2 个答案:

答案 0 :(得分:3)

您可以使用服务器端语言。这对PHP来说相当容易

<?php
 if(isset($_POST['submit']))
 {
   $output=shell_exec('sh /somePATH/cgi-bin/script.sh');
   echo $output;
 }
?>

<form action="" method="post">
<input type="submit" name="submit" value="Call my Shell Script">
</form>

包含所有其他HTML并使用扩展程序.php

保存文件

答案 1 :(得分:1)

以下列出了您可以在httpd.conf中查看的有关CGI的内容:

如果您要加载或不加载CGI模块:

LoadModule cgi_module modules/mod_cgi.so

验证CGI的别名

# ScriptAlias: This controls which directories contain server scripts. 
# ScriptAliases are essentially the same as Aliases, except that
# documents in the target directory are treated as applications and
# run by the server when requested rather than as documents sent to the
# client.  The same rules about trailing "/" apply to ScriptAlias
# directives as to Alias.
#
ScriptAlias /cgi-bin/ "/etc/your_httpd_path/cgi-bin/"

脚本目录的规则:

# "/etc/your_httpd_path/cgi-bin/" should be changed to whatever your ScriptAliased
# CGI directory exists, if you have that configured.
#
<Directory "/etc/your_httpd_path/cgi-bin/">
    AllowOverride All
    Options None
    Require all granted
</Directory>

不同文件扩展名的处理程序(添加.sh)

# AddHandler allows you to map certain file extensions to "handlers":
# actions unrelated to filetype. These can be either built into the server
# or added with the Action directive (see below)
#
# To use CGI scripts outside of ScriptAliased directories:
# (You will also need to add "ExecCGI" to the "Options" directive.)
#
AddHandler cgi-script .cgi .pl .asp .sh

检查环境中是否按预期配置了所有内容。

顺便说一下:不要给脚本777,给apache用户赋予特定权限,找出哪个用户正在运行httpd服务(通常是www-data),并执行以下操作:

# remove extra file permissions for others
chmod o-wx /somePATH/cgi-bin/script.sh
# Define the user of the script (same as the user who runs httpd)
chown www-data  /somePATH/cgi-bin/script.sh