简体   繁体   中英

Execute a python script from web browser

I have a Linux proxy server (RaspberryPi-3) running on squid . I want to start the squid service using an HTML button on its webpage. With this button, I'm trying to execute a python program to start the squid service:

#!/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. 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.

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.

You added the PHP tag so i assume that you are using in fact PHP as your web scripting language.

There is no need for Python, you can directly execute the command from PHP

First you need enable the www-data user to run the command without 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

shell_exec ("service squid restart")

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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