Skip to content

Instantly share code, notes, and snippets.

@za
Last active July 12, 2023 07:45
Show Gist options
  • Save za/0b1123d029d204a597949589eea189bc to your computer and use it in GitHub Desktop.
Save za/0b1123d029d204a597949589eea189bc to your computer and use it in GitHub Desktop.
Extract IP address from a text file
import ipaddress
import re
import sys
def extract_ip_addresses(lines):
ip_addresses = []
for line in lines:
words = line.split()
for word in words:
word = re.sub('"', " ", word)
word = word.strip()
try:
ip = ipaddress.ip_address(word)
ip_addresses.append(ip)
except ValueError:
pass
return ip_addresses
if __name__ == '__main__':
if len(sys.argv) > 1:
filename = sys.argv[1]
with open(filename, 'r') as file:
lines = file.readlines()
ips = extract_ip_addresses(lines)
for ip in ips:
print(ip)
else:
lines = sys.stdin.readlines()
ips = extract_ip_addresses(lines)
for ip in ips:
print(ip)
@za
Copy link
Author

za commented Jul 11, 2023

Example usage with sample.txt file:

➜  $ python3 extract.py sample.txt 
192.168.2.30
202.205.24.0

@za
Copy link
Author

za commented Jul 11, 2023

Pipeline support:

➜  $ grep ciao voila.csv | python3 extract.py
202.142.99.0
203.188.3.9

with voila.csv

➜  findip head voila.csv 
no, name, description
1, ciao, 202.142.99.0
2, chiko, 202.143.98.1
3, ciao, 203.188.3.9

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment