【发布时间】:2017-02-26 21:55:59
【问题描述】:
我有一个问题让我头疼了好几天。我在 Python 2.7.10 中使用 Paramiko 模块,我想向 Brocade 路由器发出多个命令,但只返回给定命令之一的输出,如下所示:
#!/usr/bin/env python
import paramiko, time
router = 'r1.test.example.com'
password = 'password'
username = 'testuser'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(router, username=username, password=password)
print('Successfully connected to %s' % router)
remote_conn = ssh.invoke_shell()
output = remote_conn.recv(1000)
# Disable paging on Brocade.
remote_conn.send('terminal length 0\n')
# Check interface status.
remote_conn.send('show interfaces ethernet 0/1\n') # I only want output from this command.
time.sleep(2)
output = remote_conn.recv(5000)
print(output)
如果我要打印完整的输出,它将包含发送给路由器的所有内容,但我只想查看 show interfaces ethernet 0/1\n 命令的输出。
谁能帮忙解决这个问题?
我想问的最后一件事。我想过滤output 变量并检查“up”或“down”等字符串的出现,但我似乎无法让它工作,因为输出中的所有内容似乎都在新行上?
例如:
如果我在 for 循环中迭代 output 变量,我会得到变量中的所有字符,如下所示:
for line in output:
print(line)
我得到这样的输出:
t
e
r
米
我
n
一个
l
l
e
n
g
t
h
0
有什么办法吗?
再次,
提前感谢您的帮助。
最好的问候,
亚伦 C.
【问题讨论】:
-
可以说,这可以(应该)缩小——手头的问题根本不是 paramiko 所特有的;您可以运行
output='terminal length 0',然后运行for line in output: print(line),并使用更少的样板来提出相同的问题。
标签: python python-2.7 ssh paramiko