Using sudo with Python script

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

    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()
    

提交回复
热议问题