Using sudo with Python script

前端 未结 11 2181
轻奢々
轻奢々 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:10

    sometimes require a carriage return:

    os.popen("sudo -S %s"%(command), 'w').write('mypass\n')
    
    0 讨论(0)
  • 2020-11-22 16:12
    • Use -S option in the sudo command which tells to read the password from 'stdin' instead of the terminal device.

    • Tell Popen to read stdin from PIPE.

    • Send the Password to the stdin PIPE of the process by using it as an argument to communicate method. Do not forget to add a new line character, '\n', at the end of the password.

    sp = Popen(cmd , shell=True, stdin=PIPE)
    out, err = sp.communicate(_user_pass+'\n')   
    
    0 讨论(0)
  • 2020-11-22 16:12

    subprocess.Popen creates a process and opens pipes and stuff. What you are doing is:

    • Start a process sudo -S
    • Start a process mypass
    • Start a process mount -t vboxsf myfolder /home/myuser/myfolder

    which is obviously not going to work. You need to pass the arguments to Popen. If you look at its documentation, you will notice that the first argument is actually a list of the arguments.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 16:13

    I know it is always preferred not to hardcode the sudo password in the script. However, for some reason, if you have no permission to modify /etc/sudoers or change file owner, Pexpect is a feasible alternative.

    Here is a Python function sudo_exec for your reference:

    import platform, os, logging
    import subprocess, pexpect
    
    log = logging.getLogger(__name__)
    
    def sudo_exec(cmdline, passwd):
        osname = platform.system()
        if osname == 'Linux':
            prompt = r'\[sudo\] password for %s: ' % os.environ['USER']
        elif osname == 'Darwin':
            prompt = 'Password:'
        else:
            assert False, osname
    
        child = pexpect.spawn(cmdline)
        idx = child.expect([prompt, pexpect.EOF], 3)
        if idx == 0: # if prompted for the sudo password
            log.debug('sudo password was asked.')
            child.sendline(passwd)
            child.expect(pexpect.EOF)
    return child.before
    
    0 讨论(0)
提交回复
热议问题