我有一台Centos 7笔记本电脑连接到LAN端口上的设备。尝试登录我的设备并为我的自动化任务执行一些命令。我在Centos 7上安装了python 3.6.4。下面是笔记本电脑上的.py脚本..
#!/usr/local/lib python3.6
import pexpect
import sys
import re
def dologin(child):
# Enter User Name
child.expect ('login:')
child.sendline ('admin')
# Enter Password
child.expect ('Password:')
child.sendline ('123')
return
def doprepcommands(child):
# Enter config prompt
child.expect ('NOS/27179080475072>')
child.sendline ('config')
# Issue command
child.expect ('NOS/27179080475072/DEBUG/Config>')
child.sendline ('show vlan')
child.expect ('NOS/27179080475072/DEBUG/Config>')
child.sendline ('exit')
child.expect ('NOS/27179080475072/DEBUG>')
child.sendline ('exit')
child.expect ('NOS/27179080475072')
child.sendline ('exit')
return
# Spawn the telnet session
child = pexpect.spawn ('telnet 192.168.1.254')
# Display progress on screen
child.logfile = sys.stdout
dologin(child)
doprepcommands(child)
当我运行脚本时,我在IDLE屏幕上观察到下面提到的错误。通过不同博客中的详细信息,我部分理解我的脚本中错误地使用了'sys.stdout'(需要以不同的方式使用python 2.7)和python 3.6)。我也试图找出我调用的函数'dologin(child)','doprepcommands(child)'是否使用了Python 3的正确语法。
我是Python的新手。有人可以帮我解决这个错误吗?
================= RESTART: /home/aricent/Siva/test_debug.py =================
Traceback (most recent call last):
File "/home/Siva/test_debug.py", line 37, in <module>
dologin(child)
File "/home/Siva/test_debug.py", line 8, in dologin
child.expect ('login:')
File "/usr/local/lib/python3.6/site-packages/pexpect/spawnbase.py", line 341, in expect
timeout, searchwindowsize, async_)
File "/usr/local/lib/python3.6/site-packages/pexpect/spawnbase.py", line 369, in expect_list
return exp.expect_loop(timeout)
File "/usr/local/lib/python3.6/site-packages/pexpect/expect.py", line 111, in expect_loop
incoming = spawn.read_nonblocking(spawn.maxread, timeout)
File "/usr/local/lib/python3.6/site-packages/pexpect/pty_spawn.py", line 485, in read_nonblocking
return super(spawn, self).read_nonblocking(size)
File "/usr/local/lib/python3.6/site-packages/pexpect/spawnbase.py", line 179, in read_nonblocking
self._log(s, 'read')
File "/usr/local/lib/python3.6/site-packages/pexpect/spawnbase.py", line 126, in _log
self.logfile.write(s)
TypeError: must be str, not bytes
我通过在不同的博客中进行一些可用的讨论来解决这个问题。我已将'spawn'替换为'spawnu',现在我可以telnet到我的设备并根据需要执行操作。 child = pexpect.spawn('telnet 192.168.1.254')child.logfile = sys.stdout
child = pexpect.spawnu ('telnet 192.168.1.254', logfile=sys.stdout, timeout = None)