【发布时间】:2011-11-18 03:09:17
【问题描述】:
我一直在尝试验证输入的字符串(在本例中为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]
#if (matchip | matchany) :
#print "the ip address is valid"
#else:
#print "Invalid Destination IP"
Error
========================
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 = re.match(anypattern,ip)
File "/usr/lib/python2.5/re.py", line 137, in match
return _compile(pattern, flags).match(string)
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
================================================ ===========
编辑
我试图在不编译正则表达式的情况下匹配 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
【问题讨论】:
-
当 IPv6 越来越相关和需要时,为什么您只匹配 IPv4?
-
我应该解析的日志文件只包含ipv4地址。
-
如果您想匹配所有内容,请将
anypattern = any更改为anypattern = "*"。如果不是,变量any来自哪里?目前,该脚本正在尝试编译内置函数any()。 docs.python.org/library/functions.html#any -
哦,我终于看到了!我不敢相信我将内置函数名称与变量混合在一起。我将 anypattern = any 转换为 anypattern = 'any' (因为我想搜索确切的字符串 - any),它现在可以工作了! :D
标签: python regex validation loops