Advertisement
Guest User

Untitled

a guest
Jan 25th, 2017
326
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 8.28 KB | None | 0 0
  1. #!/usr/bin/python
  2.  
  3. # Visit Codingsec.net > https://codingsec.net/2016/05/create-port-scanner-python/
  4.  
  5. # HISTORY
  6. #
  7. # V1.01 - 2017-01-25:
  8. # + Scan subnet except for 1 IP only with module ipaddress. Install this module (`sudo pip install ipaddress`) before using it.
  9. # + Ping before scanning (use pyping). Note that ICMP messages can only be send from processes running as root.
  10. # + Add some well-known ports with ref https://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers#Well-known_ports
  11.  
  12. # Importing the modules
  13. # socket :=> This is what we use to create a socket connection
  14. # argparse is used to parse arguments. This is not important now
  15. # and it is out of the scope of this post
  16. import socket,sys,time,datetime,argparse,os
  17.  
  18. import ipaddress
  19. import pyping
  20.  
  21. # This dictionary contains the most popular ports used
  22. # You can add ports here.
  23. # The key is the port number and the values is the service used by that port
  24. common_ports = {
  25.     '21': 'FTP',
  26.     '22': 'SSH',
  27.     '23': 'TELNET',
  28.     '25': 'SMTP',
  29.     '53': 'DNS',
  30.     #'69': 'TFTP',
  31.     '80': 'HTTP',
  32.     #'109': 'POP2',
  33.     '110': 'POP3',
  34.     #'123': 'NTP',
  35.     #'137': 'NETBIOS-NS',  #'138': 'NETBIOS-DGM',
  36.     '139': 'NETBIOS-SSN',
  37.     '143': 'IMAP',
  38.     #'156': 'SQL-SERVER',
  39.     #'389': 'LDAP',
  40.     '443': 'HTTPS',
  41.     '445': 'NETBIOS-SMB',
  42.     #'546': 'DHCP-CLIENT',
  43.     #'547': 'DHCP-SERVER',
  44.     '587': 'STMP SSL',
  45.     '995': 'POP3-SSL',
  46.     '993': 'IMAP-SSL',
  47.     '1701': 'L2TP',
  48.     #'2086': 'WHM/CPANEL',    '2087': 'WHM/CPANEL',    '2082': 'CPANEL',    '2083': 'CPANEL',
  49.     '3306': 'MYSQL',
  50.     '3389': 'RDP',
  51.     #'4899': 'Radmin',
  52.     '5800': 'VNC-5800',
  53.     '5900': 'VNC-5900',
  54.     '6969': 'Torrent',
  55.     '8080': 'HTTP Proxy',
  56.     '8443': 'PLESK',
  57.     '10000': 'VIRTUALMIN/WEBMIN'
  58. }
  59.  
  60.  
  61. # This is the function that will connect to a port and will check
  62. # if it is open or closed
  63. def check_port(host, port, result = 1):
  64.     # The function takes 3 arguments
  65.     # host : the IP to scan
  66.     # port : the port number to connect
  67.     try:
  68.         # Creating a socket object named 'sock'
  69.         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  70.         # Setting socket timeout so that the socket does not wait forever to complete  a connection
  71.         sock.settimeout(0.5)
  72.         # Connect to the socket
  73.         # if the connection was successful, that means the port
  74.         # is open, and the output 'r' will be zero
  75.         r = sock.connect_ex((host, port))
  76.         if r == 0:
  77.             result = r
  78.         sock.close() # closing the socket
  79.     except Exception, e:
  80.         pass
  81.  
  82.     return result # returns the result of the scan.
  83.  
  84. # This function reads the dictonary of ports and services and
  85. # Checks for the service name corresponding to a port.
  86. def get_service(port):
  87.     port = str(port) # converts the int to string
  88.     if port in common_ports: # check if the port is available in the common ports dictionary
  89.         return common_ports[port] # returns the service name if available
  90.     else:
  91.         return 0 # return 0 if no service is identified
  92.  
  93.  
  94. flag = 0  # we're gonna use this flag later. Just keep it in mind
  95. os.system('clear') # Clear the console window
  96.  
  97. line = "+" * 80 # Just a fancy line consisting '+'
  98. desc = line+'''\nA Simple port scanner that works!! (c) digitz.org
  99.    Example usage: python port_scanner.py example.com 1 1000
  100.    The above example will scan the host \'example.com\' from port 1 to 1000
  101.    To scan most common ports, use: python port_scanner.py example.com\n'''+line+"\n"
  102.     # Just a description about the script and how to use it
  103.  
  104. # I would suggest you to read about "argparse", it comes in handy
  105. # when you want to parse arguments
  106. parser = argparse.ArgumentParser(description = desc, formatter_class=argparse.RawTextHelpFormatter)
  107. parser.add_argument('hosts', metavar='H', help='Host name you want to scan')
  108. parser.add_argument('startport', metavar='P1', nargs='?', help='Start scanning from this port')
  109. parser.add_argument('endport', metavar='P2', nargs='?',help='Scan until this port')
  110. args = parser.parse_args()
  111.  
  112.  
  113. # args.startpoint corresponds to the first port we will scan
  114. # args.endport corresponds to the last port.
  115. # Here, we're checking if both starting port and ending port is defined
  116. # If it is not defined, we will do a scan over most popular TCP ports.
  117. if (args.startport) and args.endport :
  118.     # If this condition is true, the script will scan over this port range
  119.     start_port = int(args.startport)
  120.     end_port = int(args.endport)
  121. else:
  122.     # In this case, the script will scan the most common ports.
  123.     # that is, if you did not give any ports as argument.
  124.     flag = 1
  125.  
  126.  
  127. starting_time = time.time() # Get the time at which the scan was started
  128. print "+" * 40
  129. print "\tSimple Port Scanner..!!!"
  130. print "+" * 40
  131.  
  132. print "Scanning started at %s" %(time.strftime("%I:%M:%S %p"))
  133.  
  134. args_hosts = args.hosts.decode('utf-8')
  135.  
  136. hosts = []
  137. if args_hosts.find("/") > 0:
  138.     hosts = list(ipaddress.ip_network(args_hosts).hosts()) # The host name to scan for open ports
  139. else:
  140.     hosts.insert(0, ipaddress.ip_address(args_hosts))
  141.  
  142. if (flag): # The flag is set, that means the user did not provide any ports as argument
  143.     print "Scanning for most common ports on %s" % args_hosts
  144. else:
  145.     # The user did specify a port range to scan
  146.     print "Scanning %s from port %s - %s: " % (host, start_port, end_port)
  147.  
  148. print ""
  149.  
  150. for host in hosts:
  151.     try:
  152.         host = str(host)
  153.         ip = str(socket.gethostbyname(host)) # Converts the host name into IP address
  154.        
  155.         ping_result = pyping.ping(ip)
  156.         if ping_result.ret_code == 0:
  157.             print "\r" + "=" * 40
  158.             print "Scan host %s" %(host)
  159.             print "Connecting to Port: ",
  160.            
  161.             open_ports = []  # This list is used to hold the open ports
  162.             if flag: # The flag is set, means the user did not give any port range
  163.                 for p in sorted(common_ports): # So we will scan the common ports.
  164.                     sys.stdout.flush() # flush the stdout buffer.
  165.                     p = int(p)
  166.                     print p,
  167.                     response = check_port(host, p) # call the function to connect to the port
  168.                     if response == 0: # The port is open
  169.                         open_ports.append(p) # append it to the list of open ports
  170.                     #if not p == end_port:
  171.                         sys.stdout.write('\b' * len(str(p))) # This is just used to clear the port number displayed. This is not important at all
  172.             else:
  173.            
  174.                 # The user did provide a port range, now we have to scan through that range
  175.                 for p in range(start_port, end_port+1):
  176.                     sys.stdout.flush()
  177.                     print p,
  178.                     response = check_port(host, p) # Call the function to connect to the port
  179.                     if response == 0: # Port is open
  180.                         open_ports.append(p) # Append to the list of open ports
  181.                     if not p == end_port:
  182.                         sys.stdout.write('\b' * len(str(p)))
  183.          
  184.             print ""
  185.            
  186.             if open_ports: # There are open ports available
  187.                 print "Open Ports: "
  188.                 for i in sorted(open_ports):
  189.                     service = get_service(i)
  190.                     if not service: # The service is not in the disctionary
  191.                         service = "Unknown service"
  192.                     print "\t%s %s: Open" % (i, service)
  193.             else:
  194.                 # No open ports were found
  195.                 print "Sorry, No open ports found.!!"
  196.        
  197.         #else:
  198.         #    print "."
  199.         # end of if pyping.ping(ip)
  200.        
  201.     except KeyboardInterrupt: # This is used in case the  user press "Ctrl+C", it will show the following error instead of a python's scary error
  202.         print "You pressed Ctrl+C. Exiting "
  203.         sys.exit(1)
  204.  
  205. print "\nScanning completed at %s" %(time.strftime("%I:%M:%S %p"))
  206. ending_time = time.time()
  207. total_time = round(ending_time - starting_time, 1) # Calculating the total time used to scan
  208.  
  209. if total_time <= 60.0:
  210.     print "Scan Took %s seconds" %(total_time)
  211. else:
  212.     total_time = round(total_time / 60, 1)
  213.     print "Scan Took %s Minutes" %(total_time)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement