1

This is my code for port scanner:

from scapy.all import *
from datetime import datetime
import threading

threadlock = threading.Lock()

def TCPort(ip_addr, port):
    time = 1   # max time to send packages to a port is 1 seconds

    threadlock.acquire()
    pkt = IP(dst=ip_addr)/TCP(dport=port,flags="S")
    ans = sr1(pkt, timeout=time, verbose=0)
    if(str(type(ans))=="<type 'NoneType'>"):
        #port is closed
        pass
    elif ans.haslayer(TCP):
         if (ans.getlayer(TCP).flags=="A") or (ans.getlayer(TCP).flags=="SA"):
        # port sent a SYN or SYN-ACK answer, so answer with RST to close
        # the connection and print the port
        sr1(IP(dst=ip_addr)/TCP(dport=port,flags="S"), timeout=time, verbose=0)
        print port,"open".rjust(9-len(str(port)))
    threadlock.release()

#main
ip_addr = "192.168.1.33"

ports = range(1,500)
start = datetime.now()
print "Started on", start.strftime('%Y-%m-%d %H:%M:%S')

for port in ports:
    t1 = threading.Thread(target=TCPort, args=(ip_addr,port))
    t2 = threading.Thread(target=TCPort, args=(ip_addr,port))
    t3 = threading.Thread(target=TCPort, args=(ip_addr,port))
    t4 = threading.Thread(target=TCPort, args=(ip_addr,port))
    t5 = threading.Thread(target=TCPort, args=(ip_addr,port))
    t6 = threading.Thread(target=TCPort, args=(ip_addr,port))
    t7 = threading.Thread(target=TCPort, args=(ip_addr,port))
    t8 = threading.Thread(target=TCPort, args=(ip_addr,port))
    t9 = threading.Thread(target=TCPort, args=(ip_addr,port))
    t10 = threading.Thread(target=TCPort, args=(ip_addr,port))
    t1.start()
    t2.start()
    t3.start()
    t4.start()
    t5.start()
    t6.start()
    t7.start()
    t8.start()
    t9.start()
    t10.start()
    t1.join()
    t2.join()
    t3.join()
    t4.join()
    t5.join()
    t6.join()
    t7.join()
    t8.join()
    t9.join()
    t10.join()

print "Finished on", datetime.now()-start

instead of doing 10 vars for the threads, How can I do the thread in fewer lines and less variables?

*** This question was edited to more specific question

*** IGNORE THIS PARAGRAPH. The system don't let me post the edit because I need to write some more words, so you can ignore this paragraph (by the way, if you read this I'll be glad to learn how an I bypass this limitation)

Eitan
  • 83
  • 2
  • 7

1 Answers1

2

I would recommend a pool-based approach, where you create a set of threads/processes, then feed them the ports you want to check. Threading pool similar to the multiprocessing Pool? is how to do this with threads, which should be all you need in this case. This manages most of the annoying parts of threading for you.

user3757614
  • 1,776
  • 12
  • 10