How do I capture Password prompt

前端 未结 2 1054
再見小時候
再見小時候 2021-01-27 17:36

I have the following code (updated to include pexpect):

import sys
import subprocess
import pexpect
print \"0\"
ssh = subprocess.Popen(\"ssh -A -t username1@200.         


        
相关标签:
2条回答
  • 2021-01-27 17:58

    With guidance from Johannes Holmberg:

    import pexpect
    
    prompt = "cisco_prompt"
    
    def start_log():
            global child
            child.logfile = open("/tmp/mylog", "w")
    
    def stop_log():
            global child
            f = open('/tmp/mylog', 'r')
            for line in f:
                    cleanedLine = line.strip()
                    if cleanedLine: # is not empty
                            print(cleanedLine)
            f.close()
            child.logfile.close
    
    ssh_cmd = "ssh -A -t username1@200.1.2.3 ssh -A -X username2@10.1.2.3"
    child = pexpect.spawn(ssh_cmd, timeout=30)
    print "Waiting for 1st password prompt"
    child.expect ('password')
    child.sendline ('password1')
    print "Waiting for 2nd password prompt"
    child.expect ('password')
    child.sendline ('password2')
    start_log()
    child.expect (prompt)
    child.sendline ('conf t')
    stop_log()
    start_log()
    child.expect ('(config)')
    stop_log()
    print "Ready for more code"
    child.close
    print "END"
    
    0 讨论(0)
  • 2021-01-27 18:06

    The password prompt isn't written to stdout. You'll need something like pexpect to capture it. This thread has more info: Sending a password over SSH or SCP with subprocess.Popen

    Edit: Regarding your updated pexpect code, first of all, if you read the documentation for subprocess, you'll see that communicate() waits for the process to terminate, that's why your program hangs until you kill the ssh session. And your call to pexpect.spawn looks wrong, it expects a string, not a Popen object. You don't need subprocess at all here.

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