Skip to content

Instantly share code, notes, and snippets.

@tbhaxor
Created October 3, 2019 19:00
Show Gist options
  • Save tbhaxor/38d97f08228f94ac6073863a04112a9a to your computer and use it in GitHub Desktop.
Save tbhaxor/38d97f08228f94ac6073863a04112a9a to your computer and use it in GitHub Desktop.
Minimal nmap automation script
from nmap import PortScanner, PortScannerError
from argparse import ArgumentParser, RawTextHelpFormatter
from os import path
import os
from socket import gethostbyname
# configuring the argument parsing
parser = ArgumentParser(description="A minimal Nmap Automation Script",
formatter_class=RawTextHelpFormatter)
parser.add_argument("--host", help="host to scan",
metavar="HOST", required=True)
parser.add_argument("--port", help="range of port to scan",
metavar="RANGE", required=True)
parser.add_argument("--detect-os", help="if passed detect the os",
default=False, action="store_true", dest="os")
parser.add_argument("--save", help="filename to save the output",
default=None, metavar="FILENAME")
args = parser.parse_args()
# starting scan
print("[~] Starting Scan on '{}'".format(args.host))
scanner = PortScanner()
print("[!] Option Detect OS is '{}'".format("ON" if args.os else "OFF"))
try:
# check if --detect-os passed
if args.os:
# scan with option -O
result = scanner.scan(hosts=gethostbyname(args.host),
ports=args.port, arguments="-O")
# open the file
if args.save:
file = open(args.save, "w")
# print time elapsed
print("[!] Scan Completed in {} secs".format(
result["nmap"]["scanstats"]["elapsed"]))
# save time elapsed
if args.save:
file.write("Scan Completed in {} secs".format(
result["nmap"]["scanstats"]["elapsed"]))
# print command line
print("[!] Command executed: {}".format(
result["nmap"]["command_line"]))
# save command line
if args.save:
file.write("\nCommand executed: {}".format(
result["nmap"]["command_line"]))
# print live hosts
print("[!] Hosts Alive: {}".format(
result["nmap"]["scanstats"]["uphosts"]))
# save live hosts
if args.save:
file.write("\nHosts Alive: {}".format(
result["nmap"]["scanstats"]["uphosts"]))
# print down hosts
print("[!] Hosts Down: {}".format(
result["nmap"]["scanstats"]["downhosts"]))
# save down hosts
if args.save:
file.write("\nHosts Down: {}".format(
result["nmap"]["scanstats"]["downhosts"]))
# print host details
print("[!] Hosts Details")
# save host details
if args.save:
file.write("\nHosts Details:")
# iterate list of hosts
for host in result["scan"].keys():
# print current host
print("\t[-] Host: {}".format(host))
# save current host
if args.save:
file.write("\n\tHost: {}".format(host))
# print host status
print("\t[-] Status: {} ({})".format(result["scan"][host]
["status"]["state"], result["scan"][host]["status"]["reason"]))
# save host status
if args.save:
file.write("\n\tStatus: {} ({})".format(result["scan"][host]
["status"]["state"], result["scan"][host]["status"]["reason"]))
# print open port
print("\t[-] Open Ports:")
# save open port
if args.save:
file.write("\n\tOpen Ports:")
# iterate ports
for port in result["scan"][host]["tcp"].keys():
# print port number
print("\t\t[*] Port Number: {}".format(port))
# save port number
if args.save:
file.write("\n\t\tPort Number: {}".format(port))
# print status
print("\t\t[*] Status: {} ({})".format(result["scan"][host]["tcp"]
[port]["state"], result["scan"][host]["tcp"][port]["reason"]))
# save status
if args.save:
file.write("\n\t\tStatus: {} ({})".format(result["scan"][host]["tcp"]
[port]["state"], result["scan"][host]["tcp"][port]["reason"]))
# print service name and version
print("\t\t[*] Service: {} ({})".format(result["scan"][host]["tcp"]
[port]["name"], result["scan"][host]["tcp"][port]["version"] if result["scan"][host]["tcp"][port]["version"] else "undefined"))
# save service name and version
if args.save:
file.write("\n\t\tService: {} ({})".format(result["scan"][host]["tcp"]
[port]["name"], result["scan"][host]["tcp"][port]["version"] if result["scan"][host]["tcp"][port]["version"] else "undefined"))
# print new line
print()
# save new line
if args.save:
file.write("\n")
pass
# print os
print("\t[-] Possible OS:")
# save os
if args.save:
file.write("\n\tPossible OS:")
# iterate os matches
for os in result["scan"][host]["osmatch"]:
# print os name
print("\t\t[*] Name: {}".format(os["name"]))
# save os name
if args.save:
file.write("\n\t\tName: {}".format(os["name"]))
# print confidence
print("\t\t[*] Confidence: {}%".format(os["accuracy"]))
# save confidence
if args.save:
file.write("\n\t\tConfidence: {}%".format(os["accuracy"]))
# print new line
print()
# save new line
if args.save:
file.write("\n")
# print new line
print("")
# save new line
if args.save:
file.write("\n")
# close file
if args.save:
file.close()
pass
else:
# scan with option
result = scanner.scan(hosts=gethostbyname(args.host), ports=args.port)
# open the file
if args.save:
file = open(args.save, "w")
# print time elapsed
print("[!] Scan Completed in {} secs".format(
result["nmap"]["scanstats"]["elapsed"]))
# save time elapsed
if args.save:
file.write("Scan Completed in {} secs".format(
result["nmap"]["scanstats"]["elapsed"]))
# print command line
print("[!] Command executed: {}".format(
result["nmap"]["command_line"]))
# save command line
if args.save:
file.write("\nCommand executed: {}".format(
result["nmap"]["command_line"]))
# print live hosts
print("[!] Hosts Alive: {}".format(
result["nmap"]["scanstats"]["uphosts"]))
# save live hosts
if args.save:
file.write("\nHosts Alive: {}".format(
result["nmap"]["scanstats"]["uphosts"]))
# print down hosts
print("[!] Hosts Down: {}".format(
result["nmap"]["scanstats"]["downhosts"]))
# save down hosts
if args.save:
file.write("\nHosts Down: {}".format(
result["nmap"]["scanstats"]["downhosts"]))
# print host details
print("[!] Hosts Details")
# save host details
if args.save:
file.write("\nHosts Details:")
# iterate list of hosts
for host in result["scan"].keys():
# print current host
print("\t[-] Host: {}".format(host))
# save current host
if args.save:
file.write("\n\tHost: {}".format(host))
# print host status
print("\t[-] Status: {} ({})".format(result["scan"][host]
["status"]["state"], result["scan"][host]["status"]["reason"]))
# save host status
if args.save:
file.write("\n\tStatus: {} ({})".format(result["scan"][host]
["status"]["state"], result["scan"][host]["status"]["reason"]))
# print open port
print("\t[-] Open Ports:")
# save open port
if args.save:
file.write("\n\tOpen Ports:")
# iterate ports
for port in result["scan"][host]["tcp"].keys():
# print port number
print("\t\t[*] Port Number: {}".format(port))
# save port number
if args.save:
file.write("\n\t\tPort Number: {}".format(port))
# print status
print("\t\t[*] Status: {} ({})".format(result["scan"][host]["tcp"]
[port]["state"], result["scan"][host]["tcp"][port]["reason"]))
# save status
if args.save:
file.write("\n\t\tStatus: {} ({})".format(result["scan"][host]["tcp"]
[port]["state"], result["scan"][host]["tcp"][port]["reason"]))
# print service name and version
print("\t\t[*] Service: {} ({})".format(result["scan"][host]["tcp"]
[port]["name"], result["scan"][host]["tcp"][port]["version"] if result["scan"][host]["tcp"][port]["version"] else "undefined"))
# save service name and version
if args.save:
file.write("\n\t\tService: {} ({})".format(result["scan"][host]["tcp"]
[port]["name"], result["scan"][host]["tcp"][port]["version"] if result["scan"][host]["tcp"][port]["version"] else "undefined"))
# print new line
print()
# save new line
if args.save:
file.write("\n")
pass
# print new line
print("")
# save new line
if args.save:
file.write("\n")
# close file
if args.save:
file.close()
pass
pass
except PortScannerError as e:
print("[x] {}".format(e.value.split("\n")[0]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment