从网络浏览器执行 python 脚本

Execute a python script from web browser

我在 squid 上有一个 Linux 代理服务器 (RaspberryPi-3) 运行。我想使用其网页上的 HTML 按钮启动 squid 服务。使用此按钮,我正在尝试执行 python 程序来启动 squid 服务:

#!/usr/bin/env python
import os
os.system ("sudo service squid restart")

但是从网页上看,它不起作用。

从浏览器打开我的 squid 的其他选项是什么?

# Importing flask module in the project is mandatory 
# An object of Flask class is our WSGI application. 
from flask import Flask 

# Flask constructor takes the name of 
# current module (__name__) as argument. 
app = Flask(__name__) 

# The route() function of the Flask class is a decorator, 
# which tells the application which URL should call 
# the associated function. 
@app.route('/') 
# ‘/’ URL is bound with hello_world() function. 
def start_squid():
    import os
    os.system ("sudo service squid restart")
    return 'Success'

# main driver function 
if __name__ == '__main__': 

    # run() method of Flask class runs the application 
    # on the local development server. 
    app.run() 

如上所述编写一个简单的 Flask api。 在你的 Html 按钮上调用这个烧瓶 url get/post ajax 这样你的鱿鱼就会被烧瓶控制器启动。

在控制器中也处理异常

您可以使用子流程实现结果。

import subprocess

subprocess.call(['sudo', 'squid', 'restart'])

但是当我们使用带有 sudo 命令的 子进程时,意味着它可能会要求输入密码来执行命令。

您添加了 PHP 标签,所以我假设您实际上正在使用 PHP 作为您的网络脚本语言。

不需要Python,可以直接从PHP

执行命令

首先,您需要启用 www-data 用户 运行 没有 sudo 的命令。

sudo visudo  # you edit the /etc/sudoers with this program

将以下行添加到文件中,然后保存。

www-data ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart squid

当设置了正确的权限后,PHP 方面应该相当简单:

<?php

shell_exec ("service squid restart")

参考 shell_exec:https://www.php.net/manual/en/function.shell-exec.php