使用python3.6.8:
我正在尝试编写启动时网络设备初始配置的脚本。我的脚本在“ip_addr:port”上打开 telnet 连接。连接后,脚本会使用“\n\n”刺激其连接的网络设备(模拟管理员的两个“Enter”输入)。
connection = asyncio.open_connection(
ip_addr,
port,
)
try:
reader, writer = await asyncio.wait_for(connection, 5)
print(f"successfully connected to {ip_addr}:{port}")
writer.write(b'\n\n\n')
Run Code Online (Sandbox Code Playgroud)
一些设备已经配置,我除了“login:”之外,在输入“\n”时显示在读取缓冲区中。但是,如果设备尚未配置,“login:”将不会显示在缓冲区中。因此,我认为我可以使用 wait_for 和 timeout 选项来取消此操作,并继续使用另一个reader.readuntil(...)期待另一个输出。
try:
await asyncio.wait_for(reader.readuntil(b' login: '), 3)
print(f"{ip_addr}:{port} alredy booted")
break
except (asyncio.TimeoutError, OSError):
print('Nope, moving forward')
await reader.readuntil(b'normal setup ?(yes/no)[n]: ')
Run Code Online (Sandbox Code Playgroud)
然而这会引发运行时错误。阅读文档时,我发现如果达到超时,任务就会被取消,那么为什么它不能有另一个协程readuntil()呢?
| 归档时间: |
|
| 查看次数: |
1559 次 |
| 最近记录: |