Python扫描端口
包含的知识点:
–多线程,锁
–socket
#encoding=utf-8
# __author__ = 'wangshenglong'
import socket
import threading
routers = []
lock = threading.Lock()
# 实际上可以认为是端口扫描,程序只是粗略地检查是否开放了80端口。
# timeout可以设置成1秒或2秒。local_ips是获取多块网卡上绑定的IP,比如我的IP地址是192.168.1.4和192.168.56.1。而代码所做的事情就是扫描 [192.168.1.1 ~ 192.168.1.254] [192.168.56.1 ~ 192.168.56.254] 有哪些IP开放80端口。
#
def search_routers():
routers = []
# gethostname得到hostname,例如 wangshenglong-Mac.local
# gethostbyname_ex返回(name, aliaslist, addresslist),例如('wangshenglong-mac.local', [], ['192.168.2.1', '192.168.56.1', '192.168.1.155'])
# 我的机器包含vboxnet0,bridge0,en0,获取ip:ifconfig |grep 'inet'|grep -v '127.0.0.1'|grep -v 'inet6' | sed -n '1p'|awk '{print $2}',其中sed -n '1p'表示取第一行
#
print(socket.gethostbyname_ex(socket.gethostname()))
local_ips = socket.gethostbyname_ex(socket.gethostname())[2] # get local IP
all_threads = []
for ip in local_ips:
for i in range(1, 255):
array = ip.split('.')
array[3] = str(i)
new_ip = '.'.join(array)
t = threading.Thread(target=check_ip, args=(new_ip,) )
t.start()
all_threads.append(t)
for t in all_threads:
t.join()
def check_ip(new_ip):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1)
result = s.connect_ex((new_ip, 80))
s.close()
if result == 0:
lock.acquire()
print new_ip.ljust(15), ' port 80 is open'
routers.append((new_ip, 80))
lock.release()
print 'Searching for routers, please wait...'
search_routers()
运行结果
192.168.2.1 port 80 is open
192.168.56.1 port 80 is open
192.168.1.155 port 80 is open
192.168.1.1 port 80 is open
192.168.1.250 port 80 is open
192.168.1.252 port 80 is open