IPsToHostnames.py
This script takes an input file full of IPs, resolves them, then sorts them alphabetically and case-insensitive.
tip
When the script is done, the output will look like this:
Resolved: HOST1
Resovled: HOST10
If you don't like that, you can run this on the output file:
sed 's/^Resolved: //' OMGNoSMBSigningLOL!.txt
import socket
def read_ips(file_path):
"""Read IPs from the input file."""
with open(file_path, 'r') as file:
return [line.strip() for line in file if line.strip()]
def nslookup(ip):
"""Perform nslookup on an IP address and return the hostname."""
try:
return socket.gethostbyaddr(ip)[0].split('.')[0] # Return the primary hostname only
except socket.herror:
return None # Return None if the IP cannot be resolved
def write_sorted_hostnames(hostnames, output_file):
"""Write sorted hostnames to the output file."""
with open(output_file, 'w') as file:
for hostname in hostnames:
file.write(f"{hostname}\n")
def main():
# Prompt the user for the input and output file names
input_file = input("Enter the path to the input file: ").strip()
output_file = input("Enter the path to the output file: ").strip()
# Read IPs from the input file
ips = read_ips(input_file)
# Perform nslookup on each IP and collect hostnames
hostnames = []
for ip in ips:
hostname = nslookup(ip)
if hostname:
hostnames.append(hostname)
print(f"Resolved: {hostname}")
else:
print(f"Could not resolve IP: {ip}")
# Sort hostnames case-insensitively
hostnames = sorted(hostnames, key=str.lower)
# Write the sorted hostnames to the output file
write_sorted_hostnames(hostnames, output_file)
print(f"Sorted hostnames written to {output_file}")
if __name__ == "__main__":
main()