Skip to content

Instantly share code, notes, and snippets.

@d33tah
Last active September 3, 2021 15:22
Show Gist options
  • Save d33tah/eee067e6baf76910312b95efd128272d to your computer and use it in GitHub Desktop.
Save d33tah/eee067e6baf76910312b95efd128272d to your computer and use it in GitHub Desktop.
A tool that displays which /24 networks portscanned me, hour by hour.
#!/usr/bin/env python2
import subprocess
import datetime
import csv
import collections
import sys
import socket
def get_asns(ips):
d = {}
s = socket.socket()
s.settimeout(3)
s.connect(("whois.cymru.com", 43))
s.send(b"begin\n")
s.send(b"verbose\n")
for ip in ips:
s.send(ip + b"\n")
s.send(b"end\n")
resp = b""
while True:
try:
buf = s.recv(1024)
except socket.timeout:
break
resp += buf
if len(buf) == 0:
s.close()
break
lines = iter(resp.splitlines())
next(lines)
for line in lines:
s = [x.strip() for x in line.rstrip().split(b"|")]
ip = s[1]
del s[1]
d[ip] = s
return d
def main():
p = subprocess.Popen(
["tcpdump", "-l", "--packet-buffered", "-n", "tcp[tcpflags] & (tcp-syn) != 0"],
stdout=subprocess.PIPE,
bufsize=0,
)
last_t = None
d = collections.Counter()
w = csv.writer(sys.stdout)
asn_parameters = ["asn", "asnet", "cc", "reg", "regdate", "asname"]
empty_as_entry = ["" for x in asn_parameters]
w.writerow(["slash24", "port", "timestamp", "num_syns"] + asn_parameters)
for line in p.stdout:
t = datetime.datetime.now().replace(minute=0, second=0, microsecond=0)
if t != last_t:
ips = [x[0] for x in d]
asns = get_asns(ips)
for k in d:
if d[k] > 1:
w.writerow(
list(k) + [str(d[k])] + list(asns.get(k[0], empty_as_entry))
)
last_t = t
d = collections.Counter()
sys.stdout.flush()
k = line.split()[2].split(".")
if k[0] == "192" and k[1] == "168":
continue
k[3] = "0"
net = ".".join(k[:4])
k = [net] + k[4:]
k.append(str(t))
d[tuple(k)] += 1
if __name__ == "__main__":
# print(get_asns([b"8.8.8.8"]))
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment