Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

authentication in python script to run as root

Tags:

python

pygtk

I am doing a project in Linux at system level in Python. So that, I want to know that if i am running my code as a normal user and if i am accessing system files then it should have root permissions for it, then how can i prompt for root password and run further code as superuser. I want to know that, how to run python script as superuser with password prompt for it..

Any help will be appreciated. Thank you in advance..

like image 445
Dnyanesh Gate Avatar asked Mar 07 '11 16:03

Dnyanesh Gate


People also ask

How do I login as root in Python?

Syntax: math. sqrt(x) Parameter: x is any number such that x>=0 Returns: It returns the square root of the number passed in the parameter. Error: When x<0 it does not executes due to a runtime error.

How do I run a Python script Sudo?

From the terminal instead of doing python yourProgram.py , do sudo python yourProgram.py . It will ask for your password so type it and it should run.


1 Answers

The other thing you can do is have your script automatically invoke sudo if it wasn't executed as root:

import os
import sys

euid = os.geteuid()
if euid != 0:
    print "Script not started as root. Running sudo.."
    args = ['sudo', sys.executable] + sys.argv + [os.environ]
    # the next line replaces the currently-running process with the sudo
    os.execlpe('sudo', *args)

print 'Running. Your euid is', euid

Output:

Script not started as root. Running sudo..
[sudo] password for bob:
Running. Your euid is 0

Use sudo -k for testing, to clear your sudo timestamp so the next time the script is run it will require the password again.

like image 198
samplebias Avatar answered Sep 21 '22 13:09

samplebias