+ -
当前位置:首页 → 问答吧 → pexpect调用ssh的报错:'NoneType' object has no attribute 'expect'

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

时间:2011-10-15

来源:互联网

本人初学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)

作者: Steel_Victor   发布时间: 2011-10-15

Python code

#!/usr/bin/env python
#-*- encoding: utf-8 -*-

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
        # 程序执行到这,返回None
        return None        

def main():
    host = raw_input('Hostname: ')
    user = raw_input('User: ')
    password = getpass.getpass()
    command = raw_input('Enter the command: ')
    # 此时child为None值
    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)




希望对楼主有所帮助...

建议楼主,插入代码一定要记得缩进..

作者: userguanguan   发布时间: 2011-10-16