Skip to content

Instantly share code, notes, and snippets.

@LuD1161
Last active March 23, 2022 07:10
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save LuD1161/bd4ac4377de548990b47b0af8d03dc78 to your computer and use it in GitHub Desktop.
Save LuD1161/bd4ac4377de548990b47b0af8d03dc78 to your computer and use it in GitHub Desktop.
Remove IPs which belong to cloudflare
import sys
import requests
from ipaddress import ip_network, ip_address
def output_valid_ips(ips):
ipvs4 = "https://www.cloudflare.com/ips-v4"
ipvs6 = "https://www.cloudflare.com/ips-v6"
ipranges = requests.get(ipvs4).text.split("\n")[:-1] # removing last trailing space
ipranges += requests.get(ipvs6).text.split("\n")[
:-1
] # removing last trailing space
nets = []
for iprange in ipranges:
nets.append(ip_network(iprange))
valid_ips = []
for ip in ips:
if ip == "": # skip empty line
continue
valid = True
for net in nets:
if ip_address(ip) in net:
valid = False
break
if valid:
valid_ips.append(ip)
return valid_ips
if __name__ == "__main__":
if len(sys.argv) < 3:
print(
"""
Usage : python {} input_file_path output_file_path
""".format(
__file__
)
)
sys.exit(1)
file_name, output_file = sys.argv[1], sys.argv[2]
with open(file_name) as f:
ips = f.read().split("\n")
valid_ips = output_valid_ips(ips)
with open(output_file, "w") as f:
for ip in valid_ips[:-1]:
f.write(ip + "\n")
# no new line after last line
f.write(valid_ips[-1])
@cyb3rzest
Copy link

raceback (most recent call last):
File "cleanip.py", line 44, in
valid_ips = output_valid_ips(ips)
File "cleanip.py", line 22, in output_valid_ips
if ip_address(ip) in net:
File "/usr/share/offsec-awae-wheels/ipaddress-1.0.23-py2.py3-none-any.whl/ipaddress.py", line 165, in ip_address
ipaddress.AddressValueError: '136.147.183.180' does not appear to be an IPv4 or IPv6 address. Did you pass in a bytes (str in Python 2) instead of a unicode object?

getting this error. kindly suggest, how to fix this

@Sicks3c
Copy link

Sicks3c commented Mar 20, 2022

@BlckHrtz Use python3 and make sure your IP address has no :PORT just [IP]

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