使用Paramiko进行ssh并运行命令然后解析打印输出

时间:2014-01-06 14:16:43

标签: python parsing paramiko

我正在编写一个ssh到Paramiko设备的脚本,运行命令并解析该命令的输出。我玩了几个解析器,似乎挂断了。这是我输入的代码:

SSH

import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
client.connect('127.0.0.1', username='foobar', password='foobar1')

stdin, stdout, stderr = client.exec_command('foo')
print stdout.read()

client.close()

从运行命令FOO输出示例

   C Processor:12-13-13 09:53:28 -- A Processor Initiated Reset
# Active Alarms:
   12-13-13 09:53:40 -- App Select Required
# Device Settings - Port 1
   MAC Address 00:00:00:00:0A:DF
   IP Address 127.0.0.1
   SubnetMask 155.155.155.0
   AAAA Server Enabled
   AAAA Server IP Pool Start 127.0.0.1
   AAAA Server IP Pool End 127.0.0.1
   AAAA Server Default Gateway 0.0.0.0
# Device Settings - Port 2
   MAC Address 00:00:00:00:0A:E0
   IP Address 127.0.0.1
   SubnetMask 155.155.155.0
   AAAA Server Enabled
   AAAA Server IP Pool Start 127.0.0.1
   AAAA Server IP Pool End 127.0.0.1
   AAAA Server Default Gateway 0.0.0.0
   Default Gateway 0.0.0.0
# Device Settings - Routing Table
   Route #1 - Disabled
   Route #2 - Disabled
   Route #3 - Disabled
   Route #4 - Disabled
   Route #5 - Disabled
   Route #6 - Disabled
   Route #7 - Disabled
   Route #8 - Disabled
   .....(there is another 50 lines of code same format)

如果有人可以指向我的帖子或网站,其中有一些关于如何将其解析为文本文件的输入,那就太棒了。提前谢谢!

1 个答案:

答案 0 :(得分:0)

这应该写入文件

data = stdout.read()

f = open('file.txt', 'w')
f.write(data)

f.close()
client.close()