## LANSKORPIAN - Personal home network scanner
## Copyright (C) Robert Rice <mindseyes@gmail.com>
## This program is published under a MIT license

print "\n"
print ("-" * 60)
print "          LANSKORPIAN Personal Home Port Scanner"
print ("-" * 60)
print "\n"

# Import modules
import subprocess
import ipaddress
from datetime import datetime
import socket
import sys
from com_ports import*



# input a network address
net_addr = raw_input("Enter a network address in CIDR format(ex.192.168.1.0/24): ")
start_time = datetime.now()

# Banner
print ("-" * 60)
print "Please wait, scanning network", net_addr
print ("-" * 60)

# Create the network
ip_net = ipaddress.ip_network(net_addr)

# Get all hosts on that network
all_hosts = list(ip_net.hosts())


# Configure subprocess to hide the console window
info = subprocess.STARTUPINFO()
info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
info.wShowWindow = subprocess.SW_HIDE

# For each IP address in the subnet, 
# run the ping command with subprocess.popen interface
for i in range(len(all_hosts)):
    output = subprocess.Popen(['ping', '-n 5', '1', '-w', '100', str(all_hosts[i])], stdout=subprocess.PIPE, startupinfo=info).communicate()[0]
   
    if "Destination host unreachable" in output.decode('utf-8'):
        pass
    elif "Request timed out" in output.decode('utf-8'):
        pass
    else:
        print(str(all_hosts[i]) + " is Active")

stop_time = datetime.now()


total =  stop_time - start_time
print 'Scanning Completed in: ', total
print "\n"

####################################################################

# Start individual host scan
remoteServer    = raw_input("Enter Active host to scan: ")
remoteServerIP  = socket.gethostbyname(remoteServer)
name = socket.getfqdn(remoteServerIP)

# Banner
print ("-" * 60)
print "Please wait, scanning Active host",  name
print ("-" * 60)


# Check what time the scan started
t1 = datetime.now()

# check and returns the service name if available
def get_service(port):
    	port = str(port) 
	if port in common_ports: 
		return common_ports[port] 
	else:
		return unknown_ports 

#start scanning ports
try:
    for port in range(1,1025):  
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        result = sock.connect_ex((remoteServerIP, port))
        if result == 0:
            print "Port {}: 	 Open".format(port),   get_service(port)
        sock.close()


except KeyboardInterrupt:
    t2 = datetime.now()
    cancel = t2 - t1
    print "Scan cancled by user in:", cancel
    sys.exit()

except socket.gaierror:
    print 'Hostname could not be resolved. Exiting'
    sys.exit()

except socket.error:
    print "Couldn't connect to server"
    sys.exit()

# Checking the time again
t3 = datetime.now()

# Calculates the difference of time, to see how long it took to run the script
total =  t3 - t1

# Printing the information to screen
print 'Scanning Completed in: ', total
