简体   繁体   English

从 Web 浏览器执行 python 脚本

[英]Execute a python script from web browser

I have a Linux proxy server (RaspberryPi-3) running on squid .我有一个在squid 上运行的 Linux 代理服务器 (RaspberryPi-3)。 I want to start the squid service using an HTML button on its webpage.我想使用其网页上的 HTML 按钮启动鱿鱼服务。 With this button, I'm trying to execute a python program to start the squid service:使用这个按钮,我试图执行一个 python 程序来启动鱿鱼服务:

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

But from the web page, it is not working.但是从网页上看,它不起作用。

What are the other options to get my squid turned on from the browser?从浏览器打开我的鱿鱼的其他选项是什么?

# 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() 

Write a simple Flask api as above.如上编写一个简单的 Flask api。 On your Html button make a get/post ajax call to this flask url so that your squid will be started by the flask controller.在您的 Html 按钮上,对这个烧瓶网址进行 get/post ajax 调用,以便您的鱿鱼将由烧瓶控制器启动。

Handle exceptions too in the controller在控制器中也处理异常

You can achieve the result by using sub-process.您可以通过使用子流程来实现结果。

import subprocess

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

But when we using sub-process with sudo command means it may ask a password to execute the command.但是当我们将子进程与 sudo命令一起使用时意味着它可能会要求输入密码来执行命令。

You added the PHP tag so i assume that you are using in fact PHP as your web scripting language.您添加了 PHP 标记,因此我假设您实际上使用 PHP 作为您的 Web 脚本语言。

There is no need for Python, you can directly execute the command from PHP不需要Python,直接从PHP执行命令即可

First you need enable the www-data user to run the command without sudo .首先,您需要启用www-data用户以在没有sudo情况下运行命令。

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

Add the following line to the file, then save.将以下行添加到文件中,然后保存。

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

When the correct permission are set than this should fairly simple on the PHP side:当设置正确的权限时,在 PHP 端应该相当简单:

<?php

shell_exec ("service squid restart")

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM