从一行获取特定字符串

时间:2016-02-18 15:59:04

标签: python python-2.7

我正在编写一个脚本,从/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 个答案:

答案 0 :(得分:1)

你似乎有两个问题。首先,你的正则表达式没有捕获你正在引用的捕获组1中的nds_。其次,即使你要捕获它,你也明确strip来自字符串的nds_

尝试:

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