Python - Making A Fast Port Scanner - Stack Overflow
Python - Making A Fast Port Scanner - Stack Overflow
8 import socket
ip = "External IP"
try:
7 s.connect((ip, port))
return True
except:
return None
if value == None:
else:
break
raw_input()
But this is too slow, I want to somehow be able to some how close or break code after a
period of time of not returning anything.
Share Improve this question edited Mar 13 '18 at 21:02 asked Oct 3 '14 at 7:16
Follow Drise Shane
4,006 4 34 61 257 1 3 13
In addition to setting socket timeout, you can also apply multi-threading technique to turbo
boost the process. It will be, at best, N times faster when you have N ports to scan.
19
# This script runs on Python 3
TCPsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
TCPsock.settimeout(delay)
try:
TCPsock.connect((ip, port_number))
output[port_number] = 'Listening'
except:
output[port_number] = ''
for i in range(10000):
# Starting threads
for i in range(10000):
threads[i].start()
for i in range(10000):
threads[i].join()
for i in range(10000):
if output[i] == 'Listening':
def main():
delay = int(input("How many seconds the socket is going to wait until timeout: "))
scan_ports(host_ip, delay)
if __name__ == "__main__":
main()
Share Improve this answer Follow edited Jan 25 '19 at 19:15 answered Jul 5 '16 at 18:15
Billy T
206 2 5
SO_REUSEADDR is only useful when listening on socket. Only creates confusion in this example
– Alex
Sep 13 '19 at 12:36
10000 was causing the error - too many open files, so reducing the range(1000) worked for me.
–
Vikram Ray
Aug 25 '20 at 17:36
here is a quick and simple port scanner, it scans 100000 ports in 180 sec:
3 import threading
import socket
target = 'pythonprogramming.net'
#ip = socket.gethostbyname(target)
def portscan(port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(0.5)#
try:
con = s.connect((target,port))
con.close()
except:
pass
r = 1
for x in range(1,100):
t = threading.Thread(target=portscan,kwargs={'port':r})
r += 1
t.start()
Share Improve this answer Follow edited Mar 13 '18 at 20:58 answered Mar 13 '18 at 20:53
Gysi Rrjolli
51 3
1 Why do you use r variable if you have x , that starts from 1 and increments every iteration?
–
diduk001
Jul 24 '20 at 18:38
1 #-*-coding:utf8;-*-
#qpy:3
#qpy:console
import socket
import os
# objects.
DEFAULT_TIMEOUT = 0.5
# was successful.
SUCCESS = 0
the host is up and listing on port x. If the connection fails for any
other reason we assume the host is down and the port is closed.'''
sock = socket.socket()
sock.settimeout(timeout)
# timeout to expire.
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# call (other problems, such as “host not found,” can still raise exceptions).
# The error indicator is 0 if the operation succeeded, otherwise the value of
# the errnovariable. This is useful to support, for example, asynchronous connects.
# Once that happens, all future operations on the socket object will fail.
# The remote end will receive no more data (after queued data is flushed).
sock.close()
return connected
print(con)
One can use threading.Thread and threading.Condition to synchronize port check and
spawning new threads.
1
Script example usage:
Checking 70 - 80
Checking 80 - 84
Checking 84 - 90
Checking 90 - 91
Checking 91 - 94
port_scan.py:
# import pdb
class IPv4PortScanner(object):
self.domain = domain
self.timeout = timeout
self.port_range = port_range
self.threadcount = threadcount
self._lock = threading.Lock()
self._condition = threading.Condition(self._lock)
self._ports_active = []
self._ports_being_checked = []
self._next_port = self.port_range[0]
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.settimeout(self.timeout)
try:
sock.connect((self.domain, port))
with self._lock:
self._ports_active.append(port)
sock.close()
return
except:
print_exc()
# pdb.set_trace()
try:
self.check_port_(port)
finally:
self._condition.acquire()
self._ports_being_checked.remove(port)
self._condition.notifyAll()
self._condition.release()
def start_another_thread(self):
raise AllThreadsStarted()
port = self._next_port
self._next_port += 1
t = threading.Thread(target=self.check_port, args=(port,))
# update books
with self._lock:
self._ports_being_checked.append(port)
t.start()
def run(self):
try:
while True:
self._condition.acquire()
self._condition.wait()
self._condition.release()
for i in xrange(slots_available):
self.start_another_thread()
except:
print_exc()
if __name__ == "__main__":
import sys
domain = sys.argv[1]
port_s = int(sys.argv[2])
port_e = int(sys.argv[3])
scanner.run()
socket.setdefaulttimeout(0.5)
This will make the program faster!
This answer is a good start, but I think it would be useful to explain why it will speed up the program,
perhaps with some references.
– Shepmaster
Dec 27 '14 at 3:10
socket.setdefualttimeout (time)
0 is used to keep trying to connect with port for perticular time...when you send request and
there is timeout set for 2 seconds so it will try to connect with port for 2 seconds....if there will
be no response from that port in 2 seconds....it will be count as a dead port
The following port scanner has a few constants defined at the top that you can modify as
needed:
0
PURPOSE -- help message for the command line
#! /usr/bin/env python3
import argparse
import collections
import itertools
import multiprocessing
import operator
import socket
POOL_SIZE = 1 << 8
TIMEOUT = 0.01
def main():
"""Get computer to scan, connect with process pool, and show open ports."""
parser = argparse.ArgumentParser(description=PURPOSE)
host = parser.parse_args().host
as pool:
ordered = sorted(numbers)
del field_names
def test(address):
try:
except OSError:
pass
else:
try:
probe.connect(info.address)
except OSError:
pass
else:
probe.shutdown(socket.SHUT_RDWR)
finally:
probe.close()
def format_ports(ports):
"""Convert port numbers into strings and show all associated services."""
if ports:
try:
service = socket.getservbyport(port)
except OSError:
service = '?'
else:
yield 'None'
if __name__ == '__main__':
main()