gpt4 book ai didi

python - 从一行中获取特定的字符串

转载 作者:太空宇宙 更新时间:2023-11-04 05:36:18 25 4
gpt4 key购买 nike

我正在编写一个脚本,从/etc/init.d 文件夹中提取所有服务。我会将详细信息提取到文件中。然后我将搜索一个字符串并提取我需要的服务。但这对我不起作用。有人可以帮助我吗?

我的代码:

import re, ConfigParser, paramiko, xlwt, collections, os

def get_status():
config = ConfigParser.RawConfigParser()
config.read('config.cfg')
component = []
for section in sorted(config.sections(), key=str.lower):
components = dict() #start with empty dictionary for each section
if not config.has_option(section, 'server.user_name'):
continue
env.user = config.get(section, 'server.user_name')
env.password = config.get(section, 'server.password')
host = config.get(section, 'server.ip')
print "Trying to connect to {} server.....".format(section)

with settings(hide('warnings', 'running', 'stdout', 'stderr'),warn_only=True, host_string=host):
try:
files = run('ls -ltr /etc/init.d/')
with open(section + "_tmp"+".txt", "w") as fo:
fo.write(files)
with open(section + "_tmp"+".txt", 'rb') as fo:
strings = ("->")
for line in fo:
if strings in line:
m = re.match('.* nds_([-_a-z0-9]+) ', line)
if m:
component = m.group(1).strip('nds_')
print component
except Exception as e:
print e

我的/etc/init.d 是这样显示的

-rwxr-xr-x. 1 root root 15407 Jan 28  2013 libvirt-guests
-rwxr-xr-x. 1 root root 9964 Apr 9 2014 jexec
lrwxrwxrwx. 1 root root 36 Apr 9 2014 nds_watchdog -> /opt/nds/watchdog/utils/nds_watchdog
lrwxrwxrwx. 1 root root 28 Apr 9 2014 nds_snmp -> /opt/nds/snmp/utils/nds_snmp
lrwxrwxrwx. 1 root root 36 Apr 9 2014 nds_ndsagent -> /opt/nds/ndsagent/utils/nds_ndsagent
lrwxrwxrwx. 1 root root 28 Apr 9 2014 nds_mama -> /opt/nds/mama/utils/nds_mama

我需要以“nds_”开头的完整字符串。例如:在这种情况下,我需要 nds_watchdog、nds_snmp、nds_ndsagent、nds_mama。我相信应该有更好的解决方案来使用 re.有人可以帮助我吗?

显示的输出是:

Trying to connect to Astro server.....
Connected to Astro server
watchdog
mp
agent

最佳答案

您似乎有两个问题。首先,您的正则表达式没有捕获您引用的捕获组 1 中的 nds_。其次,即使您要捕获它,您也会从字符串中显式地剥离nds_

尝试:

m = re.match('.* (nds_[-_a-z0-9]+) ')
...
component = m.group(1)

关于python - 从一行中获取特定的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35486313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com