Using sudo with Python script

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

    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
    

提交回复
热议问题