通过Apache解析Python程序

1.系统情况

  • Apach2
  • python3
  • ubuntu 18.04

2.更新本地软件包索引

sudo apt update

3.安装 python3

sudo apt install python3
[email protected]:~/pythonCodes$ python3 --version
Python 3.6.8

3.安装 Apache2

sudo apt install apache2

4.查看Apache 服务器状态

sudo systemctl status apache2
 apache2.service - The Apache HTTP Server
   Loaded: loaded (/lib/systemd/system/apache2.service; enabled; vendor preset: enabled)
  Drop-In: /lib/systemd/system/apache2.service.d
           └─apache2-systemd.conf
   Active: active (running) since Thu 2019-09-19 18:57:56 CST; 1h 51min ago
  Process: 26830 ExecStop=/usr/sbin/apachectl stop (code=exited, status=0/SUCCESS)
  Process: 22508 ExecReload=/usr/sbin/apachectl graceful (code=exited, status=0/SUCCESS)
  Process: 26836 ExecStart=/usr/sbin/apachectl start (code=exited, status=0/SUCCESS)
 Main PID: 26840 (apache2)
    Tasks: 56 (limit: 4667)
   CGroup: /system.slice/apache2.service
           ├─26840 /usr/sbin/apache2 -k start
           ├─26841 /usr/sbin/apache2 -k start
           ├─26842 /usr/sbin/apache2 -k start
           └─26843 /usr/sbin/apache2 -k start

9月 19 18:57:56 billhwkxc systemd[1]: Starting The Apache HTTP Server...
9月 19 18:57:56 billhwkxc apachectl[26836]: AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set 
9月 19 18:57:56 billhwkxc systemd[1]: Started The Apache HTTP Server.

5.确保Apache运行后,用浏览器访问本地ip,查看是否正常

正常页面

6.加载CGI模块

sudo a2enmod cgid

加载后重启服务器

sudo systemctl restart apache2

7.CGI默认的目录是:/usr/lib/cgi-bin

测试是否正常

sudo vi /usr/lib/cgi-bin/test.py
#!/usr/bin/env python3
print ("Content-type: text/html\n\n")
print ("Hello CGI\n")

8.修改test.py权限

sudo chmod 705 /usr/lib/cgi-bin/test.py

9.浏览器访问test.py或者curl 测试

 curl http://localhost/cgi-bin/test_script

Hello CGI

10.写好脚本,放到默认路径/usr/lib/cgi-bin下,即可运行成功。如果需要更换路径到:/var/www/html/cgi-enabled

sudo  vi /etc/apache2/conf-available/cgi-enabled.conf
<Directory "/var/www/html/cgi-enabled">
    Options +ExecCGI
    AddHandler cgi-script .cgi .py
</Directory>

11.新建CGI目录 /var/www/html/cgi-enabled,如果新建 /var/www/html/cgi-bin 新目录不生效

sudo mkdir /var/www/html/cgi-enabled

12.加载配置

sudo a2enconf cgi-enabled

13.重启Apache

sudo systemctl restart apache2

14.新建测试脚本index.py

sudo vi /var/www/html/cgi-enabled/index.py
#!/usr/bin/env python3


print ("Content-type: text/html\n\n")
print ("<html>\n<body>")
print ("<div style=\"width: 100%; font-size: 40px; font-weight: bold; text-align: center;\">")
print ("Python Script Test Page")
print ("</div>\n</body>\n</html>")

15.访问index.py

参考:

https://www.server-world.info/en/note?os=Ubuntu_18.04&p=httpd&f=5




0 条评论

发表评论

电子邮件地址不会被公开。 必填项已用*标注