Python regex read /etc/resolv.conf and return ip address only, think its almost there,
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.search
is 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)
or ip.group()
.
Also re.search
doesn't throw an exception if there is no match, and instead returns None
. So your code should look something like:
ip = re.search(r"\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b",line)
if ip is None:
ip = "none set"
Another way
>>> data=open("/etc/resolv.conf").read().split()
>>> for item in data:
... if len( item.split(".") ) == 4:
... print item
...
192.168.0.1
Python3
def get_resolvers():
"""
if using WSL will access /etc/resolv.conf and parse the host address
:return: str ip address
"""
resolvers = []
try:
with open("/etc/resolv.conf", encoding='utf-8') as resolvconf:
for line in resolvconf.readlines():
line = line.split('#', 1)[0].rstrip()
if 'nameserver' in line:
resolvers.append(line.split()[1])
return resolvers[0] if len(resolvers) > 0 else "127.0.0.1"
except Exception as err:
return "127.0.0.1"
精彩评论