authentication in python script to run as root

后端 未结 2 1835
故里飘歌
故里飘歌 2020-12-03 07:58

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 sho

相关标签:
2条回答
  • 2020-12-03 08:26

    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.

    0 讨论(0)
  • 2020-12-03 08:28
    import os
    euid = os.geteuid() 
    if euid != 0:
      raise EnvironmentError, "need to be root"
      exit()
    

    This won't prompt in the middle of script but would rather force the user to re-run it with sudo or as root

    0 讨论(0)
提交回复
热议问题