如何捕获密码提示 [英] How do I capture Password prompt

查看:67
本文介绍了如何捕获密码提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码(已更新为包含pexpect):

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.1.2.3 ssh -A -X username2@10.1.2.3",
        shell = True,
        stdout = subprocess.PIPE,
        stderr = subprocess.PIPE).communicate()
print "1"
child = pexpect.spawn(ssh)
print "2"
child.expect ('password')
print "3"
child.sendline ('password2')
print "4"
result = ssh.stdout.readlines()
if result == []:
        error = ssh.stderr.readlines()
        print >>sys.stderr, "ERROR: %s" % error
else:
        print result

当我运行它时,我看到屏幕上显示打印零"和密码"提示.打印One的行永远不会执行,因此以下pexpect代码也不会执行.我可以以用户身份输入密码,但密码会挂起.当我用Ctrl + C杀死它时,然后会出现带有第二个密码提示的第二个登录标语,然后返回到命令提示符.有人可以解释一下如何捕获第一密码提示,以便程序可以发送密码而不是用户吗?另外,有人可以解释为什么我在终止程序之前不得到结果变量吗?

When I run it, I see the Zero printed followed by the Password prompt displayed on the screen. The line that prints One never executes and so the following pexpect code doesn't either. I can enter the password as a user but then it hangs. When I kill it with Ctrl+C, the 2nd login banner with 2nd Password prompt then appears before returning to the command prompt. Can someone please explain how to capture the 1st Password prompt so the program can send the password instead of the user? Also, can someone please explain why I don't get the result variable until I kill the program?

推荐答案

在约翰尼斯·霍尔姆伯格(Johannes Holmberg)的指导下:

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"

这篇关于如何捕获密码提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆