Aar*_*uch 1 python ssh paramiko python-2.7
有个问题让我头疼了好几天了。我正在使用带有 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)
Run Code Online (Sandbox Code Playgroud)
如果我要打印完整的输出,它将包含发送到路由器的所有内容,但我只想查看 showinterfaces ethernet 0/1\n命令的输出。
任何人都可以帮助解决这个问题吗?
我想问最后一件事。我想过滤变量output并检查是否出现“up”或“down”等字符串,但我似乎无法让它工作,因为输出中的所有内容似乎都在新行上?
例如:
如果我在 for 循环中迭代output变量,我会得到变量中的所有字符,如下所示:
for line in output:
print(line)
Run Code Online (Sandbox Code Playgroud)
我得到这样的输出:
t
e
r
米
我
n
A
我
我
e
n
G
t
H
0
有什么办法解决这个问题吗?
再次,
预先感谢您的任何帮助。
此致,
亚伦·C.
阅读完所有评论后,我做了以下更改:
#!/usr/bin/env python
import paramiko, time
router = 'r2.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')
time.sleep(2)
# Clearing output.
if remote_conn.recv_ready():
output = remote_conn.recv(1000)
# Check interface status.
remote_conn.send('show interfaces ethernet 4/1\n') # I only want output from this command.
time.sleep(2)
# Getting output I want.
if remote_conn.recv_ready():
output = remote_conn.recv(5000)
print(output)
# Test: Check if interface is up.
for line in output.split('\n'):
if 'line protocol is up' in line:
print(line)
Run Code Online (Sandbox Code Playgroud)
现在一切都很好。
感谢您的所有帮助。
此致,
亚伦·C.