Python监测局域网内弱密码的Mysql服务器

wylc123 1年前 ⋅ 4925 阅读

一、功能描述

        Python实现获取局域网内可ping通的IP,并验证这些IP中开通了Mysql服务,切用户名为root,密码为列举的弱密码的主机。

二、 技能点

  1. Python读取控制台命令返回值
  2.  多线程跑数据
  3.  Python连接Mysql数据库

三、代码

      1. 获取局域网可ping通IP
#!usr/bin/env python
# -*- coding: utf-8 -*-
#!文件类型: python
#!创建时间: 2020/8/26 14:32
#!作者: SongBin
#!文件名称: GetLanIP.py
#!简介:获取局域网内所有机器IP地址与网卡MAC地址
import queue
import threading
import time
import os
import platform

live_ip = 0
exitFlag = 0

class myThread(threading.Thread):
    def __init__(self, threadID, name, q):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.q = q

    def run(self):
        # print("Starting " + self.name)
        process_data(self.name, self.q)
        # print("Exiting " + self.name)



def process_data(threadName, q):
    while not exitFlag>0:
        # queueLock.acquire()
        if not workQueue.empty():
            data = q.get()
            ping_ip(data)
            # queueLock.release()
            # print("%s processing %s" % (threadName, data))
        # else:
            # queueLock.release()
            # print ("队列为空")


def get_os():
    os = platform.system()
    if os == "Windows":
        return "n"
    else:
        return "c"


def ping_ip(ip_str):
    cmd = ["ping", "-{op}".format(op=get_os()),
           "1", ip_str]
    output = os.popen(" ".join(cmd)).readlines()
    for line in output:
        if str(line).upper().find("TTL") >= 0:
            print("ip: %s is ok ***" % ip_str)
            global live_ip
            live_ip += 1
            break
        if (str(line).upper().find("请求超时") >= 0 or str(line).upper().find("无法访问目标主机") >= 0):
            break

def find_ip(ip_prefix):
    ips = []
    # The number of workers.
    '''''
    给出当前的ip地址段 ,然后扫描整个段所有地址
    '''
    for i in range(5, 256):
        for n in range(1, 256):
            ip = '%s.%s.%s' % (ip_prefix,i, n)
            ips.append(ip)
    return ips


print("开始扫描时间: %s" % time.ctime())
queueLock = threading.Lock()
NUM_WORKERS = 30
workQueue = queue.Queue(NUM_WORKERS)
threads = []


# 创建新线程
for n in range(NUM_WORKERS):
    thread = myThread(n, "Thread-"+str(n), workQueue)
    thread.start()
    threads.append(thread)

# 填充队列
ips = find_ip('192.168')
# queueLock.acquire()
for ip in ips:
    workQueue.put(ip)
    # print ("队列添加"+ip)
# queueLock.release()

# 等待队列清空
while not workQueue.empty():
    pass

# 通知线程是时候退出
exitFlag = 1

# 等待所有线程完成
for t in threads:
    t.join()
print("Exiting Main Thread")
print("扫描结束时间 %s" % time.ctime())
print('本次扫描共检测到本网络存在%s台设备' % live_ip)
        2.  获取可以连接的Mysql服务器
#!usr/bin/env python
# -*- coding: utf-8 -*-
#!文件类型: python
#!创建时间: 2020/8/31 15:06
#!作者: SongBin
#!文件名称: GetIpToMysql.py
#!简介:判断局域网中可拼通的IP上是否有弱密码的Mysql数据库

# 导入pymysql模块
import pymysql
import queue
import threading
import time
import os
import platform

live_ip = 0
exitFlag = 0

class myThread(threading.Thread):
    def __init__(self, threadID, name, q):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.q = q

    def run(self):
        # print("Starting " + self.name)
        process_data(self.name, self.q)
        # print("Exiting " + self.name)



def process_data(threadName, q):
    while not exitFlag>0:
        # queueLock.acquire()
        if not workQueue.empty():
            data = q.get()
            tryMysqlConn(data)
            # queueLock.release()
            # print("%s processing %s" % (threadName, data))
        # else:
            # queueLock.release()
            # print ("队列为空")


#测试mysql是否可以链接
def tryMysqlConn(host):
    pws = ['123456', 'cnkittod', 'ttod', 'cnki', '111111', '888888', '666666', '000000', '112233']
    for password in pws:
        try:
            # 连接database
            conn = pymysql.connect(
                host=host,
                user="root",
                password=password,
                database="",
                charset="utf8")

            # 得到一个可以执行SQL语句的光标对象
            cursor = conn.cursor()  # 执行完毕返回的结果集默认以元组显示
            # 得到一个可以执行SQL语句并且将结果作为字典返回的游标
            # cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

            # 定义要执行的SQL语句
            sql = "SELECT VERSION()"

            # 执行SQL语句
            cursor.execute(sql)

            # 关闭光标对象
            cursor.close()

            # 关闭数据库连接
            conn.close()

            flag = "can link"
            print('Mysql连接状态:%s ### %s ### %s' % (host, password, flag))
            global live_ip
            live_ip += 1
            f.write(host+'######'+password + '\n')
            break
        except:
            flag = "not link"
            print('Mysql连接状态:%s ### %s ### %s' % (host, password, flag))
            continue

print("开始扫描时间: %s" % time.ctime())
f = open('d:\\can_link_ips.txt', 'w', encoding="utf-8")
queueLock = threading.Lock()
NUM_WORKERS = 50
workQueue = queue.Queue(NUM_WORKERS)
threads = []

# 创建新线程
for n in range(NUM_WORKERS):
    thread = myThread(n, "Thread-"+str(n), workQueue)
    thread.start()
    threads.append(thread)

# 填充队列
file = open("d:\\mysql_ip.txt")
# queueLock.acquire()
for line in file.readlines():
    ip = line.strip('\n')
    workQueue.put(ip)
    # print ("队列添加"+ip)
# queueLock.release()

# 等待队列清空
while not workQueue.empty():
    pass

# 通知线程是时候退出
exitFlag = 1

# 等待所有线程完成
for t in threads:
    t.join()
print("Exiting Main Thread")
print("扫描结束时间 %s" % time.ctime())
print('本次扫描共检测到本网络存在%s台设备可连接mysql' % live_ip)

 

更多内容请访问:IT源点

相关文章推荐

全部评论: 0

    我有话说: