python 3ネットワーク管理


Python3ネットワークアプリケーション を使用してターゲットホストがアクティブであると判断
from __future__ import print_function
import subprocess
import threading
from queue import Queue
from queue import Empty


def call_ping(ip):
    if subprocess.call(["ping", "-c", "1", ip]):
        print("{0} is alive(   )".format(ip))
    else:
        print("{0} is unreacheable(  )".format(ip))


def is_reacheable(q):
    try:
        while True:
            ip = q.get_nowait()
            call_ping(ip)
    except Empty:
        pass


def main():
    q = Queue()
    with open('ips.txt') as f:
        for line in f:
            q.put(line)

    threads = []
    for i in range(10):
        thr = threading.Thread(target=is_reacheable, args=(q, ))
        thr.start()
        threads.append(thr)

    for thr in threads:
        thr.join()


if __name__ == '__main__':
    main()

このプログラムはips.txtファイルが必要で、自分で作成することができます.ファイルに検索するipアドレスを記入
192.168.1.1
192.168.1.2
...
socketを使用してポートスキャナを作成
# -*- coding:utf-8 -*-


from __future__ import print_function
from socket import *


def conn_scan(host, port):
    conn = socket(AF_INET, SOCK_STREAM)
    try:
        conn.connect((host, port))
        print(host, port, 'is avaliable')
    except Exception as e:
        print(host, port, 'is not avaliable')
    finally:
        conn.close()


def main():
    host = "127.0.0.1"
    for port in range(20, 5000):
        conn_scan(host, port)


if __name__ == '__main__':
    main()

telnetlibライブラリを使用してポートスキャンを行います.
# -*- coding:utf-8 -*-


from __future__ import print_function
import telnetlib


def conn_scan(host, port):
    t = telnetlib.Telnet()
    try:
        t.open(host, port, timeout=1)
        print(host, port, '    ')
    except Exception:
        print(host, port, '     ')
    finally:
        t.close()


def main():
    host = '127.0.0.1'
    for port in range(80, 5000):
        conn_scan(host, port)


if __name__ == '__main__':
    main()


これまでの経験を総括することによって、リストの迅速な生成を実現する(ip:portを格納する)
>>> In [1]: l1 = ('a', 'b', 'c')                                                                                               

>>> In [2]: l2 = (22, 80)                                                                                                      

>>> In [3]: list([(x, y) for x in l1 for y in l2])                                                                             
Out[3]: [('a', 22), ('a', 80), ('b', 22), ('b', 80), ('c', 22), ('c', 80)]

第1の方法はリスト導出式を用いてリストを生成し,この方法に対して最適化を選択することができる.
>>> In [1]: from itertools import product                                                                                      

>>> In [2]: l1 = ('a', 'b', 'c')                                                                                               

>>> In [3]: l2 = (22, 80)                                                                                                      

>>> In [4]: list(product(l1, l2))                                                                                              
Out[5]: [('a', 22), ('a', 80), ('b', 22), ('b', 80), ('c', 22), ('c', 80)]

第2の方法は、productライブラリからのitertools関数(複数の反復可能なオブジェクトのデカルト積を返すために使用される)を使用する.