Implementation of Port Scanning Tool by python

  • 2021-08-28 20:38:24
  • OfStack


#  Simple port scanning tool 
#  Author : Charles
#  WeChat official account : Charles Pikachu of 
import time
import socket
import threading

#  Whether the judgment is correct or not IP Address. 
def isIP(ip):
  ip_addr = ip.split('.')
  if len(ip_addr) != 4:
   return False
  for ipnum in ip_addr:
   if not (0 <= int(ipnum) < 255):
     return False
  else:
   return True


#  Port scanning tool 
class scanThread(threading.Thread):
  def __init__(self, ip, port_min=0, port_max=65535):
   #  Initialization. 
   threading.Thread.__init__(self)
   self.port_max = port_max
   self.port_min = port_min
   self.ip = ip
   # assert isinstance(int,self.port_min) and isinstance(int,self.port_max)
  #  Rewrite run
  def run(self):
   return self.__checker()
  #  Detection 
  def __checker(self):
   
   for port in range(self.port_min,self.port_max):
     self.__connect(port)
  #  Connect 
  def __connect(self,port):
   socket.setdefaulttimeout(1)
   self.sock = socket.socket()
   try:
     start_time = time.time()
     self.sock.connect((self.ip,port))
     end_time = time.time()
     connect_time = int(start_time - end_time)
     info = 'Find --> [IP]: %s, [PORT]: %s, [Connect Time]: %d' % (self.ip, port, connect_time)
     print(info)
     self.__save(info)
     self.sock.close()
   except:
     # print(' There's been a mistake ')
     self.sock.close()
  def __save(self,info):
   try:
     with open('results.txt', 'a') as f:
      f.write(info + '\n')
   except:
     print(' There is a problem writing the file ')
     time.sleep(0.1)

if __name__ == '__main__':
  #  Input IP Address. 
  ip = input('Input IP(example <xxx.xxx.xxx.xxx>):\n')
  print(isIP(ip))
  while not isIP(ip):
   ip = input(' Please enter the correct IP Address :\n')
  #  Enter the minimum port, 
  port_min = input(' The minimum ports to scan are: ')
  while not (0 <= int(port_min) < 65535):
   port_min = input(' Please enter the correct minimum port to scan: ')
  port_max = input(' The maximum ports that need to be scanned are ( 65535 ): ')
  while not (0 <= int(port_min) < int(port_max) < 65535):
   port_min = input(' Please enter the correct maximum port to scan ( 65535 ): ')
  num = 8
  port_max = int(port_max)
  port_min = int(port_min)
  interval = (port_max - port_min) // num
  for i in range(interval):
   scanThread(ip, i * num, (i + 1) * num).start()

The above is the python port scanning tool implementation details, more about the python port scanning tool information please pay attention to this site other related articles!


Related articles: