Updated 2022-05-21 1
Viewed 5 times
0

Guys I am new to python, and try to extract some info from below "iptables" rule

-A PREROUTING -s 192.168.100.74/32 -p udp -m udp --dport 5161 -j REDIRECT --to-ports 5162

Below is my code

        result = re.search("-A PREROUTING -s (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/32 -p (udp|tcp) -m udp|tcp --dport ([0-9]+) -j REDIRECT --to-ports ([0-9]+)", line)
        if result != None:
            print(result.groups())

However I failed to extract port numbers, so could anyone point out where I did wrong. Thanks sincerely.

('192.168.100.74', 'udp', None, None)

🔴 No definitive solution yet
📌 Solution 1
0

Change the 2nd udp|tcp to a (?:udp|tcp) (non-capturing group) and you get the expected result.

result = re.search(r"-A PREROUTING -s (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/32 -p (udp|tcp) -m (?:udp|tcp) --dport ([0-9]+) -j REDIRECT --to-ports ([0-9]+)", line)
if result != None:
    print(result.groups())

('192.168.100.74', 'udp', '5161', '5162')