Change to sudo user within a python script

前端 未结 8 1869
挽巷
挽巷 2020-11-29 05:33

I have a problem. I am writing a piece of software, which is required to perform an operation which requires the user to be in sudo mode. running \'sudo python filename.py\'

相关标签:
8条回答
  • 2020-11-29 06:00
    import subprocess
    subprocess.check_output("sudo -i -u " + str(username) + " ls -l", shell=True).decode("utf-8").strip()
    
    0 讨论(0)
  • 2020-11-29 06:07

    You can use setuid to set the users uid. But for obvious security reasons you can only do this if you are root (or the program has suid root rights). Both of these are probably a bad idea.

    In this case you need to sudo rights to run a specific program. In that case just sub to "sudo theprogram" instead.

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