ctf之AWD(5)_服務器

ctf之AWD(5)_服務器

根據github源碼做了一些修改和添加
內容 : (1)修改mysql密碼 (2)數據庫監控 (3)文件監控

(1)修改mysql密碼

#####  change_mysql.py  #####
# -- coding: utf-8 --
#mysqladmin -uroot -proot password test1234
import os

COLOR_GREEN = '\033[1;32;40m'
COLOR_RED = '\033[1;31;40m'

def change_mysql_pass(db_user, old_pass, new_pass):
    host = '127.0.0.1'
    command = "mysqladmin -h%s -u%s -p%s password %s" % (host, db_user, old_pass, new_pass)
    try:
        c = os.system(command)
        if c == 0:
            print(COLOR_GREEN + '[+]: 修改成功')
        else:
            print(COLOR_RED + '[-]: 修改失敗')
    except Exception as e:
        print(COLOR_RED +'[-]: ' + str(e))
        pass

if __name__ == '__main__':
    db_user = 'root'
    old_pass = 'root'
    new_pass = '123456'
    change_mysql_pass(db_user, old_pass, new_pass)

(2)數據庫監控

文件: (1)main_log_mon_linux.py (2)monitor.py

#####  main_log_mon_linux.py  #####
#coding:utf-8
import subprocess
import time
import pymysql
import os
from monitor import logMonitor

def execSQL(db, sql):
    cursor = db.cursor()
    cursor.execute(sql)
    data = cursor.fetchone()
    return data
    print(time.strftime('[%H:%M:%S]:  ') + str(data ))

def getConfig():
    host = '127.0.0.1'
    port = 3306
    user = 'root'
    password = 'root'
    db_name = 'dvwa'
    charset = 'utf8'
    try:
        # global db
        db = pymysql.connect(host,user,password,db_name,port=port,charset=charset)
        print(time.strftime('[%H:%M:%S]') + 'Database connection succeed.')
        return db
    except:
        print(time.strftime('[%H:%M:%S]') + 'Database connection failed')
        pass

def main():
    # global db
    db = getConfig()
    data = execSQL(db, "SELECT VERSION()")
    print(time.strftime('[%H:%M:%S]') + "The version of database: %s " % data)
    time.sleep(1)
    data = execSQL(db, "show variables like '%general_log%';")[1]
    print(time.strftime('[%H:%M:%S]') + 'The status of log:' + data)
    if data == "OFF":
        try:
            print(time.strftime('[%H:%M:%S]') + 'Starting log mode...')
            time.sleep(1)
            try:
                # logPath = r'D:\\github\\MySQL_Monitor\\'
                logPath = os.getcwd()
                #print(logPath)
                global log
                logName = str(time.strftime('%Y_%m_%d')) + "_log.txt"
                log = logPath + "/" + logName
                #log = log.replace("\\", "/")  # for windows not support to use \ in log file path
                data = execSQL(db, "set global general_log_file='" + log + "';")
            except:
                pass

            data = execSQL(db, "set global general_log=on;")
            data = execSQL(db, "show variables like '%general_log%';")[1]
            if data == "ON":
                print(time.strftime('[%H:%M:%S]') + 'Log is started.')
                print(time.strftime('[%H:%M:%S]') + 'Log monitor running...')
                log = str(execSQL(db, "show variables like 'general_log_file';")[-1])
                logMonitor(log, db)
        except:
            print(time.strftime('[%H:%M:%S]') + 'Log starting failed.')
            exit()
    else:
        print(time.strftime('[%H:%M:%S]') + 'Log monitor running...')
    log = str(execSQL(db, "show variables like 'general_log_file';")[-1])
    db.close()
    logMonitor(log, db)


if __name__ == '__main__':
    #/var/lib/mysql/localhost.log
    main()

#####  monitor.py  #####
#coding:utf-8
import time
import os
import re
import subprocess

prefix = ''


def logMonitor(log, db):

    command = 'tail -f ' + log
    # print("command: {}".format(command))
    popen = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)

    status_monitor = statusMonitor(db)
    try:
        while True:
            
            line = popen.stdout.readline().strip()
            encodeStr = bytes.decode(line)
            if encodeStr != '':
                print('[+]:' +encodeStr)
            else:
                pass
            pattern_query = re.findall('Query\s*(.*)', encodeStr, re.S)
            if len(pattern_query) != 0:
                select_query = pattern_query[0]
                select_query = 'operation: ' + select_query

                pattern_id = re.findall('Z\s*(\d*)', encodeStr, re.S)
                if len(pattern_id) > 0:
                    select_id = pattern_id[0]
                    select_id = 'id: ' + select_id

                    joinTime = time.strftime("[%H:%M:%S]", time.localtime())

                    print(joinTime + '   ' + select_id + '     ' + select_query)
                else:
                    pass

    except KeyboardInterrupt:
        pass


class statusMonitor():

    def __init__(self, db):
        self.db = db
        self.cursor = db.cursor()

        self.staMonitor_SQLdict = {
            'open table': "show global status like 'open%tables%'",
            'thread': "show global status like 'Thread%'",
            'all connections': "show processlist",
            # threads_connected 當前建立的連接
        }


    def show_open_table(self):
        # cursor = self.db.cursor()
        self.db.ping(reconnect=True)
        self.cursor.execute(self.staMonitor_SQLdict['open table'])
        data = self.cursor.fetchall()
        open_tables = data[0][1]
        opened_tables = data[1][1]
        print('Open tables: {}'.format(open_tables))
        print('Opened tables: {}'.format(opened_tables))

    
    def show_thread(self):
        # cursor = self.db.cursor()
        self.db.ping(reconnect=True)
        self.cursor.execute(self.staMonitor_SQLdict['thread'])
        data = self.cursor.fetchall()
        threads_connected = data[1][1]
        threads_running = data[3][1]
        print('Threads connected: {}'.format(threads_connected))
        print('Threads running: {}'.format(threads_running))


    def show_all_connections(self):
        # cursor = self.db.cursor()
        self.db.ping(reconnect=True)
        self.cursor.execute(self.staMonitor_SQLdict['all connections'])
        data = self.cursor.fetchall()
        print('-' * 110)
        print('%-6s%-20s%-20s%-20s%-12s%-10s%-20s' % ('|Id', '|User', '|Host', '|Database', '|Command', '|Time', '|Info'))
        print('-' * 110)
        for user in data:
            print('%-6s' % ('|' + str(user[0])))
            print('%-20s' % ('|' + str(user[1])))
            print('%-20s' % ('|' + str(user[2])))
            print('%-20s' % ('|' + str(user[3])))
            print('%-12s' % ('|' + str(user[4])))
            print('%-10s' % ('|' + str(user[5])))
            print('%-20s' % ('|' + str(user[6])))
            print()
        print('-' * 110)

數據庫監控使用

pip install pymysql
python main_log_mon_linux.py
#默認日誌文件  /var/lib/mysql/localhost.log

py文件打包成elf

#在linux下運行
pip install pyinstaller
pyinstaller -F main_log_mon_linux.py    #打包成單文件
pyinstaller -D main_log_mon_linux.py    #打包成一個目錄,文件大
ldd ***         #查看依賴so文件

#最好的解決方法
pip install pymysql
pip show pymysql        #查看 Location 和 Requires
#將pymysql文件夾複製到main_log_mon_linux.py所在文件夾裏,如果有依賴項,也要把庫複製過來,這樣只要有python環境就可以運行

文件監控

ctf之AWD(6)_服務器
https://blog.csdn.net/qq_38232378/article/details/100930512

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章