2016-02-18 48 views
2

我正在編寫一個腳本從/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 
+0

你能包括究竟這是不是爲你工作的細節?我不明白這一點。 – BlackVegetable

+1

@BlackVegetable ..我在主要部分 –

回答

1

你似乎有兩個問題。首先,您的正則表達式不捕獲您正在引用的捕獲組1中的nds_。其次,即使要捕獲它,也要明確strip中的nds_

嘗試:

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

@BlackVegetable中添加了當前輸出...完美。它的作品非常漂亮。謝謝您的幫助。 –

相關問題