pexpect调用ssh的报错:'NoneType' object has no attribute 'expect'

Steel_Victor Steel_Victor 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
本人初学python,是菜鸟中的菜鸟。今天跑了一个脚本,调用pexpect连接ssh到远端服务器运行命令并返回结果。python版本是2.5.
遇到报错,无法解决。望DX赐教。谢谢!

错误信息(斜体字部分是脚本中定义的部分信息):
ERROR! 1
SSH could not login. Here is what SSH said:

Password: <class 'pexpect.TIMEOUT'>
'NoneType' object has no attribute 'expect'

这个报错是说对象未定义类型?错误应该是发生在第一个if i==0处,但是child已经是由pexpect.spawn生成的对象了,为什么要报错说NoneType?



完整脚本:(来源: http://www.oschina.net/question/12_7583 )

#!/usr/bin/env python
import pexpect
import getpass, os

def ssh_command(user, host, password, command):
ssh_newkey="Are you sure you want to continue connecting"
child = pexpect.spawn ('ssh -l %s %s %s'%(user, host, command))
i=child.expect([pexpect.TIMEOUT, ssh_newkey, 'passowrd: '])
if i==0:
print 'ERROR! 1'
print 'SSH could not login. Here is what SSH said:'
print child.before, child.after
return None
if i==1:
child.sendline('yes')
child.expect('password: ')
i=child.expect([pexpect.TIMEOUT, 'password: '])
if i==0:
print 'ERROR! 2'
print 'SSH could not login. here is what SSH said:'
print child.before, child.after
return None
child.sendline(password)
return child

def main():
host = raw_input('Hostname: ')
user = raw_input('User: ')
password = getpass.getpass()
command = raw_input('Enter the command: ')
child = ssh_command(user, host, password, command)
child.expect(pexpect.EOF)
print child.before

if __name__ == '__main__':
try:
main()
except Exception, e:
print str(e)
# traceback.print_exc()
os._exit(1)

...全文

相关推荐

评论 6
收藏 已收藏
分享
返回顶部
Steel_Victor
脚本语言 37,737 成员 34,208 内容