Windows file system event

Windows Events

Events are typically used for troubleshooting application and driver software.

  • Prior to WindowsВ Vista, you would use either Event Tracing for Windows (ETW) or Event Logging to log events.
  • WindowsВ Vista introduced a new event model that unified both the Event Tracing for Windows (ETW) and Windows Event Log API.
  • WindowsВ 10 introduces TraceLogging which builds on ETW and provides a simplified way to instrument code for native, .NET and WinRT developers.

The new TraceLogging model allows you to include structured data with events, correlate events, and does not require a separate instrumentation manifest XML file.

The WindowsВ Vista model uses an XML manifest to define the events that you want to publish. Events can be published to a channel or an ETW session. You can publish the events to the following types of channels: Admin, Operational, Analytic and Debug. If you use only ETW to enable the publisher, you do not need to specify channels in your manifest. For complete details on writing a manifest, see Writing an Instrumentation Manifest, and for information on channels, see Defining Channels.

To register your event publisher and to publish events, you use the ETW API. For details, see Providing Events and Developing a Provider. The event publisher will automatically write the events to the channels specified in the manifest if they are enabled.

If you want to control the events that an event publisher publishes at a finer level of granularity, use the ETW API. For example, if the manifest defines both write and read events, you can enable only the write events. An event can also specify a level value such as warning or error, so you can limit the events that are written to those that specify the error level. For details, see Controlling Event Tracing Sessions. The events are written to the session’s log file.

Consuming events involves retrieving the events from an event channel, an event log file (.evtx or .evt files), a trace file (.etl files), or a real-time ETW session. To consume events from an ETW trace file or a real-time ETW session, use the trace data helper (TDH) functions in ETW to consume the events. You can also use TDH to read the event metadata. For details, see Consuming Events. To consume events from an event channel or an event log file, use the Windows Event Log functions to query or subscribe to events. For more information, see Querying for Events or Subscribing to Events.

Prior to WindowsВ Vista, you must use Event Tracing for Windows or Event Logging to publish and consume events.

File System Event Handler Делегат

Определение

Представляет метод, обрабатывающий события Changed, Created или Deleted класса FileSystemWatcher. Represents the method that will handle the Changed, Created, or Deleted event of a FileSystemWatcher class.

Параметры

Источник события. The source of the event.

Объект класса FileSystemEventArgs, содержащий данные о событии. The FileSystemEventArgs that contains the event data.

Примеры

В следующем примере показано, как создать FileSystemWatcher для отслеживания изменений в файле (создание, удаление, переименование, изменение), происходящих на диске. The following example shows how to create a FileSystemWatcher to monitor file changes (creates, deletes, renames, changes) occurring on a disk drive. В примере также показано, как правильно получать уведомления об ошибках. The example also shows how to properly receive error notifications.

Комментарии

При создании делегата FileSystemEventHandler необходимо указать метод, обрабатывающий событие. When you create a FileSystemEventHandler delegate, you identify the method that will handle the event. Чтобы связать событие с обработчиком событий, нужно добавить в событие экземпляр делегата. To associate the event with your event handler, add an instance of the delegate to the event. Обработчик событий вызывается всякий раз, когда происходит событие, если делегат не удален. The event handler is called whenever the event occurs, unless you remove the delegate. Дополнительные сведения о делегатах обработчиков событий см. в разделе обработка и вызов событий. For more information about event handler delegates, see Handling and Raising Events.

Методы расширения

Получает объект, представляющий метод, представленный указанным делегатом. Gets an object that represents the method represented by the specified delegate.

Аудит удаления файлов в сетевой папке на Windows Server

С помощью аудита событий доступа к объектам файловой системы вы можете определить конкретного пользователя, который создал, удалил или изменил определенный файл. В этой статье мы покажем, как настроить аудит событий удаления объектов в общей сетевой папке на Windows Server 2016. После настройки аудита, вы можете с помощью информации в журнале событий найти пользователя, который удалил на файловом сервере.

Читайте также:  Как загрузить шрифт windows

Включаем политику аудита доступа к файлам и папкам в Windows

По умолчанию в Windows Server не включен аудит событий доступа к объектам на файловой системе. Вы можете включить и настроить аудит событий с помощью групповой политики. Если нужно включить политики аудита на нескольких серверах или компьютера, можно использовать доменные GPO (настраиваются с помощью консоли управления gpmc.msc). Если нужно настроить аудит только на одном сервере, можно воспользоваться локальной групповой политикой.

  1. Запустите консоль редактора локальной политики – gpedit.msc ;
  2. Перейдитевраздел GPO срасширенными политиками аудитаWindows Settings -> Security Settings -> Advanced Audit Policy Configuration -> Object Access;
  3. Откройте политику Audit File System и укажите, что вы хотите сохранять в журнал только успешные события доступа к объектам файловой системы (Configure the following audit events -> Success);

Настройка аудита событий удаления файлов из конкретной папки

Теперь нужно настроить аудит в свойствах общей сетевой папки, доступ к которой вы хотите отслеживать. Запустите проводник и откройте свойства общей папки. Перейдите на вкладку Security. Нажмите кнопку Advanced -> вкладка Auditing.

Если появится сообщение You must be an administrator or have been given the appropriate privileges to view the audit properties of this object, нажмите кнопку Continue.

Затем нажмите кнопку Add чтобы указать пользователя или группу, для которых нужно записывать все события аудита. Если вы хотите отслеживать события для всех пользователей, укажите группу Everyone.

Затем нужно указать использование каких разрешений доступа к объекту нужно записывать в лог. Чтобы сохранять в Event Log только события удаления файлов, нажмите кнопку Show advanced permissions. В списке событий оставьте аудит только для событий удаления папок и файлов — Delete и Delete subfolders and files.

$Path = «D:\Public»
$AuditChangesRules = New-Object System.Security.AccessControl.FileSystemAuditRule(‘Everyone’, ‘Delete,DeleteSubdirectoriesAndFiles’, ‘none’, ‘none’, ‘Success’)
$Acl = Get-Acl -Path $Path
$Acl.AddAuditRule($AuditChangesRules)
Set-Acl -Path $Path -AclObject $Acl

Теперь, если пользователь удалит любой файл или папку в сетевой папке, в журнале безопасности системы появляется событие File System -> Audit Succes c Event ID 4663 от источника Microsoft Windows security auditing.

Откройте mmc консоль Event Viewer ( eventvwr.msc ), разверните секцию Windows Logs -> Security. Включите фильтр событий по EventID 4663.

Откройте любой их оставшихся событий в Event Viewer. Как вы видите, в нем есть информация об имени удаленного файла и учетной записи пользователя, который удалил файл.

После настройки аудита, найдите в журнале Security вы сможете найти с:

  • Кто и когда удалил файл в сетевой папке;
  • Из какого приложения удален файл;
  • На какой момент времени нужно восстанавливать бэкап данного каталога.

Запись событий удаления файлов в SQL базу (MySQL/MSSQL)

Если после включения аудита удаления файлов в сетевой папке, вы видите в журнале много событий, найти что-то в логах бывает проблематично. Во-первых, найти нужную запись среди тысячи событий довольно сложно (в Windows отсутствуют вменяемые средства поиска интересующего события с возможностью гибкой фильтрации), а во-вторых, если файл был удален давно, это событие может просто отсутствовать в журнале, т.к. было перезатерто более новыми.

Вы можете записывать все нужные событий в отдельную SQL базу данных. Для хранения событий можно использовать Microsoft SQL Server, Elasticsearch или MySQL/MariaDB.

В этом примере мы покажем, как записывать события аудита в отдельную таблицу БД на сервере MySQL. Формат таблицы:

  • Имя сервера;
  • Имя удаленного файла
  • Время удаления;
  • Имя пользователя, удалившего файл.

MySQL запрос на создание такой таблицы будет выглядеть так:

CREATE TABLE track_del (id INT NOT NULL AUTO_INCREMENT, server VARCHAR(100), file_name VARCHAR(255), dt_time DATETIME, user_name VARCHAR(100), PRIMARY KEY (ID));

Если вы хотите использовать Microsoft SQL, обратите внимание на статью “Как выполнить запрос к MSSQL Server из скрипта PowerShell?”.

Для получения событий с EventID 4663 из журнала Security за текущий день можно использовать такой PowerShell скрипт:

$today = get-date -DisplayHint date -UFormat %Y-%m-%d
Get-WinEvent -FilterHashTable @ | Foreach <
$event = [xml]$_.ToXml()
if($event)
<
$Time = Get-Date $_.TimeCreated -UFormat «%Y-%m-%d %H:%M:%S»
$File = $event.Event.EventData.Data[6].»#text»
$User = $event.Event.EventData.Data[1].»#text»
$Computer = $event.Event.System.computer
>
>

Следующий PowerShell скрипт запишет полученные данные в БД MySQL на удаленном сервере:

Set-ExecutionPolicy RemoteSigned
Add-Type –Path ‘C:\Program Files (x86)\MySQL\MySQL Connector Net 6.9.8\Assemblies\v4.5\MySql.Data.dll’
$Connection = [MySql.Data.MySqlClient.MySqlConnection]@
$Connection.Open()
$sql = New-Object MySql.Data.MySqlClient.MySqlCommand
$sql.Connection = $Connection
$today = get-date -DisplayHint date -UFormat %Y-%m-%d
Get-WinEvent -FilterHashTable @ | Foreach <
$event = [xml]$_.ToXml()
if($event)
<
$Time = Get-Date $_.TimeCreated -UFormat «%Y-%m-%d %H:%M:%S»
$File = $event.Event.EventData.Data[6].»#text»

$File = $File.Replace(‘\’,’|’)
$User = $event.Event.EventData.Data[1].»#text»
$Computer = $event.Event.System.computer
$sql.CommandText = «INSERT INTO track_del (server,file_name,dt_time,user_name ) VALUES (‘$Computer’,’$File’,’$Time’,’$User’)»
$sql.ExecuteNonQuery()
>
>
$Reader.Close()
$Connection.Close()

Теперь, чтобы узнать, кто удалил файл «document1 — Copy.DOC». Достаточно в консоли PowerShell выполнить следующий скрипт.

$DeletedFile = «%document1 — Copy.DOC%»
Set-ExecutionPolicy RemoteSigned
Add-Type –Path ‘C:\Program Files (x86)\MySQL\MySQL Connector Net 6.9.8\Assemblies\v4.5\MySql.Data.dll’
$Connection = [MySql.Data.MySqlClient.MySqlConnection]@
$Connection.Open()
$MYSQLCommand = New-Object MySql.Data.MySqlClient.MySqlCommand
$MYSQLDataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter
$MYSQLDataSet = New-Object System.Data.DataSet
$MYSQLCommand.Connection=$Connection
$MYSQLCommand.CommandText=»SELECT user_name,dt_time from track_del where file_name LIKE ‘$DeletedFile'»
$MYSQLDataAdapter.SelectCommand=$MYSQLCommand
$NumberOfDataSets=$MYSQLDataAdapter.Fill($MYSQLDataSet, «data»)
foreach($DataSet in $MYSQLDataSet.tables[0])
<
write-host «User:» $DataSet.user_name «at:» $DataSet.dt_time
>
$Connection.Close()

В результате в консоли PS появится имя пользователя и время удаления файла.

Скрипт сброса данных из журнала в БД можно выполнять один раз в конце дня по планировщику или повесить триггер на событие удаления (On Event), что более ресурсоемко. Все зависит от требования к системе.

Можно создать реагировать простую веб страницу на php для получения информации о событиях удаления файлов в более удобном виде. Задача решается силами любого php программиста за 1-2 часа.

Запись информации о событиях удаления файлов в текстовый файл

Если вы не хотите вести отдельную БД, можно сохранять события аудита удалений файлов в текстовый лог файл. Воспользуйтесь таким PowerShell скриптом:

$Outfile = «C:\ps\delete-file-log.txt»
$today = get-date -DisplayHint date -UFormat %Y-%m-%d
Get-WinEvent -FilterHashTable @ | Foreach <
$event = [xml]$_.ToXml()
if($event)
<
$Time = Get-Date $_.TimeCreated -UFormat «%Y-%m-%d %H:%M:%S»
$File = $event.Event.EventData.Data[6].»#text»
$User = $event.Event.EventData.Data[1].»#text»
$strLog = $Computer + » » + $File + » » + $Time + » » + $User
$strLog | out-file $Outfile –append
>
>

Итак, мы предложили идею и некий общий каркас системы аудита и хранения информации об удаленных файлах в сетевых шарах, при желании ее с лёгкостью можно будет модифицировать под ваши нужды.

File System Watcher Class

Definition

Listens to the file system change notifications and raises events when a directory, or file in a directory, changes.

Examples

The following example creates a FileSystemWatcher to watch the directory specified at run time. The component is set to watch for changes in LastWrite and LastAccess time, the creation, deletion, or renaming of text files in the directory. If a file is changed, created, or deleted, the path to the file prints to the console. When a file is renamed, the old and new paths print to the console.

Remarks

Use FileSystemWatcher to watch for changes in a specified directory. You can watch for changes in files and subdirectories of the specified directory. You can create a component to watch files on a local computer, a network drive, or a remote computer.

To watch for changes in all files, set the Filter property to an empty string («») or use wildcards («*.*»). To watch a specific file, set the Filter property to the file name. For example, to watch for changes in the file MyDoc.txt, set the Filter property to «MyDoc.txt». You can also watch for changes in a certain type of file. For example, to watch for changes in text files, set the Filter property to «*.txt».

There are several types of changes you can watch for in a directory or file. For example, you can watch for changes in Attributes , the LastWrite date and time, or the Size of files or directories. This is done by setting the NotifyFilter property to one of the NotifyFilters values. For more information on the type of changes you can watch, see NotifyFilters.

You can watch for renaming, deletion, or creation of files or directories. For example, to watch for renaming of text files, set the Filter property to «*.txt» and call the WaitForChanged method with a Renamed specified for its parameter.

The Windows operating system notifies your component of file changes in a buffer created by the FileSystemWatcher. If there are many changes in a short time, the buffer can overflow. This causes the component to lose track of changes in the directory, and it will only provide blanket notification. Increasing the size of the buffer with the InternalBufferSize property is expensive, as it comes from non-paged memory that cannot be swapped out to disk, so keep the buffer as small yet large enough to not miss any file change events. To avoid a buffer overflow, use the NotifyFilter and IncludeSubdirectories properties so you can filter out unwanted change notifications.

For a list of initial property values for an instance of FileSystemWatcher, see the FileSystemWatcher constructor.

Please note the following when using the FileSystemWatcher class.

Hidden files are not ignored.

In some systems, FileSystemWatcher reports changes to files using the short 8.3 file name format. For example, a change to «LongFileName.LongExtension» could be reported as «LongFil

This class contains a link demand and an inheritance demand at the class level that applies to all members. A SecurityException is thrown when either the immediate caller or the derived class does not have full-trust permission. For details about security demands, see Link Demands.

The maximum size you can set for the InternalBufferSize property for monitoring a directory over the network is 64 KB.

Copying and moving folders

The operating system and FileSystemWatcher object interpret a cut-and-paste action or a move action as a rename action for a folder and its contents. If you cut and paste a folder with files into a folder being watched, the FileSystemWatcher object reports only the folder as new, but not its contents because they are essentially only renamed.

To be notified that the contents of folders have been moved or copied into a watched folder, provide OnChanged and OnRenamed event handler methods as suggested in the following table.

Event Handler Events Handled Performs
OnChanged Changed, Created, Deleted Report changes in file attributes, created files, and deleted files.
OnRenamed Renamed List the old and new paths of renamed files and folders, expanding recursively if needed.

Events and Buffer Sizes

Note that several factors can affect which file system change events are raised, as described by the following:

Common file system operations might raise more than one event. For example, when a file is moved from one directory to another, several OnChanged and some OnCreated and OnDeleted events might be raised. Moving a file is a complex operation that consists of multiple simple operations, therefore raising multiple events. Likewise, some applications (for example, antivirus software) might cause additional file system events that are detected by FileSystemWatcher.

The FileSystemWatcher can watch disks as long as they are not switched or removed. The FileSystemWatcher does not raise events for CDs and DVDs, because time stamps and properties cannot change. Remote computers must have one of the required platforms installed for the component to function properly.

Note that a FileSystemWatcher may miss an event when the buffer size is exceeded. To avoid missing events, follow these guidelines:

Increase the buffer size by setting the InternalBufferSize property.

Avoid watching files with long file names, because a long file name contributes to filling up the buffer. Consider renaming these files using shorter names.

Keep your event handling code as short as possible.

Constructors

Initializes a new instance of the FileSystemWatcher class.

Initializes a new instance of the FileSystemWatcher class, given the specified directory to monitor.

Initializes a new instance of the FileSystemWatcher class, given the specified directory and type of files to monitor.

Properties

Gets a value indicating whether the component can raise an event.

(Inherited from Component) Container

Gets the IContainer that contains the Component.

(Inherited from Component) DesignMode

Gets a value that indicates whether the Component is currently in design mode.

(Inherited from Component) EnableRaisingEvents

Gets or sets a value indicating whether the component is enabled.

Gets the list of event handlers that are attached to this Component.

(Inherited from Component) Filter

Gets or sets the filter string used to determine what files are monitored in a directory.

Gets the collection of all the filters used to determine what files are monitored in a directory.

Gets or sets a value indicating whether subdirectories within the specified path should be monitored.

Gets or sets the size (in bytes) of the internal buffer.

Gets or sets the type of changes to watch for.

Gets or sets the path of the directory to watch.

Gets or sets an ISite for the FileSystemWatcher.

Gets or sets the object used to marshal the event handler calls issued as a result of a directory change.

Methods

Begins the initialization of a FileSystemWatcher used on a form or used by another component. The initialization occurs at run time.

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject) Dispose()

Releases the unmanaged resources used by the FileSystemWatcher.

Releases all resources used by the Component.

(Inherited from Component) Dispose(Boolean)

Releases the unmanaged resources used by the FileSystemWatcher and optionally releases the managed resources.

Ends the initialization of a FileSystemWatcher used on a form or used by another component. The initialization occurs at run time.

Determines whether the specified object is equal to the current object.

(Inherited from Object) Finalize()

Releases the resources held by the current instance.

Serves as the default hash function.

(Inherited from Object) GetLifetimeService()

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject) GetService(Type)

Returns an object that represents a service provided by the Component or by its Container.

(Inherited from Component) GetType()

Gets the Type of the current instance.

(Inherited from Object) InitializeLifetimeService()

Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject) MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object) MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject) OnChanged(FileSystemEventArgs)

Raises the Changed event.

Raises the Created event.

Raises the Deleted event.

Raises the Error event.

Raises the Renamed event.

Returns a String containing the name of the Component, if any. This method should not be overridden.

(Inherited from Component) ToString()

Returns a string that represents the current object.

(Inherited from Object) WaitForChanged(WatcherChangeTypes)

A synchronous method that returns a structure that contains specific information on the change that occurred, given the type of change you want to monitor.

A synchronous method that returns a structure that contains specific information on the change that occurred, given the type of change you want to monitor and the time (in milliseconds) to wait before timing out.

Events

Occurs when a file or directory in the specified Path is changed.

Occurs when a file or directory in the specified Path is created.

Occurs when a file or directory in the specified Path is deleted.

Occurs when the component is disposed by a call to the Dispose() method.

(Inherited from Component) Error

Occurs when the instance of FileSystemWatcher is unable to continue monitoring changes or when the internal buffer overflows.

Occurs when a file or directory in the specified Path is renamed.

Читайте также:  Кмс активатор windows 10 2004
Оцените статью