Skip to content

Instantly share code, notes, and snippets.

@Kamforka
Last active October 8, 2020 09:35
Show Gist options
  • Save Kamforka/088969a55db25bfc712d291e73ad2b34 to your computer and use it in GitHub Desktop.
Save Kamforka/088969a55db25bfc712d291e73ad2b34 to your computer and use it in GitHub Desktop.
import argparse
import csv
import datetime as dt
import os
import scapy.all as scapy
def check_outdir(outdir):
if not os.path.exists(outdir):
raise argparse.ArgumentTypeError(
"the specified output directory '{}' doesn't exist".format(outdir)
)
if not os.path.isdir(outdir):
raise argparse.ArgumentTypeError(
"the specified output directory '{}' is not a directory".format(outdir)
)
return outdir
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"-t", "--target", required=True, help="Target IP Address/Adresses"
)
parser.add_argument(
"-o", "--outdir", type=check_outdir, help="Output directory of the scan result",
)
args = parser.parse_args()
return args
def scan(target):
arp_req_frame = scapy.ARP(pdst=target)
broadcast_eth_frame = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
broadcast_eth_arp_req_frame = broadcast_eth_frame / arp_req_frame
answered_list = scapy.srp(broadcast_eth_arp_req_frame, timeout=1, verbose=False)[0]
scan_results = []
for answer in answered_list:
client_dict = {"ip": answer[1].psrc, "mac": answer[1].hwsrc}
scan_results.append(client_dict)
return scan_results
def display_result(scan_results):
print(
"-----------------------------------\nIP Address\tMAC Address\n-----------------------------------"
)
for result in scan_results:
print("{}\t{}".format(result["ip"], result["mac"]))
def write_results(scan_results, outdir):
timestamp = dt.datetime.now().strftime("%Y%m%d%H%M")
filename = "scan_result_{}.csv".format(timestamp)
filepath = os.path.join(outdir, filename)
with open(filepath, "w") as fp:
if len(scan_results):
# if there's any scan result, write to the csv
# otherwise just create the empty file
writer = csv.DictWriter(fp, scan_results[0].keys())
writer.writeheader()
writer.writerows(scan_results)
if __name__ == "__main__":
args = get_args()
scan_results = scan(args.target)
if args.outdir:
# store the results in the specified output directory
write_results(scan_results, args.outdir)
else:
# outdir not specified, print results to console
display_result(scan_results)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment