7
\$\begingroup\$

In order to avoid the user having to explicitly prefix a script with sudo or su --command, I wrote the following:

import sys
import os
if os.getuid():
 root = "/usr/bin/sudo"
 if not os.path.exists("/usr/bin/sudo"):
 root = "/bin/su --command"
 command = "{} {}".format(root, sys.argv[0])
 command = command.split()
 retcode = subprocess.call(command)
 if retcode:
 print("something wrong happened")
else:
 action_that_needs_admin_rights()

It feels like a hack to me, so am looking forward to better approaches.

asked May 3, 2011 at 1:18
\$\endgroup\$
0

1 Answer 1

5
\$\begingroup\$

The last time I checked (which admittedly has been a while) all major Linux distributions except Ubuntu have a default setup in which sudo is installed, but not configured to be able to start arbitrary applications. So on those your script will fail.

Apart from that I think it's a bad idea to use split like this. This will break if the python file (or the path to it if it was invoked with a path) contains spaces. I'd do it like this instead:

if sudo:
 root = ["/usr/bin/sudo"]
else:
 root = ["/bin/su", "--command"]
command = root + [ sys.argv[0] ]

A further problem is that you're requiring the script to be marked as executable. I think it'd be a better idea to use sys.executable to get the python interpreter and invoke that.

answered May 3, 2011 at 2:06
\$\endgroup\$
4
  • \$\begingroup\$ What's wrong with requiring the script executable? \$\endgroup\$ Commented May 3, 2011 at 2:21
  • \$\begingroup\$ @Tshepang: It's not wrong as such, it just means that it won't work in cases in which it otherwise would (i.e. in the case where the user invokes the script with python script.py rather than making it executable). \$\endgroup\$ Commented May 3, 2011 at 2:32
  • \$\begingroup\$ Even in that case it should work, because sys.argv[0] is always the script filename. \$\endgroup\$ Commented May 3, 2011 at 8:30
  • 3
    \$\begingroup\$ @Tshepang: Yes, that's the point. sudo filename.py does not work, if the file is not executable. You need to do sudo python filename.py. \$\endgroup\$ Commented May 3, 2011 at 8:40

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.