10
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pythonでポートスキャン

Last updated at Posted at 2019-12-04

はじめに

CTFの本でポートスキャンをpythonでできるってことを知り
「え?pythonってそんなのできる?」という好奇心からスタート
その過程でシングルで動かすよりもマルチスレッドのほうが抜群に早いことを知り
せっかくなので比較のために両方残す。

気を付ける事

ポートスキャンは外部のサイトにやるのはNGなので
実験にあたっては自前のPCでVirtualboxを使って仮想サーバを立ち上げて
そこに対してポートスキャンをかました。
そんなわけで↓↓のソースコードで書かれている"10.0.0.2"は自前の仮想サーバのIPです。

1.シンプルなポートスキャン

参考:https://qiita.com/najayama/items/728682bcae824c902046

一番勉強になったコードはコレ。なんせ無駄が一つもない。
その代わり遅い。逆に遅いからこそ「マルチスレッドの有効性」というもの痛烈に感じることができた。

simple-port-scanner.py
import socket

max_port = 6000
min_port = 1

target_host = input("Input target host name or address: ")

for port in range(min_port, max_port):
    #target_host のポート番号portに接続を試行
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    return_code = sock.connect_ex((target_host, port))
    sock.close()

    #socket.connect_ex は成功すると0を返す
    if return_code == 0:
        print("Port %d open!" % (port))

print("Complete!")

2.マルチスレッドなポートスキャン

参考:https://www.valuestar.work/news/archives/20

こちらも負けず劣らず無駄がない。
threadをうまく使ってるので死ぬほど早い。1.では1ポートあたり1秒くらいかかっていたので
1~1024ポートやるのに結構な時間を要したがこっちのプログラムだと、3秒程度で処理が終了した。
threadやばい。

今回は突貫で参考にしたのでコード丸写しなため、比較できる形になっていない。
後々比較できるように整形出来たら…いいなぁ

multi-port-scanner.py
import socket
import threading

scan_range = [1, 10000];

host = "10.0.0.2";

threads = [];
ports = [];
isopen = [];

def Run(port, i):
    con = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    return_code = con.connect_ex((host, port))
    con.close()

    if return_code == 0:
        isopen[i] = 1;
    
    
count = 0;
for port in range(scan_range[0], scan_range[1]):
    ports.append(port);
    isopen.append(0);
    thread = threading.Thread(target=Run, args=(port, count));
    thread.start();
    threads.append(thread);
    count = count + 1;

for i in range(len(threads)):
    threads[i].join();
    if isopen[i] == 1:
        print("%d open" % ports[i]);

おわりに

ポートスキャンの勉強のために調べたけど
予想以上に自分の中ではthreadの破壊力が印象に残ってしまった。
後でゆっくりソースコードを眺めて整理することにしよう

~おしまい~

10
13
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?