Guest User

Untitled

a guest
Dec 13th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.07 KB | None | 0 0
  1. #!/usr/bin/python3.7
  2.  
  3. import asyncio
  4. import ipaddress
  5. import re
  6. import sys
  7.  
  8.  
  9. MAX_NUMBER_WORKERS = 200
  10.  
  11.  
  12. def ipsort(t):
  13. '''used to sort output by ipaddress, then port'''
  14. return tuple([*map(int, t[0].split('.')), t[1]])
  15.  
  16.  
  17. def eprint(*args, **kwargs):
  18. print(*args, **kwargs, file=sys.stderr)
  19.  
  20.  
  21. def parseports(portstring):
  22. '''
  23. syntax: port,port-range,...
  24. use regex to verify input validity, then create a tuple of
  25. ports used in port scan. there definitely some room for optimization
  26. here, but it won't matter much. go optimize the coroutines instead.
  27. '''
  28. if not re.match(r'[\d\-,\s]+', portstring):
  29. raise ValueError('Invalid port string')
  30. ports = []
  31. portstring = list(filter(None, portstring.split(',')))
  32. for port in portstring:
  33. if '-' in port:
  34. try:
  35. port = [int(p) for p in port.split('-')]
  36. except ValueError:
  37. raise ValueError('Are you trying to scan a negative port?')
  38. for p in range(port[0], port[1]+1):
  39. ports.append(p)
  40. else:
  41. ports.append(int(port))
  42. for port in ports:
  43. if not (-1 < port < 65536):
  44. raise ValueError('Ports must be between 0 and 65535')
  45. return tuple(set(ports))
  46.  
  47.  
  48. def fancy_print(data, csv):
  49. if csv:
  50. fmt = '{},{}'
  51. else:
  52. fmt = '{:<15} :{}'
  53. for datum in data:
  54. print(fmt.format(*datum))
  55.  
  56.  
  57. async def task_worker(task_queue, out_queue):
  58. '''pull connection information from queue and attempt connection'''
  59. while True:
  60. ip, port, timeout = (await task_queue.get())
  61. conn = asyncio.open_connection(ip, port)
  62. try:
  63. await asyncio.wait_for(conn, timeout)
  64. except asyncio.TimeoutError:
  65. pass
  66. else:
  67. out_queue.put_nowait((ip, port))
  68. finally:
  69. task_queue.task_done()
  70.  
  71.  
  72. async def task_master(
  73. network: str, portrange: str, timeout: float,
  74. task_queue: asyncio.Queue, scan_completed: asyncio.Event):
  75. '''add jobs to a queue, up to ``MAX_NUMBER_WORKERS'' at a time'''
  76. network = network.replace('/32', '')
  77. try:
  78. # check to see if we are scanning a single host...
  79. hosts = [str(ipaddress.ip_address(network)),]
  80. except ValueError:
  81. # ...or a CIDR subnet.
  82. hosts = map(str, ipaddress.ip_network(network).hosts())
  83. for ip in hosts:
  84. for port in portrange:
  85. await task_queue.put((ip, port, timeout))
  86. scan_completed.set()
  87.  
  88.  
  89. async def main(network, ports=None, timeout=0.1, csv=False):
  90. '''
  91. main task coroutine which manages all the other functions
  92. if scanning over the internet, you might want to set the timeout
  93. to around 1 second, depending on internet speed.
  94. '''
  95. task_queue = asyncio.Queue(maxsize=MAX_NUMBER_WORKERS)
  96. out_queue = asyncio.Queue()
  97. scan_completed = asyncio.Event()
  98. scan_completed.clear() # progress the main loop
  99.  
  100. if ports is None: # list of common-ass ports
  101. ports = ("9,20-23,25,37,41,42,53,67-70,79-82,88,101,102,107,109-111,"
  102. "113,115,117-119,123,135,137-139,143,152,153,156,158,161,162,170,179,"
  103. "194,201,209,213,218,220,259,264,311,318,323,383,366,369,371,384,387,"
  104. "389,401,411,427,443-445,464,465,500,512,512,513,513-515,517,518,520,"
  105. "513,524,525,530,531,532,533,540,542,543,544,546,547,548,550,554,556,"
  106. "560,561,563,587,591,593,604,631,636,639,646,647,648,652,654,665,666,"
  107. "674,691,692,695,698,699,700,701,702,706,711,712,720,749,750,782,829,"
  108. "860,873,901,902,911,981,989,990,991,992,993,995,8080,2222,4444,1234,"
  109. "12345,54321,2020,2121,2525,65535,666,1337,31337,8181,6969")
  110. ports = parseports(ports)
  111.  
  112. # initialize task to add scan info to task queue
  113. tasks = [asyncio.create_task(
  114. task_master(network, ports, timeout, task_queue, scan_completed)
  115. )]
  116. # initialize workers
  117. for _ in range(MAX_NUMBER_WORKERS):
  118. tasks.append(asyncio.create_task(task_worker(task_queue, out_queue)))
  119.  
  120. eprint('scanning . . .')
  121. await scan_completed.wait() # wait until the task master coro is done
  122. await task_queue.join() # wait for workers to finish
  123. for task in tasks:
  124. task.cancel()
  125. await asyncio.gather(*tasks, return_exceptions=True)
  126. eprint('gathering output . . .')
  127. openports = []
  128. while out_queue.qsize():
  129. openports.append(out_queue.get_nowait())
  130. openports.sort(key=ipsort)
  131. fancy_print(openports, csv=csv)
  132.  
  133. eprint('shutting down . . .')
  134.  
  135. if __name__ == '__main__':
  136. # import argparse?
  137. if len(sys.argv) < 2:
  138. print(
  139. 'TCP Network scanner using asyncio module for Python 3.7+',
  140. "Scan ports in ``portstring'' or common ports if blank."
  141. 'Port string syntax: port, port-range ...',
  142. f'Usage: {sys.argv[0]} network [portstring]',
  143. sep='\n'
  144. )
  145. raise SystemExit
  146. elif len(sys.argv) == 2:
  147. asyncio.run(main(sys.argv[1]))
  148. else:
  149. asyncio.run(main(sys.argv[1], ''.join(sys.argv[2:])))
Add Comment
Please, Sign In to add comment