Last active
October 6, 2016 02:11
-
-
Save s4w3d0ff/e0e0e77910d42ad68b0b4646a375504f to your computer and use it in GitHub Desktop.
returns a list of 'Unassigned' ports from iana.org
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os.path | |
from csv import reader as csvreader | |
import json, requests, logging | |
# url for retieving the unregistered portlist | |
IANAURL = 'http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.csv' | |
def getAvailPorts(minport=1024): | |
""" | |
Downloads the current iana.org port assignment csv | |
Sorts the list for 'Unassigned' | |
saves the port list in JSON to a local file | |
returns a list of 'Unassigned' ports | |
""" | |
# check if we have a saved port list | |
if os.path.isfile('ports.json'): | |
with open('ports.json') as f: | |
portList = json.load(f) | |
return portList | |
# download the list | |
else: | |
logging.info("Downloading: '%s'" % IANAURL) | |
logging.info("This could take awhile...") | |
raw = requests.get(IANAURL) | |
reader = csvreader(raw.iter_lines(), delimiter=',') | |
portList = [] | |
logging.info("Generating portList...") | |
for row in reader: | |
if 'Unassigned' in row: | |
if '-' in row[1]: # if port range | |
if int(row[1].split('-')[0]) > minport: | |
for i in range( | |
int(row[1].split('-')[0]), | |
int(row[1].split('-')[1]) | |
): | |
portList.append(i) | |
elif int(row[1]) > minport: | |
portList.append(int(row[1])) | |
logging.info("Found %s 'Unassigned' ports > %s" % ( | |
str(len(portList)), str(minport)) | |
) | |
with open('ports.json', 'w+') as f: | |
json.dump(portList, f, sort_keys=True, indent=4, ensure_ascii=False) | |
return portList | |
if __name__ == "__main__": | |
logging.basicConfig() | |
getAvailPorts() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment