首页 > 解决方案 > Python Pexpect 属性错误。'NoneType' 没有属性 'sendline'

问题描述

使用 Pexpect 编写脚本以通过 ssh 进行连接,但它会引发属性错误。

import pexpect
PROMPT = ['# ', '>>> ', '> ', '\$ ', '~# ']
def send_command(child, cmd):
    child.sendline(cmd)
    child.expect(PROMPT)
    print child.before, child.after
def connect(user, host, password):
    ssh_newkey = 'Are you sure you want to continue connecting (yes/no)?'
    connStr = 'ssh ' + user + '@' + host
    child = pexpect.spawn(connStr)
    ret = child.expect([ssh_newkey, 'password:'])
    if ret == 0:
        print '[-] Error Connecting'
        return
    elif ret == 1:
        child.sendline('yes')
        ret = child.expect('password:')
        if ret == 0:
            print '[-] Error Connecting'
            return
    child.sendline(password)
    child.expect(PROMPT)
    return child
def main():
    host = 'test.rebex.net'
    user = 'demo'
    password = 'password'
    child = connect(user, host, password)
    send_command(child, 'cat /etc/shadow | grep root')
if __name__ == '__main__':
    main()

我收到以下错误:

[-] Error Connecting
Traceback (most recent call last):
  File "./bruteSSH.py", line 33, in <module>
    main()
  File "./bruteSSH.py", line 31, in main
    send_command(child, 'cat /etc/shadow | grep root')
  File "./bruteSSH.py", line 6, in send_command
    child.sendline(cmd)
AttributeError: 'NoneType' object has no attribute 'sendline'

我相信这与我的子对象是“NoneType”有关,但我无法确定我做错了什么。

标签: pythonattributesnonetypepexpect

解决方案


首先,您在第 6 行的缩进是错误的。

导致此错误的原因是子对象尚未正确设置并成功连接。

如果这正是您的代码,那么问题是“child.sendline()”在函数外部执行,而 child 是函数“send_command”内部的局部变量,因此全局子变量尚未定义


推荐阅读