- Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathlesson07_scan_sequentially.py
More file actions
Latest commit
34 lines (31 loc) · 1.04 KB
/
Copy pathlesson07_scan_sequentially.py
File metadata and controls
34 lines (31 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# SuperFastPython.com
# example of an asyncio sequential port scanner
importasyncio
# returns True if a connection can be made
asyncdeftest_port_number(host, port, timeout=3):
# create coroutine for opening a connection
coro=asyncio.open_connection(host, port)
# execute the coroutine with a timeout
try:
# open the connection and wait for a moment
_,writer=awaitasyncio.wait_for(coro, timeout)
# close connection once opened
writer.close()
# indicate the connection can be opened
returnTrue
exceptasyncio.TimeoutError:
# indicate the connection cannot be opened
returnFalse
# main coroutine
asyncdefmain(host, ports):
# report a status message
print(f'Scanning {host}...')
# scan ports sequentially
forportinports:
ifawaittest_port_number(host, port):
print(f'> {host}:{port} [OPEN]')
# define a host and ports to scan
host='python.org'
ports=range(1, 1024)
# start the asyncio program
asyncio.run(main(host, ports))