Using sudo with Python script

前端 未结 11 2180
轻奢々
轻奢々 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 15:53
    sudoPassword = 'mypass'
    command = 'mount -t vboxsf myfolder /home/myuser/myfolder'
    p = os.system('echo %s|sudo -S %s' % (sudoPassword, command))
    

    Try this and let me know if it works. :-)

    And this one:

    os.popen("sudo -S %s"%(command), 'w').write('mypass')

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

    Please try module pexpect. Here is my code:

    import pexpect
    remove = pexpect.spawn('sudo dpkg --purge mytool.deb')
    remove.logfile = open('log/expect-uninstall-deb.log', 'w')
    remove.logfile.write('try to dpkg --purge mytool\n')
    if remove.expect(['(?i)password.*']) == 0:
        # print "successfull"
        remove.sendline('mypassword')
        time.sleep(2)
        remove.expect(pexpect.EOF,5)
    else:
        raise AssertionError("Fail to Uninstall deb package !")
    
    0 讨论(0)
  • 2020-11-22 16:04

    Many answers focus on how to make your solution work, while very few suggest that your solution is a very bad approach. If you really want to "practice to learn", why not practice using good solutions? Hardcoding your password is learning the wrong approach!

    If what you really want is a password-less mount for that volume, maybe sudo isn't needed at all! So may I suggest other approaches?

    • Use /etc/fstab as mensi suggested. Use options user and noauto to let regular users mount that volume.

    • Use Polkit for passwordless actions: Configure a .policy file for your script with <allow_any>yes</allow_any> and drop at /usr/share/polkit-1/actions

    • Edit /etc/sudoers to allow your user to use sudo without typing your password.

    All the above allow passwordless root privilege, none require you to hardcode your password. Choose any approach and I can explain it in more detail.

    As for why it is a very bad idea to hardcode passwords, here are a few good links for further reading:

    • http://www.security-faqs.com/why-you-shouldnt-hard-code-your-passwords-when-programming.html
    • https://security.web.cern.ch/security/recommendations/en/password_alternatives.shtml
    • https://security.stackexchange.com/questions/92465/whats-more-secure-hard-coding-credentials-or-storing-them-in-a-database
    • https://blogs.manageengine.com/it-security/passwordmanagerpro/2010/02/17/use-of-hard-coded-credentials-a-dangerous-programming-error-cwe.html
    • https://www.csoonline.com/article/3038302/application-development/hard-coded-passwords-remain-a-key-security-flaw.html
    0 讨论(0)
  • 2020-11-22 16:04

    It works in python 2.7 and 3.8:

    from subprocess import Popen, PIPE
    from shlex import split
    
    proc = Popen(split('sudo -S %s' % command), bufsize=0, stdout=PIPE, stdin=PIPE, stderr=PIPE)
    proc.stdin.write((password +'\n').encode()) # write as bytes
    proc.stdin.flush() # need if not bufsize=0 (unbuffered stdin)
    

    without .flush() password will not reach sudo if stdin buffered. In python 2.7 Popen by default used bufsize=0 and stdin.flush() was not needed.

    For secure using, create password file in protected directory:

    mkdir --mode=700 ~/.prot_dir
    nano ~/.prot_dir/passwd.txt
    chmod 600 ~/.prot_dir/passwd.txt 
    

    at start your py-script read password from ~/.prot_dir/passwd.txt

    with open(os.environ['HOME'] +'/.prot_dir/passwd.txt') as f:
        password = f.readline().rstrip()
    
    0 讨论(0)
  • 2020-11-22 16:06

    To limit what you run as sudo, you could run

    python non_sudo_stuff.py
    sudo -E python -c "import os; os.system('sudo echo 1')"
    

    without needing to store the password. The -E parameter passes your current user's env to the process. Note that your shell will have sudo priveleges after the second command, so use with caution!

    0 讨论(0)
  • I used this for python 3.5. I did it using subprocess module.Using the password like this is very insecure.

    The subprocess module takes command as a list of strings so either create a list beforehand using split() or pass the whole list later. Read the documentation for moreinformation.

    #!/usr/bin/env python
    import subprocess
    
    sudoPassword = 'mypass'
    command = 'mount -t vboxsf myfolder /home/myuser/myfolder'.split()
    
    cmd1 = subprocess.Popen(['echo',sudoPassword], stdout=subprocess.PIPE)
    cmd2 = subprocess.Popen(['sudo','-S'] + command, stdin=cmd1.stdout, stdout=subprocess.PIPE)
    
    output = cmd2.stdout.read.decode()
    
    0 讨论(0)
提交回复
热议问题