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)]
第一种方式使用列表推导式来生成列表,针对这种方式,我们可以选择优化。
>>> 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)]
第二种方式使用
product
函数(用来返回多个可迭代对象的笛卡尔积),该函数来自itertools
库。