Skip to content

Commit b6321bc

Browse files
Merge pull request #1588 from tanujbordikar/port_changes
port scanner commit
2 parents e1cfb06 + 8221400 commit b6321bc

File tree

1 file changed

+22
-9
lines changed

1 file changed

+22
-9
lines changed

PortScanning/portscanningscript.py

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import socket
22
import subprocess
33
import sys
4+
import asyncio
45
from datetime import datetime
56

67
subprocess.call('cls', shell=True)
@@ -17,16 +18,28 @@
1718
# Check what time the scan started
1819
t1 = datetime.now()
1920

20-
# Using the range function to specify ports (here it will scans all ports
21+
async def scan_port(port):
22+
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
23+
sock.setblocking(False)
24+
try:
25+
await asyncio.wait_for(
26+
asyncio.get_event_loop().sock_connect(sock, (remoteServerIP, port)),
27+
timeout=1
28+
)
29+
print("Port {}: Open".format(port))
30+
except (socket.timeout, ConnectionRefusedError):
31+
pass
32+
finally:
33+
sock.close()
2134

22-
# We also put in some error handling for catching errors
23-
try:
35+
async def main():
36+
tasks = []
2437
for port in range(1, 1025):
25-
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
26-
result = sock.connect_ex((remoteServerIP, port))
27-
if result == 0:
28-
print("Port {}: Open".format(port))
29-
sock.close()
38+
tasks.append(scan_port(port))
39+
await asyncio.gather(*tasks)
40+
41+
try:
42+
asyncio.run(main())
3043
except KeyboardInterrupt:
3144
print("You pressed Ctrl+C")
3245
sys.exit()
@@ -45,4 +58,4 @@
4558
# Calculates the difference of time, to see how long it took to run the script
4659
total = t2 - t1
4760

48-
print('Scanning Completed in: ', total)
61+
print('Scanning Completed in:', total)

0 commit comments

Comments
 (0)