Skip to content

Instantly share code, notes, and snippets.

@GithubKillsMyOpsec
Last active August 7, 2024 17:00
Show Gist options
  • Save GithubKillsMyOpsec/7b0679a8a68099a3d7026fd41efcd8e7 to your computer and use it in GitHub Desktop.
Save GithubKillsMyOpsec/7b0679a8a68099a3d7026fd41efcd8e7 to your computer and use it in GitHub Desktop.
Take shodan query and output to txt file for eyewitness/nuclei to process.
import shodan
import time
# Replace with your Shodan API key
SHODAN_API_KEY = 'APIKEYHERE'
# Query to perform on Shodan
query = 'ASN:111111' # Example query, change as needed
# Initialize the Shodan API
api = shodan.Shodan(SHODAN_API_KEY)
# Queries Shodan for a search term and stores results in a list of dictionaries
def query_shodan(term):
print("Running Shodan Query")
templist = []
previous_ip = ""
while True:
try:
# Search Shodan and get a bunch of IP addresses
results = api.search(term, page=1, limit=200)
for result in results['matches']:
if previous_ip == result['ip_str']:
continue
else:
previous_ip = result['ip_str']
temp = {}
temp["Query"] = term
time.sleep(1)
try:
host = api.host(result['ip_str'])
except shodan.exception.APIError as e:
print("No " + result['ip_str'] + ' %s\r' % e)
continue
ip = host.get('ip_str', None)
temp["IP"] = ip
ports = host.get('ports', [])
temp["Ports"] = ports
hostnames = host.get('hostnames', [])
temp["Hostnames"] = hostnames
templist.append(temp)
break
except Exception as e:
print("Exception!")
print('%s\r' % e)
return templist
# Format and save results to a file
def save_to_file(results, filename='eyewitness_queries.txt'):
with open(filename, 'w') as f:
for result in results:
ip = result["IP"]
ports = result["Ports"]
hostnames = result.get("Hostnames", [])
if hostnames:
# Write each hostname on a new line
for hostname in hostnames:
f.write(f"{hostname}\n")
# Write the IP with its ports
for port in ports:
f.write(f"{ip}:{port}\n")
print(f"Results saved to {filename}")
# Perform the Shodan query
results = query_shodan(query)
# Save the formatted results to a file
save_to_file(results)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment