Advertisement
cmiN

ssps

Oct 11th, 2012
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.03 KB | None | 0 0
  1. #! /usr/bin/env python
  2. #
  3. # ssps: Simple Single Port Scanner
  4. # Copyright (C) 2012  cmiN
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program.  If not, see <http://www.gnu.org/licenses/>.
  18. #
  19. # Author(s): Cosmin Poieana <cmin764@yahoo.com>
  20.  
  21.  
  22. import sys
  23. import socket
  24. import threading
  25. import time
  26.  
  27.  
  28. # some constants referring to options
  29. THRD = 50 # how many threads
  30. TOUT = 2 # socket timeout
  31. OUTP = None # output file
  32. VERB = False # verbose
  33. USAGE = """Usage: {0} FILE PORT [OPTION]...
  34. Scan for open PORT using hosts from FILE
  35.  
  36. Options:
  37.    -o, --output <str>       file name to store the output
  38.    -t, --threads <int>      number of threads, default {1}
  39.    -T, --timeout <float>    timeout in seconds, default {2}
  40.    -v, --verbose            see all the activity
  41.  
  42. For "can't start new thread" error try to reduce stack size:
  43.    ulimit -s 1024
  44. Report bugs to cmin764@yahoo.com""".format("{0}", THRD, TOUT)
  45.  
  46.  
  47. def scan(host):
  48.     # create the socket and try to connect
  49.     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  50.     rcode = sock.connect_ex((host, port))
  51.     # critical print
  52.     lock.acquire()
  53.     if not rcode:
  54.         print host + " OK"
  55.         if OUTP:
  56.             OUTP.write(host + "\n")
  57.     elif VERB:
  58.         print host
  59.     lock.release()
  60.     # increment the semaphore
  61.     semaphore.release()
  62.  
  63.  
  64. def strtime(wtime):
  65.     # convert seconds to string
  66.     sec = wtime % 60
  67.     wtime /= 60
  68.     mnt = wtime % 60
  69.     hrs = wtime / 60
  70.     return "%dh %dm %ds" % (hrs, mnt, sec)
  71.  
  72.  
  73. def main(argc, argv):
  74.     if argc == 1:
  75.         print "Run with --help"
  76.         return 0
  77.     elif argv[1] in ("-h", "--help"):
  78.         print USAGE.format(argv[0])
  79.         return 0
  80.     elif argc < 3:
  81.         print "Missing argument(s)"
  82.         return 6
  83.     else:
  84.         # check file
  85.         try:
  86.             fin = open(argv[1], "r")
  87.         except IOError:
  88.             print "Can't find file '%s' or read data" % argv[1]
  89.             return 1
  90.         # check port
  91.         try:
  92.             global port
  93.             port = int(argv[2])
  94.         except ValueError:
  95.             print "Invalid port '%s'" % argv[2]
  96.             return 2
  97.         # and now the options
  98.         ind = 3
  99.         while ind < argc:
  100.             if argv[ind] in ("-t", "--threads"):
  101.                 ind += 1
  102.                 if ind == argc:
  103.                     print "Missing value"
  104.                     return 5
  105.                 try:
  106.                     global THRD
  107.                     THRD = int(argv[ind])
  108.                 except ValueError:
  109.                     print "Invalid value '%s'" % argv[ind]
  110.                     return 3
  111.             elif argv[ind] in ("-T", "--timeout"):
  112.                 ind += 1
  113.                 if ind == argc:
  114.                     print "Missing value"
  115.                     return 5
  116.                 try:
  117.                     global TOUT
  118.                     TOUT = float(argv[ind])
  119.                 except ValueError:
  120.                     print "Invalid value '%s'" % argv[ind]
  121.                     return 3
  122.             elif argv[ind] in ("-o", "--output"):
  123.                 ind += 1
  124.                 if ind == argc:
  125.                     print "Missing value"
  126.                     return 5
  127.                 try:
  128.                     global OUTP
  129.                     OUTP = open(argv[ind], "a")
  130.                 except IOError:
  131.                     print "Can't find file '%s' or write data" % argv[ind]
  132.                     return 1
  133.             elif argv[ind] in ("-v", "--verbose"):
  134.                 global VERB
  135.                 VERB = True
  136.             else:
  137.                 print "Invalid option '%s'" % argv[ind]
  138.                 return 4
  139.             ind += 1
  140.         # if we get here, everything (almost) is fine
  141.         start = time.time()
  142.         print "Started at %s" % time.ctime()
  143.         global lock, semaphore
  144.         lock = threading.Lock()
  145.         semaphore = threading.Semaphore(THRD)
  146.         socket.setdefaulttimeout(TOUT)
  147.         for host in fin:
  148.             semaphore.acquire()
  149.             threading.Thread(target=scan,
  150.                              args=(host.strip(),)).start()
  151.         fin.close()
  152.         # now wait for the remaining threads
  153.         while threading.active_count() > 1:
  154.             pass
  155.         if OUTP:
  156.             OUTP.close()
  157.         print "Ended at %s and took %s" % (time.ctime(),
  158.                                            strtime(time.time() - start))
  159.         return 0
  160.  
  161.  
  162. if __name__ == "__main__":
  163.     sys.exit(main(len(sys.argv), sys.argv))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement