import subprocess # a function that gathers more information about a given IP Address def gatherInformationOfIpA(ipToCheck): descr = [] country = [] source = [] autSys = [] nothingFound = False descrFound = False countryFound = False sourceFound = False # execute 'whois' on the command line and save output to t t = subprocess.run(['whois', ipToCheck], stdout=subprocess.PIPE) # save generated output of shell command to a file with open("output.txt", "w") as output: output.write(t.stdout.decode('utf-8')) # parse information, like Description, Country, Source and if found the ASN with open("output.txt", "r", encoding="utf-8", errors='replace') as ripeDb: ipInfos = [line.split() for line in ripeDb if line.strip()] for i, row in enumerate(ipInfos): if any("inetnum" in s for s in row): if ipToCheck >= row[1] and ipToCheck <= row[3]: for local in range(1, 20): if ("descr:" in ipInfos[i + local]) and not descrFound: descr.extend(ipInfos[i + local][1:]) descrFound = True continue if ("country:" in ipInfos[i + local]) and not countryFound: country.extend(ipInfos[i + local][1:]) countryFound = True continue if ("source:" in ipInfos[i + local]) and not sourceFound: source.extend(ipInfos[i + local][1:]) sourceFound = True break if any("origin" in s for s in row): autSys.extend(row[1:]) break if not descrFound or not countryFound or not sourceFound: nothingFound = True # print information (which use of this information is wanted? Output, Returned?) if not nothingFound: print("#############################################") print("More Information about", ipToCheck) print("Description: ", ' '.join(descr) if descr else "unknown") print("Country: ", ' '.join(country) if country else "unknown") print("Source: ", ' '.join(source) if source else "unknown") print("AS Number: ", ' '.join(autSys) if autSys else "unknown") print("#############################################") print("\n") else: print("IP-Address", ipToCheck, "is not assigned by IANA yet\n") # in case it should be stored to a file with open("information.txt", "w") as info: info.write("#############################################\n") info.write("More Information about" + ipToCheck + "\n") info.write("Description: " + ' '.join(descr) + "\n" if descr else "unknown" + "\n") info.write("Country: " + ' '.join(country) + "\n" if country else "unknown" + "\n") info.write("Source: " + ' '.join(source) + "\n" if source else "unknown" + "\n") info.write("AS Number: " + ' '.join(autSys) + "\n" if autSys else "unknown" + "\n") info.write("#############################################\n")