Using sudo with Python script

前端 未结 11 2282
轻奢々
轻奢々 2020-11-22 15:10

I\'m trying to write a small script to mount a VirtualBox shared folder each time I execute the script. I want to do it with Python, because I\'m trying to learn it for scri

11条回答
  •  渐次进展
    2020-11-22 16:13

    To pass the password to sudo's stdin:

    #!/usr/bin/env python
    from subprocess import Popen, PIPE
    
    sudo_password = 'mypass'
    command = 'mount -t vboxsf myfolder /home/myuser/myfolder'.split()
    
    p = Popen(['sudo', '-S'] + command, stdin=PIPE, stderr=PIPE,
              universal_newlines=True)
    sudo_prompt = p.communicate(sudo_password + '\n')[1]
    

    Note: you could probably configure passwordless sudo or SUDO_ASKPASS command instead of hardcoding your password in the source code.

提交回复
热议问题