# -*- coding: utf-8 -*-
'''
на входе папка или файл, на выходе CSV: имя файла;сумма мд5;папка полностью;имя компа
'''
import os
import hashlib
import platform
import time
import sys
class MyItem:
def __init__(self, f):
self.hostname = hostname
self.md5sum = md5(f)
self.size = os.path.getsize(f)
self.created = "%s" % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(os.path.getctime(f)))
self.modified = "%s" % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(os.path.getmtime(f)))
self.ext = os.path.splitext(f)[1]
self.full_dir, self.file_name = os.path.split(os.path.abspath(f))
def md5(fname): # https://stackoverflow.com/questions/3431825/generating-an-md5-checksum-of-a-file
hash_md5 = hashlib.md5()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
hostname = platform.node()
result_header = "file_name;md5sum;size;created;modified;ext;full_path;hostname\n"
result_file = open('./result.csv','w')
result_file.write(result_header)
targets = []
if len(sys.argv) > 1:
targets = sys.argv[1::]
else:
targets.append(".")
for t in targets:
if os.path.exists(t):
if os.path.isdir(t):
for current_dir, dirs, files in os.walk(t):
for f in files:
try:
i = os.path.join(current_dir, f)
print(i)
item = MyItem(i)
result_file.write('%s;%s;%s;%s;%s;%s;%s;%s\n'%(item.file_name, item.md5sum, item.size, item.created, item.modified, item.ext, item.full_dir, item.hostname))
except:
print('Error!')
if os.path.isfile(t):
try:
i = t
print(i)
item = MyItem(i)
result_file.write('%s;%s;%s;%s;%s;%s;%s;%s\n'%(item.file_name, item.md5sum, item.size, item.created, item.modified, item.ext, item.full_dir, item.hostname))
except:
print('Error!')
result_file.close()
Архив метки: md5
md5deep
-r Enables recursive mode. All subdirectories are traversed. Please note that recursive mode cannot be used to examine all files
of a given file extension. For example, calling md5deep -r *.txt will examine all files in directories that end in .txt.
-e Displays a progress indicator and estimate of time remaining for each file being processed. Time estimates for files larger
than 4GB are not available on Windows. This mode may not be used with th -p mode.
-t Display a timestamp in GMT with each result. On Windows this timestamp will be the file’s creation time. On all other systems
it should be the file’s change time.
-z Enables file size mode. Prepends the hash with a ten digit representation of the size of each file processed. If the file
size is greater than 9999999999 bytes (about 9.3GB) the program displays 9999999999 for the size.
-o <bcpflsd>
Enables expert mode. Allows the user specify which (and only which) types of files are processed. Directory processing is
still controlled with the -r flag. The expert mode options allowed are:
f — Regular files
b — Block Devices
c — Character Devices
p — Named Pipes
l — Symbolic Links
s — Sockets
d — Solaris Doors
e — Windows PE executables
Мониторинг изменений файлов в linux
Скрипт взял здесь http://www.iamroot.ru/2013/01/kontrol-izmeneniya-fajlov-v-linux.html
Скрипт:
#!/bin/bash ulimit -t 20 checkdir="/bin /sbin" filedb="/var/tmp/permsecdb" email="test@iamroot.ru" out=$( exec 2>&1 umask 266 find $checkdir -type f -printf "%m\t" -exec md5sum {} \; >$filedb.tmp diff $filedb $filedb.tmp mv -f $filedb.tmp $filedb ) if [ "$out" ];then (date; echo; echo "$out") | mail -s "Change permsec `hostname`" $email fi
Скрипт проходится по всем файлам в папках из checkdir, считает их контрольные суммы MD5, результаты записывает в файл filedb и сравнивает его с результатами прошлой проверки командой diff. Если обнаружены изменения, отправляется оповещение на test@iamroot.ru, если нет, то ничего не происходит. Скрипт надо добавлять заданием в cron, чтоб выполнялся по расписанию.