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()