我正在编写一个脚本从/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
你能包括究竟这是不是为你工作的细节?我不明白这一点。 – BlackVegetable
@BlackVegetable ..我在主要部分 –