johnmahugu

python port scanner portscanner.py

May 24th, 2016
267
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.39 KB | None | 0 0
  1. #!/usr/bin/env python
  2. import socket
  3. import subprocess
  4. import sys
  5. from datetime import datetime
  6.  
  7. # Clear the screen
  8. subprocess.call('clear', shell=True)
  9.  
  10. # Ask for input
  11. remoteServer    = raw_input("Enter a remote host to scan: ")
  12. remoteServerIP  = socket.gethostbyname(remoteServer)
  13.  
  14. # Print a nice banner with information on which host we are about to scan
  15. print "-" * 60
  16. print "Please wait, scanning remote host", remoteServerIP
  17. print "-" * 60
  18.  
  19. # Check what time the scan started
  20. t1 = datetime.now()
  21.  
  22. # Using the range function to specify ports (here it will scans all ports between 1 and 1024)
  23.  
  24. # We also put in some error handling for catching errors
  25.  
  26. try:
  27.     for port in range(1,1025):  
  28.         sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  29.         result = sock.connect_ex((remoteServerIP, port))
  30.         if result == 0:
  31.             print "Port {}:      Open".format(port)
  32.         sock.close()
  33.  
  34. except KeyboardInterrupt:
  35.     print "You pressed Ctrl+C"
  36.     sys.exit()
  37.  
  38. except socket.gaierror:
  39.     print 'Hostname could not be resolved. Exiting'
  40.     sys.exit()
  41.  
  42. except socket.error:
  43.     print "Couldn't connect to server"
  44.     sys.exit()
  45.  
  46. # Checking the time again
  47. t2 = datetime.now()
  48.  
  49. # Calculates the difference of time, to see how long it took to run the script
  50. total =  t2 - t1
  51.  
  52. # Printing the information to screen
  53. print 'Scanning Completed in: ', total
Add Comment
Please, Sign In to add comment