#!/usr/bin/env python

##########################################################################################
# www.blueteam.fail                                                                      #
# License: MIT License - do whatever, but don't be a dick                                #
#                                                                                        #
# Script does NMAP scan of each single IP address from the file with given flags.        #
# Output is saved according to '-oA' flag: <input filename>-<ip address>.nmap/.gnmap/.xml#
# Usage: python mass_nmap_scan.py -f "-A -Pn -sTU" -i file_with_ips.txt                  #
##########################################################################################

import os
import argparse


def nmap_scan(ip_addr, flags, output_filename):
    nmap_command = 'nmap' + ' ' + str(flags.rstrip() + ' ' + '-oA ' + output_filename + '-' + ip_addr.rstrip() + ' ' + ip_addr.rstrip())
    print 'Running: ' + nmap_command
    os.system(nmap_command)


def file_digestion(path_to_files, flags):
    for path_to_single_file in path_to_files:
        output_filename = os.path.splitext(os.path.basename(path_to_single_file))[0]
        file_data = open(path_to_single_file, "r")

        for host_ip_addr in file_data:
            nmap_scan(host_ip_addr.strip(), flags, output_filename)

        file_data.close()
        print '###File ' + str(os.path.basename(path_to_single_file)) + ' was digested successfully.###'


def define_action(supplied_vars):
    path_to_files = supplied_vars['i']
    flags_list = supplied_vars['f']
    flags_string = flags_list[0].replace('-oA', '')  # Remove '-oA' flag as it's already included in the nmap command

    if path_to_files:
        file_digestion(path_to_files, flags_string)
    else:
        print 'No file [-i] specified. Please refer to -h.'


def main():
    parser = argparse.ArgumentParser(description='#Mass NMAP scan tool#')
    parser.add_argument('-f', help='NMAP flags in double quotes, e.g.: "-Pn -A -sTU"', metavar='flag', type=str, nargs='+')
    parser.add_argument('-i', help='file with IPs to scan (multiple files are supported)', metavar='file', type=str, nargs='+')
    args = parser.parse_args()

    if args.f:
        define_action(vars(args))
    else:
        print 'No flags specified. Please refer to -h.'


main()
