This is a quick python port scanner using asyncio module.
Key points:
- It doesn't use multiprocessing or multithreading; it uses asyncronous processes. The scripts sends the requests one after another and processes the replies when they arrive.
- I used semaphore to limit the request counts. It seems there's a limitation on both Windows and Linux machines. source
- Adding timeout is important because some connection attempts may hang. asyncio.wait_for is used for that purpose.
Have fun!
import asyncio
async def check_port(ip, port, loop):
conn = asyncio.open_connection(ip, port, loop=loop)
try:
reader, writer = await asyncio.wait_for(conn, timeout=3)
print(ip, port, 'ok')
return (ip, port, True)
except:
print(ip, port, 'nok')
return (ip, port, False)
finally:
if 'writer' in locals():
writer.close()
async def check_port_sem(sem, ip, port, loop):
async with sem:
return await check_port(ip, port, loop)
async def run(dests, ports, loop):
sem = asyncio.Semaphore(400) #Change this value for concurrency limitation
tasks = [asyncio.ensure_future(check_port_sem(sem, d, p, loop)) for d in dests for p in ports]
responses = await asyncio.gather(*tasks)
return responses
dests = ['steemit.com', 'steem.io', 'www.raiblocks.net', 'bitcoin.org'] #destinations
ports = [80, 443, 8080, 8443] #ports
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(run(dests, ports, loop))
loop.run_until_complete(future)
print('#'*50)
print('Results: ', future.result())
Output:
steem.io 443 ok
steem.io 80 ok
www.raiblocks.net 443 ok
www.raiblocks.net 80 ok
www.raiblocks.net 8443 ok
www.raiblocks.net 8080 ok
steemit.com 80 ok
steemit.com 443 ok
bitcoin.org 80 ok
bitcoin.org 443 ok
steemit.com 8080 nok
steem.io 8080 nok
bitcoin.org 8080 nok
bitcoin.org 8443 nok
steem.io 8443 nok
steemit.com 8443 nok
##################################################
Results: [('steemit.com', 80, True), ('steemit.com', 443, True), ('steemit.com', 8080, False), ('steemit.com', 8443, False), ('steem.io', 80, True), ('steem.io', 443, True), ('steem.io', 8080, False), ('steem.io', 8443, False), ('www.raiblocks.net', 80, True), ('www.raiblocks.net', 443, True), ('www.raiblocks.net', 8080, True), ('www.raiblocks.net', 8443, True), ('bitcoin.org', 80, True), ('bitcoin.org', 443, True), ('bitcoin.org', 8080, False), ('bitcoin.org', 8443, False)]
Congratulations @gunhanoral! You received a personal award!
Click here to view your Board
Do not miss the last post from @steemitboard:
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Congratulations @gunhanoral! You received a personal award!
You can view your badges on your Steem Board and compare to others on the Steem Ranking
Vote for @Steemitboard as a witness to get one more award and increased upvotes!
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit