I've been trying to validate an inputted string (sys argv[1] in this case). I need to create a script that goes through a log file and matches the entries for source and destination ip with any argument input with the script. The kinds of valid inputs are either
an IP or partial ip
"any"(string which means all ip addresses in a given column).
So far I have the following code. Whenever I run the script in bash along with an argument (e.g any random number or word/alphabets etc) I get errors. Please let me know how I can fix them. Really appreciate a way to validate input against the IP address reg ex and the word 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)
Also I tried to do it this way but it kept giving me errors, is it possible to pass 2 arguments to an if loop via the "OR |" operator? How would I do it this way?[/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
==========================================================
EDIT
I was trying to match the IP without compiling the regex. So I modified the script to do so. This resulted in the error:
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 = anypattern.match(ip)
AttributeError: 'builtin_function_or_method' object has no attribute 'match'
==========================================================
EDIT#2
I was able to reproduce my error in a simpler code version. What the heck am i doing wrong??????
#!/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)
ERROR
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
When you use re.compile you call the match function on the compiled object: ippattern.match(ip). Also, to get to matched ip from a MatchObject, use MatchObject.group(). Fixed up your example some and it should now do what you need:
#!/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])
Some results:
[ 19:46 jon#hozbox ~/SO/python ]$ ./new.py 100.
ip match: 100.
[ 19:46 jon#hozbox ~/SO/python ]$ ./new.py 100.1.
ip match: 100.1.
[ 19:46 jon#hozbox ~/SO/python ]$ ./new.py 100.1.55.
ip match: 100.1.55.
[ 19:46 jon#hozbox ~/SO/python ]$ ./new.py 100.1.55.255
ip match: 100.1.55.255
[ 19:47 jon#hozbox ~/SO/python ]$ ./new.py any
ip match: any
[ 19:47 jon#hozbox ~/SO/python ]$ ./new.py foo
[ 19:47 jon#hozbox ~/SO/python ]$
This regular expression might be better:
((([1-2]?[0-9]?[0-9]\.){1,3}([1-2]?[0-9]?[0-9])?)|any)
It will match anything like:
127.0.0.1
127.0.0
127.0
127.
192.168.1.1
any
Your regular expression would have trouble with the above because it doesn't match 0.
Edit:
I had missed the part about matching any.
This regular expression will match a few invalid addresses, however if you are just searching through log files that should be fine. You may wish to check out this link if you really need to be exact.
Related
`
def arduino_connect():
global sock
print("Cihazlar axtarılır....")
nearby_devices = bluetooth.discover_devices()
num = 0
for i in nearby_devices:
num+=1
print(str(num)+":"+bluetooth.lookup_name(i)+" MAC: "+i)
if i=="00:21:13:00:EF:19":
selection = num-1
bd_addr = nearby_devices[selection]
port = 1
print("Sən seçdin:" +bluetooth.lookup_name(bd_addr))
sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
sock.connect((bd_addr,port))
`
Traceback (most recent call last):
File "ordubot.py", line 92, in <module>
test(wake)
File "ordubot.py", line 81, in test
response(voice)
File "ordubot.py", line 57, in response
arduino_connect()
File "ordubot.py", line 38, in arduino_connect
print(str(num)+":"+bluetooth.lookup_name(i)+" MAC: "+i)
TypeError: must be str, not NoneType
This code gives this error, can you please help?
In this code, I want python to connect to the mac address specified by bluetooth, but this code gives an error.
When joining items using the + operator, they have to be of the same type.
That means that if bluetooth.lookup_name(i) returns a result which isn't a string (a NoneType in your case) than the concatenation fails.
You can use format string to print the result anyway -
print(f"{}:{} MAC: {}".format(num, bluetooth.lookup_name(i), i)
This will work even if not all of the arguments of format are strings.
My get_current_mac function:
def get_current_mac(interface):
ifconfig_result = subprocess.check_output(["ifconfig", interface])
mac_address_search_result = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w:\w\w", ifconfig_result)
if mac_address_search_result:
return mac_address_search_result.group(0)
else:
print("[-] Could not read MAC address.")
I am then wanting to print the result to the screen:
options = get_arguments()
current_mac = get_current_mac(options.interface)
print("Current MAC address is: " + str(current_mac))
The entire error is:
Traceback (most recent call last):
File "./MAC_changer.py", line 38, in <module>
current_mac = get_current_mac(options.interface)
File "./MAC_changer.py", line 30, in get_current_mac
mac_address_search_result = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w:\w\w", ifconfig_result)
File "/usr/lib/python3.7/re.py", line 183, in search
return _compile(pattern, flags).search(string)
TypeError: cannot use a string pattern on a bytes-like object
line 38 is: options = get_arguments()
line 30 is: mac_address_search_result = re.search(r"\w\w:\w\w:\w\w:\w\w:\w\w:\w\w", ifconfig_result)
You need to convert a byte-like object into a string, this can be done using decode method:
ifconfig_result = ifconfig_result.decode('utf-8')
In this link you can read more about converting bytes to string
I am currently using pyparsing module to create my own interpreter. My current code is
import pyparsing as pp
# To parse a packet with srcip,dstip,srcmac,dstmac
identifier = pp.Word(pp.alphas,pp.alphanums+'_')
ipfield = pp.Word(pp.nums,max=3)
ipAddr = pp.Combine(ipfield+"."+ipfield+"."+ipfield+"."+ipfield)
hexint = pp.Word(pp.hexnums,exact=2)
macAddr = pp.Combine(hexint+(":"+hexint)*5)
ip = pp.Combine(identifier+"="+ipAddr)
mac = pp.Combine(identifier+"="+macAddr)
pkt = ip & ip & mac & mac
arg = "createpacket<" + pp.Optional(pkt) + ">"
arg.parseString("createpacket<srcip=192.168.1.3dstip=192.168.1.4srcmac=00:FF:FF:FF:FF:00>")
While I run the last line of the code to parse an example string I get an error as follows:
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/dist-packages/pyparsing.py", line 1041, in parseString
raise exc
pyparsing.ParseException: Expected ">" (at char 13), (line:1, col:14)
Can anyone explain the reason for this error?
While I execute the below program with little modification I am getting an error.
import sys,re
match=re.compile(r'aa[0-9]+AB')
while 1 :
line=eval(raw_input('Enter the string to search' 'or' "press 'q' to Quit"))
if line == 'q':
print "you are quit from the program"
break
if match.search(line):
print 'Matched:',line
print pat
print 'found',match.group()
print type(pat)
else:
print "no match"
print type(pat)
Input:
'aa12AB'
O/P:
>>> Matched: aa12AB
<_sre.SRE_Pattern object at 0x02793720>
found
Traceback (most recent call last):
File "C:\Pyth`enter code here`on27\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", line 325, in RunScript
exec codeObject in __main__.__dict__
File "C:\Users\thangaraj\Desktop\python program\UK Training program\New to add labtop\regular exp\Script1.py", line 11, in <module>
print 'found',match.group()
AttributeError: '_sre.SRE_Pattern' object has no attribute 'group'
>>>
You have to assign to a match object:
m = match.search(line)
and then:
m.group()
Why are you using eval? You should use match.search (although you should probably rename the variable from match as usually, the return value of search is called a match) and the return value of search will have a group method, as #Birei wrote.
The following code works as expected if I declare the "line" variable at the beginning of the script. something like ...
s = "Jul 15 12:12:51 whitelist logger: 1|999999999999|id:d9faff7c-4016-4343-b494-37028763bb66 submit date:1307130919 done date:1307130919 stat:DELIVRD err:0|L_VB3_NM_K_P|1373687445|vivnel2|L_VB3_GH_K_P|promo_camp1-bd153424349bc647|1"
When I open a file and loop through lines, the groups attribute does not work. I get an error:AttributeError: 'NoneType' object has no attribute 'groups'
# cat mylast.py
import re
f = open('customer.csv')
for line in f:
logger_re = re.compile(
"logger: ([^ ]+)\
submit date:(\d+)\
done date:(\d+)\
stat:(.+)\
err:(.+)$")
myvalues = logger_re.search(line).groups()
print myvalues
f.close()
Exception:
# python mylast.py
Traceback (most recent call last):
File "mylast.py", line 13, in ?
myvalues = logger_re.search(line).groups()
AttributeError: 'NoneType' object has no attribute 'groups'
Your regular expression is not matching your actual file contents.
As such, logger_re.search(line) returns None.
The problem here is that you indented your regular expression but did not compensate for the extra whitespace:
logger_re = re.compile(
"logger: ([^ ]+)\
submit date:(\d+)\
done date:(\d+)\
stat:(.+)\
err:(.+)$")
Note that the whitespace at the start of the line there matters. Use separate strings (Python will join them at compile time):
logger_re = re.compile(
"logger: ([^ ]+) "
"submit date:(\d+) "
"done date:(\d+) "
"stat:(.+) "
"err:(.+)$")
Your search will return None if no matches were found. You need to check that myvalues is not None before attempting to access groups().