标题:pexpect 使用范例 出处:Felix021 时间:Wed, 31 Oct 2012 10:13:06 +0000 作者:felix021 地址:https://www.felix021.com/blog/read.php?2097 内容: 在shell里头,有些程序(比如ssh)的交互是从pty中读取的数据,直接的重定向无法解决,因此需要用到expect这种东西。不过这货的编译比较麻烦,各种依赖。幸好有个pexpect是纯python的,存档留个记录。 #!/usr/bin/python import sys import pexpect password = 'password' expect_list = ['(yes/no)', 'password:'] p = pexpect.spawn('ssh username@localhost ls') try: while True: idx = p.expect(expect_list) print p.before + expect_list[idx], if idx == 0: print "yes" p.sendline('yes') elif idx == 1: print password p.sendline(password) except pexpect.TIMEOUT: print >>sys.stderr, 'timeout' except pexpect.EOF: print p.before 如果密码错误的话,输出引用 The authenticity of host 'localhost (127.0.0.1)' can't be established. RSA key fingerprint is fe:00:00::00:00:00:00:00:00:00:00:00:00:00:00. Are you sure you want to continue connecting ((yes/no) yes )? yes Warning: Permanently added 'localhost' (RSA) to the list of known hosts. username@localhost's password: password Permission denied, please try again. username@localhost's password: password Permission denied, please try again. username@localhost's password: password Permission denied (publickey,gssapi-with-mic,password). 如果正确,则输出引用 username@localhost's password: password a b bin code Generated by Bo-blog 2.1.0