简体   繁体   English

Python正则表达式只读取/etc/resolv.conf并返回ip地址,认为它几乎就在那里,

[英]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. 我一直在写一个python脚本,我遇到了某个函数的问题,它应该打开/etc/resolv.conf文件,逐行读取并只返回ip地址。 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. 虽然它似乎找到了ip地址,但它并没有告诉我那时只有那个内存的哪个部分有任何想法如何让它告诉我匹配的字符串本身。

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 . re.search返回一个匹配对象 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() . 要获取整个匹配的文本,请使用ip.group(0)ip.group()

Also re.search doesn't throw an exception if there is no match, and instead returns None . 如果没有匹配, re.search也不会抛出异常,而是返回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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM