Skip to content

Instantly share code, notes, and snippets.

@namuyan
Created September 30, 2018 03:12
Show Gist options
  • Save namuyan/05cde65c12199494314dcd74ded02f58 to your computer and use it in GitHub Desktop.
Save namuyan/05cde65c12199494314dcd74ded02f58 to your computer and use it in GitHub Desktop.
Pythonでポートスキャンするプログラムを作成
from socket import socket, gethostbyname, AF_INET, SOCK_STREAM
from threading import Thread, Lock
from time import sleep, time
def _thread(address, ports, opened, lock):
while True:
with lock:
try:
port = ports.pop()
except IndexError:
break
s = socket(AF_INET, SOCK_STREAM)
s.settimeout(5)
if s.connect_ex((address, port)) == 0:
with lock:
opened.append(port)
if port % 2000 == 0:
print("Now.. ", port)
s.close()
def port_scan(address, start=1, finish=65535, t=8000):
s = time()
threads = list()
ports = list(reversed(range(start+1, finish+1)))
opened = list()
lock = Lock()
host = gethostbyname(address)
print("Port scan", address, "(", host, ") form", start, "to", finish)
for i in range(t):
threads.append(Thread(
target=_thread, args=(host, ports, opened, lock), daemon=True))
for t in threads:
t.start()
sleep(0.005)
print(len(threads), "thread working.")
for t in threads:
t.join()
print("Finished", round(time()-s, 3), "Sec")
return opened
if __name__ == '__main__':
r = port_scan('google.com')
print(r)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment