unable to provide password to a process with subprocess [python]

前端 未结 2 919
小鲜肉
小鲜肉 2020-12-12 05:47

I\'m using subprocess to run a script from within python. I tried this

option 1

password = getpass.getpass()
from subprocess import Popen, PIPE, che         


        
相关标签:
2条回答
  • 2020-12-12 06:14

    You should be passing the password as a value to the communicate() function instead of stdin.write(), like so:

    from getpass import getpass
    from subprocess import Popen, PIPE
    
    password = getpass("Please enter your password: ")
    proc = Popen("command option1 option2".split(), stdin=PIPE, stdout=PIPE)
    # Popen only accepts byte-arrays so you must encode the string
    proc.communicate(password.encode())
    
    0 讨论(0)
  • 2020-12-12 06:15

    Here's a very basic example of how to use pexpect for this:

    import sys
    import pexpect
    import getpass
    
    password = getpass.getpass("Enter password:")
    
    child = pexpect.spawn('ssh -l root 10.x.x.x "ls /"')
    i = child.expect([pexpect.TIMEOUT, "password:"])
    if i == 0:
        print("Got unexpected output: %s %s" % (child.before, child.after))
        sys.exit()
    else:
        child.sendline(password)
    print(child.read())
    

    Output:

    Enter password:
    
    bin
    boot
    dev
    etc
    export
    home
    initrd.img
    initrd.img.old
    lib
    lib64
    lost+found
    media
    mnt
    opt
    proc
    root
    run
    sbin
    selinux
    srv
    sys
    tmp
    usr
    var
    vmlinuz
    vmlinuz.old
    

    There are more detailed examples here.

    0 讨论(0)
提交回复
热议问题