Python扫描端口

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值