#!/bin/bash
import socket
import subprocess
import ipaddress
import nmap
import pexpect
from core.flowcontrol import WriteFileFunction

# Function to parse raw NMAP results into readable format
def reportscan(argument, IP):
	output = " "
	nm = nmap.PortScanner()
	nm.scan(hosts=IP, arguments=argument)
	output += (nm.command_line())
	output +=  ('Host : %s (%s) \n' % (IP, nm[IP].hostname()))
	output += ('State : %s \n' % nm[IP].state())
	for proto in nm[IP].all_protocols():
		output += ('------\n')
		output += ('Protocol : %s\n' % proto)
		lport = nm[IP][proto].keys()
		for port in sorted(lport):
			output+=('port : %s \tstate : %s \tservice : %s\n' % (port, nm[IP][proto][port]['state'], nm[IP][proto][port]['name']))
	print(output)
	return output	

#NMAP Ping / Traceroute
def NmapPingTraceroute (IP_List, directory):
	name = "NmapPingTraceroute"
	output = " "
	nm = nmap.PortScanner()
	output += ("-----Host-Ping-----\n")
	output += ("-----Results-------\n")
	for IP in IP_List:
		nm.scan(hosts= IP, arguments= '-sn -PO[1]')
		host_list = [(x, nm[x]['status']['state']) for x in nm.all_hosts()]
		for host, status in host_list:
			if 'up' in status:
				Ping_Hosts = ('[+][+] {0}:{1} [+][+]\n'.format(host, status))
				Ping_Hosts = str(Ping_Hosts)
				output += Ping_Hosts
				print (Ping_Hosts)
	print (output)
	for IP in IP_List:
		child = pexpect.spawnu("traceroute "+IP )
		for line in child:
			print (line)
			line = str(line)
			output += line
	WriteFileFunction(output,directory,name)

#NMAP full port Scan
def NmapFullPortScan (IP_List, directory):
	name = "NmapFullPortScan"
	output = " "
	nm = nmap.PortScanner()
	argument = "-A -T4 -sS -sU -p0-65535"
	print (IP_List)
	for IP in IP_List:
		print ("\n" + IP)
		output += reportscan(argument, IP)
	WriteFileFunction(output,directory,name)

#NMAP Large Network Scan
def BaselineLargeNetworks(IP_List,directory):
	name = "BaselineLargeNetworks"
	output = " "
	nm = nmap.PortScanner()	
	argument = ("-Pn -sU --top-ports=500 -sT T:0-65535 -PO[1]")
	for IP in IP_List:
		print ("\n" + IP)
		output += reportscan(argument, IP)
	WriteFileFunction(output,directory,name)

#Checks for dual homed systems for pivoting purposes 
def DualHomedSystems(IP_List,directory):
	name = "DualHomedSystems"
	output = " "
	nm = nmap.PortScanner()
	argument = "-Pn -p 445,443 --script duplicates nbstat,ssl-cert"
	print (argument)
	for IP in IP_List:
		print ("\n" + IP)
		output += reportscan(argument, IP)
	WriteFileFunction(output,directory,name)