我使用paramiko登錄設備並運行一些命令,然後僅捕獲相關輸出。代碼的相關部分看起來是這樣的:使用python在文本文件中查找出現第n個詞的實例
stdin, stdout, stderr = ssh.exec_command('show interface')
print stdout.read()
這給出了以下的輸出:
Ethernet interface 0:0
Internet address: 171.182.204.207 netmask 255.255.255.0
Internet address: fe80::2d0:83ff:fe06:4c67 prefixlen 64
MTU size: 1500
Link status: configured to full duplex, 1 gigabit/sec network
Member of the bridge: none
Ethernet interface 0:1
Internet address: fe80::2d0:83ff:fe06:4c66 prefixlen 64
MTU size: 1500
Link status: autosensed to full duplex, 1 gigabit/sec network
Member of the bridge: none
現在出了這一點,我想只有鏈路狀態,所以我這樣做:
stdin, stdout, stderr = ssh.exec_command('show interface')
link = '\n'.join(item for item in stdout.read().splitlines() if 'Link' in item)
print link
,現在我得到這樣的:
Link status: configured to full duplex, 1 gigabit/sec network
Link status: autosensed to full duplex, 1 gigabit/sec network
工作正常。但是,我想要的是在我的列表理解中指定出現次數,這樣我只能得到關鍵字Link的第一次,第二次或第n次出現。
+1,用於確保只有相關內容被讀入內存的選項。 – Amistad