Python 練習之 監控目錄下是否創建、修改文件,並用pyclamd掃描(加入Logging)

Python 練習之 監控目錄下是否創建、修改文件,並用pyclamd掃描(加入Logging)

#Time: 2020/03/31
#Author: Xiaohong
#運行環境: OS: Raspberry Pi 4
#  Python: 3.7
功能: 1.用WatchDog 檢測目錄   2. 用 pyclamd 掃描變動 3.用Logging 記錄關鍵動作

log的配置文件:logconfig.ini:

[loggers]
keys=root

[handlers]
keys=fileHandler, errorFileHandler,criticalFileHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=INFO
handlers=fileHandler,errorFileHandler,criticalFileHandler

[handler_fileHandler]
class=FileHandler
level=INFO
formatter=simpleFormatter
args=('watchdog.log', 'a')

[handler_errorFileHandler]
class=FileHandler
level=ERROR
formatter=simpleFormatter
args=('watchdog-error.log', 'a')

[handler_criticalFileHandler]
class=FileHandler
level=CRITICAL
formatter=simpleFormatter
args=('watchdog-critica.log', 'a')

[formatter_simpleFormatter]
format=%(asctime)s -%(name)s - %(levelname)s - %(message)s

源文件:

from watchdog.observers import Observer
from watchdog.events import *
import time
import pyclamd
from threading import Thread
import os
import logging
import logging.config

a = r"/home/pi/ClamLogs"
#a = r"F:\360Downloads"


class Scan2(Thread):  # 繼承多線程Thread類
    def __init__(self, IP, scan_type, file):
        """構造方法"""
        Thread.__init__(self)
        self.IP = IP
        self.scan_type = scan_type
        self.file = file
        self.connstr = ""
        self.scanresult = ""

    def run(self):
        """多進程run方法"""
        try:
            cd = pyclamd.ClamdNetworkSocket('127.0.0.1', 3310)
            """探測連通性"""
            if cd.ping():
                self.connstr = self.IP+" connection [OK]"
                """重載clamd病毒特徵庫"""
                cd.reload()
                """判斷掃描模式"""
                if self.scan_type == "contscan_file":
                    self.scanresult = "{0}\n".format(
                        cd.contscan_file(self.file))
                elif self.scan_type == "multiscan_file":
                    self.scanresult = "{0}\n".format(
                        cd.multiscan_file(self.file))
                elif self.scan_type == "scan_file":
                    self.scanresult = "{0}\n".format(cd.scan_file(self.file))
                time.sleep(1)
            else:
                self.connstr = self.IP+" ping error,exit"
                return
        except Exception as e:
            self.connstr = self.IP+" "+str(e)
        else:
            if self.scanresult.strip() == 'None':
                logging.info('%s File Scan no virus!'%self.file)
                print('is None')
                pass
            else:
                print('Not None')
                if 'FOUND' in self.scanresult:
                    print('Found!')                    
                    logging.critical('%s File Scan virus!!!Begin Remove'%self.file)
                    #scan_command = '/usr/bin/clamscan -i --remove '+self.file
                    #os.system(scan_command)
                    #logging.critical('%s File Removed !!!!'%self.file)
                else:
                    print('Access')
                    logging.error('%s File Access denied!'%self.file)
                    #print(self.scanresult)

def scan01(scanfile2):
    IPs = ['127.0.0.1']  # 掃描主機的列表
    scantype = "multiscan_file"  # 指定掃描模式,支持 multiscan_file、contscan_file、scan_file
    scanfile = scanfile2  # 指定掃描路徑
    i = 1
    threadnum = 2  # 指定啓動的線程數
    scanlist = []  # 存儲Scan類線程對象列表
    for ip in IPs:
        """將數據值帶入類中,實例化對象"""
        currp = Scan2(ip, scantype, scanfile)
        scanlist.append(currp)  # 追加對象到列表
        """當達到指定的線程數或IP列表數後啓動線程"""
        if i % threadnum == 0 or i == len(IPs):
            for task in scanlist:
                task.start()  # 啓動線程
            for task in scanlist:
                task.join()  # 等待所有子線程退出,並輸出掃描結果
                print(task.connstr)  # 打印服務器連接信息
                print(task.scanresult)  # 打印結果信息
                scanlist = []
        i += 1


class MyHandler(FileSystemEventHandler):
    def on_modified(self, event):
        print("文件被修改了 %s" % event.src_path)
        file = event.src_path
        if os.path.isfile(file):
            if '/.' not in file:
                logging.info('File Modified or Created :%s'%file)                
                scan01(file)

if __name__ == "__main__":
    path = a
    logging.config.fileConfig('logconfig.ini')
    event_handler = MyHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()

    try:
        while True:
            time.sleep(1)

    except KeyboardInterrupt:
        observer.stop()
    observer.join()

 

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