Reputation: 522
I am writing a script extract all the services from /etc/init.d folder. I will extract the details to a file. Then i will search for a string and extract the service which i require. But this is not working for me. Can someone help me in this?
My Code:
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
My /etc/init.d shows like this
-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
I require the complete string which starts with 'nds_'. For eg: in this case, i require nds_watchdog, nds_snmp, nds_ndsagent, nds_mama. I am sure there should be better solutions to extract using re. Can someone help me in this?
The output showing is:
Trying to connect to Astro server.....
Connected to Astro server
watchdog
mp
agent
Upvotes: 2
Views: 60
Reputation: 13054
You seem to have two problems. First, your regex isn't capturing the nds_
in the capturing group 1 that you're referencing. Second, you are explicitly strip
ing the nds_
from the string even if you were to capture it.
Try:
m = re.match('.* (nds_[-_a-z0-9]+) ')
...
component = m.group(1)
Upvotes: 1