Electrodog10
Posts: 3
Joined: Fri Jul 26, 2013 10:35 pm

Python CGI running Sudo os.system

Sun Dec 18, 2016 2:37 pm

I'm trying to write a Python CGI script that will execute an executable file in the /usr/local/bin/ folder. It's a compiled C program that is for a legacy tuner. My problem is that the executable file will ONLY run when in sudo because of the libhid library that requires a sudo user.

How can I get this os.system command to run "as sudo" so it works properly?

The code is below. Thanks!

Code: Select all

#!/usr/bin/env python
import cgi
import os
form = cgi.FieldStorage() # instantiate only once!
band = form.getfirst('band', 'empty')
freq = form.getfirst('freq', 'empty')

# Avoid script injection escaping the user input
band = cgi.escape(band)
freq = cgi.escape(freq)

bandLower = band.lower()
sysCommand = ("sudo /usr/local/bin/shark -"+bandLower +" " + freq)
os.system(sysCommand)

print("""\
Content-Type: text/html\n
<html><body>
<p>The submitted command was "%s"</p>
</body></html>
""" % sysCommand)


Electrodog10
Posts: 3
Joined: Fri Jul 26, 2013 10:35 pm

Re: Python CGI running Sudo os.system

Sun Dec 18, 2016 2:47 pm

Also it works if I run it as a regular Python file, so basically I need to give the "user" running the CGI script the same permissions that the pi user has. I'm using lighttpd for server software.
Thanks!

User avatar
DougieLawson
Posts: 39304
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK
Contact: Website Twitter

Re: Python CGI running Sudo os.system

Sun Dec 18, 2016 3:16 pm

The web server runs as uid=www-data, gid=www-data. It's an exceedingly bad idea to give www-data free use of sudo.
Note: Any requirement to use a crystal ball or mind reading will result in me ignoring your question.

Criticising any questions is banned on this forum.

Any DMs sent on Twitter will be answered next month.
All non-medical doctors are on my foes list.

lewiscallaway
Posts: 2
Joined: Sun Jun 01, 2014 8:37 pm

Re: Python CGI running Sudo os.system

Sun Dec 18, 2016 3:22 pm

I know it is bad, but it will be run only on a local network.

How do I give www-data the permissions to execute?

User avatar
DougieLawson
Posts: 39304
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK
Contact: Website Twitter

Re: Python CGI running Sudo os.system

Sun Dec 18, 2016 3:50 pm

Edit your sudoers file with sudo visudo.
Note: Any requirement to use a crystal ball or mind reading will result in me ignoring your question.

Criticising any questions is banned on this forum.

Any DMs sent on Twitter will be answered next month.
All non-medical doctors are on my foes list.

Return to “Python”