IP正则表达式验证

2024-04-25 11:02:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在尝试验证输入的字符串(在本例中是sys argv[1])。我需要创建一个脚本来遍历日志文件,并将源和目标ip的条目与脚本输入的任何参数相匹配。有效输入的类型是

  • IP或部分IP
  • “any”(字符串,表示给定列中的所有ip地址)。在

到目前为止,我有以下代码。每当我在bash中运行脚本和参数(例如任何随机数或单词/字母表等)时,我都会遇到错误。请告诉我怎样才能修好它们。真的很感激一种方法来验证输入对IP地址reg ex和单词any。在

#!/usr/bin/python

import sys,re

def ipcheck(ip):
    #raw patterns for "any" and "IP":
    ippattern = '([1-2]?[0-9]?[0-9]\.){1,3}([1-2]?[0-9]?[0-9])?'
    anypattern = any
    #Compiled patterns
    cippattern = re.compile(ippattern)
    canypattern = re.compile(any)
    #creating global variables for call outside function    
    global matchip
    global matchany
    #matching the compiled pattern 
    matchip = cippattern.match(ip)
    matchany = canypattern.match(ip)

new = sys.argv[1]
snew = str(new)
print type(snew)
ipcheck(new)

我也试着这样做,但它总是给我错误,有没有可能通过“OR |”操作符将2个参数传递给if循环?我该怎么做?[/b]

^{pr2}$

=============================================================

编辑

我试图在不编译正则表达式的情况下匹配IP。所以我修改了脚本。这导致错误:

错误

user@bt:/home# ./ipregex.py a
<type 'str'>
Traceback (most recent call last):
File "./ipregex.py", line 21, in <module>
ipcheck(new)
File "./ipregex.py", line 15, in ipcheck
matchany = anypattern.match(ip)
AttributeError: 'builtin_function_or_method' object has no attribute 'match'

=============================================================

编辑#2

我能够在一个更简单的代码版本中重现我的错误。我到底做错什么了??????在

#!/usr/bin/python

import sys
import re

def ipcheck(ip):
    anypattern = any
    cpattern = re.compile(anypattern)
    global matchany
    matchany = cpattern.match(ip)
    if matchany:
            print "ip match: %s" % matchany.group()
new = sys.argv[1]
ipcheck(new)

错误

user@bt:/home# ./test.py any
Traceback (most recent call last):
File "./test.py", line 14, in <module>
ipcheck(new)
File "./test.py", line 8, in ipcheck
cpattern = re.compile(anypattern)
File "/usr/lib/python2.5/re.py", line 188, in compile
return _compile(pattern, flags)
File "/usr/lib/python2.5/re.py", line 237, in _compile
raise TypeError, "first argument must be string or compiled pattern"
TypeError: first argument must be string or compiled pattern

Tags: inpyiprenewmatch错误sys
2条回答

此正则表达式可能更好:

((([1-2]?[0-9]?[0-9]\.){1,3}([1-2]?[0-9]?[0-9])?)|any)

它将匹配以下内容:

^{pr2}$

您的正则表达式将遇到上述问题,因为它与0不匹配。在

编辑:

我错过了关于匹配any的部分。在

这个正则表达式将匹配一些无效的地址,但是如果您只是在搜索日志文件,这应该没问题。如果你真的需要精确的话,你可以去看看this link。在

使用re.compile时,对已编译的对象调用match函数:ippattern.match(ip)。另外,要从MatchObject获取匹配的ip,请使用MatchObject.group()。修正了你的一些例子,现在它可以满足你的需要:

#!/usr/bin/python

import sys
import re

def ipcheck(ip):
    ippattern_str = '(([1-2]?[\d]{0,2}\.){1,3}([1-2]?[\d]{0,2})|any)'

    ippattern = re.compile(ippattern_str)
    # ippattern is now used to call match, passing only the ip string
    matchip = ippattern.match(ip)
    if matchip:
        print "ip match: %s" % matchip.group()

if len(sys.argv) > 1:
    ipcheck(sys.argv[1])

一些结果:

^{pr2}$

相关问题 更多 >