如何过滤命令行输出?

2024-10-01 00:26:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要过滤在网络设备中执行的命令的输出,以便只显示与文本匹配的行,如“10.13.32.34”。 我创建了一个python代码,它提供了命令的所有输出,但我只需要其中的一部分。你知道吗

我使用的是运行在windows10pro上的python3.7.3。你知道吗

下面是我使用的代码,我需要过滤部分,因为我是一个没有基本python编程概念的网络工程师。(直到现在……)

from steelscript.steelhead.core import steelhead
from steelscript.common.service import UserAuth
auth = UserAuth(username='admin', password='password')
sh = steelhead.SteelHead(host='em01r001', auth=auth)
from steelscript.cmdline.cli import CLIMode
sh.cli.exec_command("show connections optimized", mode=CLIMode.CONFIG)
output = (sh.cli.exec_command("show connections optimized"))

Tags: 代码fromimport命令authclishowsh
1条回答
网友
1楼 · 发布于 2024-10-01 00:26:43

我不知道你的输出是什么样的,所以用你问题中的文本作为示例数据。不管怎样,对于一个简单的模式,比如你的问题,你可以这样做:

output = '''\
I need to filter the output of a command executed
in network equipment in order to bring only the
lines that match a text like '10.13.32.34'. I
created a python code that brings all the output
of the command but I need only part of this.

I am using Python 3.7.3 running on a Windows 10
Pro.

The code I used is below and I need the filtering
part because I am a network engineer without the
basic notion of python programming. (till now...)
'''

# Filter the lines of text in output.
filtered = ''.join(line for line in output.splitlines()
                            if '10.13.32.34' in line)

print(filtered)  # -> lines that match a text like '10.13.32.34'. I

通过使用Python的内置正则表达式^{}模块中的^{}函数,可以对更复杂的模式执行类似的操作。使用正则表达式更复杂,但功能非常强大。有许多关于如何使用它们的教程,包括Python自己的文档中名为Regular Expression HOWTO的教程。你知道吗

相关问题 更多 >