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

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

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

效果如下:

源文件如下:

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

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)


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):
          scan01(file)
 
    def on_created(self, event):
        print("文件被創建了 %s" % event.src_path)
        file=event.src_path
        if os.path.isfile(file):
          scan01(file)
 
 
if __name__ == "__main__":
    path = a
    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()

 

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