python - 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”有关,但我无法确定我做错了什么。
解决方案
首先,您在第 6 行的缩进是错误的。
导致此错误的原因是子对象尚未正确设置并成功连接。
如果这正是您的代码,那么问题是“child.sendline()”在函数外部执行,而 child 是函数“send_command”内部的局部变量,因此全局子变量尚未定义
推荐阅读
- typescript - Mongoose 错误:架构尚未注册
- javascript - 停止连接四的获胜函数再次返回 true 的最佳算法是什么?
- typescript - 键入对象属性装饰器
- ros - 如何将 SVG 图像添加到 Gazebo?
- java - java中用户输入的问题
- php - 查看哪个表影响了另一个表 SQL-Server
- python-3.x - numpy ifft 输出的功率比原始信号大得多
- java - 如何在 Android 中检查手机身份验证用户?
- python - 如何在 C 回调中使用 Pybind11 访问 Python 对象?
- python - Python Selenium - AttributeError:“WebElement”对象没有属性“send_Keys”