I have been writing a python script and I am having a problem with a certain function, its supposed to open the /etc/resolv.conf file, read it line by line and return only the ip addresses. Although it appears to be finding the ip address ,it’s not telling me then only what part of memory there in any idea how to get it to tell me the matching string itself.
Here’s the function:
def get_resolv():
nameservers=[]
rconf = open("/etc/resolv.conf","r")
line = rconf.readline()
while line:
try:
ip = re.search(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b",line)
except:
ip = "none set"
print ip
nameservers.append(ip)
line= rconf.readline()
return nameservers
heres the ouput when called:
None
<_sre.SRE_Match object at 0xb76964b8>
<_sre.SRE_Match object at 0xb7696db0>
The
re.searchis returning a Match Object. This is an object which has a number of attributes which tell you about the match.To get the whole matched text use
ip.group(0)orip.group().Also
re.searchdoesn’t throw an exception if there is no match, and instead returnsNone. So your code should look something like: