检测网络驱动器挂载wmi

发布于 2024-12-18 07:28:23 字数 564 浏览 1 评论 0原文

如何使用 wmi 检测网络驱动器安装事件?我主要感兴趣的是像 Win32_VolumeChangeEvent 这样的网络驱动器。

 _eventWatcher = new ManagementEventWatcher("SELECT * FROM Win32_VolumeChangeEvent");

 _eventWatcher.EventArrived += (o, args) => 
     {switch(args.NewEvent["EventType"].ToString()[0])
         {
             case '2':
                 //mount
                 Debug.WriteLine(args.NewEvent["DriveName"]);
                 break;
             case '3':
                 //unmount
                 break;
         }
     };

 _eventWatcher.Start();

提前致谢。

How to detect network drive mount event using wmi ? I'm mainly interested i something like Win32_VolumeChangeEvent just for network drives.

 _eventWatcher = new ManagementEventWatcher("SELECT * FROM Win32_VolumeChangeEvent");

 _eventWatcher.EventArrived += (o, args) => 
     {switch(args.NewEvent["EventType"].ToString()[0])
         {
             case '2':
                 //mount
                 Debug.WriteLine(args.NewEvent["DriveName"]);
                 break;
             case '3':
                 //unmount
                 break;
         }
     };

 _eventWatcher.Start();

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

兰花执着 2024-12-25 07:28:23

您可以使用此查询(我使用 Powershell 进行快速测试,但您可以轻松转换为 C#)

$query = "SELECT * FROM __instanceCreationEvent WITHIN 5 WHERE TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.DriveType=4"

Register-WMIEvent -Query $query -Action {$global:a=$Args[0];$global:b=$Args[1];write-host "done" }

Id              Name            State      HasMoreData     Location  Command
--              ----            -----      -----------     --------  -------
14              f2c5223d-3ae... NotStarted False                     $global:a=$Args[0];$gl...


PS C:\> net use
Les nouvelles connexions seront mémorisées.

La liste est vide.

PS C:\> net use o: \\jpbhpp2\c$
La commande s'est terminée correctement.

PS C:\> done


PS C:\> $a


Scope     : System.Management.ManagementScope
Query     : System.Management.EventQuery
Options   : System.Management.EventWatcherOptions
Site      :
Container :



PS C:\> $b

NewEvent                                                    Context
--------                                                    -------
System.Management.ManagementBaseObject                      {}


PS C:\> $b.NewEvent


__GENUS             : 2
__CLASS             : __InstanceCreationEvent
__SUPERCLASS        : __InstanceOperationEvent
__DYNASTY           : __SystemClass
__RELPATH           :
__PROPERTY_COUNT    : 3
__DERIVATION        : {__InstanceOperationEvent, __Event, __IndicationRelated, __SystemClass}
__SERVER            : WM2008R2ENT
__NAMESPACE         : //./root/CIMV2
__PATH              :
SECURITY_DESCRIPTOR :
TargetInstance      : System.Management.ManagementBaseObject
TIME_CREATED        : 129670237461553750



PS C:\> $b.NewEvent.TargetInstance


__GENUS                      : 2
__CLASS                      : Win32_LogicalDisk
__SUPERCLASS                 : CIM_LogicalDisk
__DYNASTY                    : CIM_ManagedSystemElement
__RELPATH                    : Win32_LogicalDisk.DeviceID="O:"
__PROPERTY_COUNT             : 40
__DERIVATION                 : {CIM_LogicalDisk, CIM_StorageExtent, CIM_LogicalDevice, CIM_LogicalElement...}
__SERVER                     : WM2008R2ENT
__NAMESPACE                  : root\CIMV2
__PATH                       : \\WM2008R2ENT\root\CIMV2:Win32_LogicalDisk.DeviceID="O:"
Access                       : 0
Availability                 :
BlockSize                    :
Caption                      : O:
Compressed                   : False
ConfigManagerErrorCode       :
ConfigManagerUserConfig      :
CreationClassName            : Win32_LogicalDisk
Description                  : Connexion réseau
DeviceID                     : O:
DriveType                    : 4
ErrorCleared                 :
ErrorDescription             :
ErrorMethodology             :
FileSystem                   : NTFS
FreeSpace                    : 36223737856
InstallDate                  :
LastErrorCode                :
MaximumComponentLength       : 255
MediaType                    : 0
Name                         : O:
NumberOfBlocks               :
PNPDeviceID                  :
PowerManagementCapabilities  :
PowerManagementSupported     :
ProviderName                 : \\jpbhpp2\c$
Purpose                      :
QuotasDisabled               : True
QuotasIncomplete             : False
QuotasRebuilding             : False
Size                         : 500000878592
Status                       :
StatusInfo                   :
SupportsDiskQuotas           : True
SupportsFileBasedCompression : True
SystemCreationClassName      : Win32_ComputerSystem
SystemName                   : WM2008R2ENT
VolumeDirty                  :
VolumeName                   :
VolumeSerialNumber           : 96B00597

You can use this query (I use Powershell for rapid test but you can easily transform to C#)

$query = "SELECT * FROM __instanceCreationEvent WITHIN 5 WHERE TargetInstance ISA 'Win32_LogicalDisk' AND TargetInstance.DriveType=4"

Register-WMIEvent -Query $query -Action {$global:a=$Args[0];$global:b=$Args[1];write-host "done" }

Id              Name            State      HasMoreData     Location  Command
--              ----            -----      -----------     --------  -------
14              f2c5223d-3ae... NotStarted False                     $global:a=$Args[0];$gl...


PS C:\> net use
Les nouvelles connexions seront mémorisées.

La liste est vide.

PS C:\> net use o: \\jpbhpp2\c$
La commande s'est terminée correctement.

PS C:\> done


PS C:\> $a


Scope     : System.Management.ManagementScope
Query     : System.Management.EventQuery
Options   : System.Management.EventWatcherOptions
Site      :
Container :



PS C:\> $b

NewEvent                                                    Context
--------                                                    -------
System.Management.ManagementBaseObject                      {}


PS C:\> $b.NewEvent


__GENUS             : 2
__CLASS             : __InstanceCreationEvent
__SUPERCLASS        : __InstanceOperationEvent
__DYNASTY           : __SystemClass
__RELPATH           :
__PROPERTY_COUNT    : 3
__DERIVATION        : {__InstanceOperationEvent, __Event, __IndicationRelated, __SystemClass}
__SERVER            : WM2008R2ENT
__NAMESPACE         : //./root/CIMV2
__PATH              :
SECURITY_DESCRIPTOR :
TargetInstance      : System.Management.ManagementBaseObject
TIME_CREATED        : 129670237461553750



PS C:\> $b.NewEvent.TargetInstance


__GENUS                      : 2
__CLASS                      : Win32_LogicalDisk
__SUPERCLASS                 : CIM_LogicalDisk
__DYNASTY                    : CIM_ManagedSystemElement
__RELPATH                    : Win32_LogicalDisk.DeviceID="O:"
__PROPERTY_COUNT             : 40
__DERIVATION                 : {CIM_LogicalDisk, CIM_StorageExtent, CIM_LogicalDevice, CIM_LogicalElement...}
__SERVER                     : WM2008R2ENT
__NAMESPACE                  : root\CIMV2
__PATH                       : \\WM2008R2ENT\root\CIMV2:Win32_LogicalDisk.DeviceID="O:"
Access                       : 0
Availability                 :
BlockSize                    :
Caption                      : O:
Compressed                   : False
ConfigManagerErrorCode       :
ConfigManagerUserConfig      :
CreationClassName            : Win32_LogicalDisk
Description                  : Connexion réseau
DeviceID                     : O:
DriveType                    : 4
ErrorCleared                 :
ErrorDescription             :
ErrorMethodology             :
FileSystem                   : NTFS
FreeSpace                    : 36223737856
InstallDate                  :
LastErrorCode                :
MaximumComponentLength       : 255
MediaType                    : 0
Name                         : O:
NumberOfBlocks               :
PNPDeviceID                  :
PowerManagementCapabilities  :
PowerManagementSupported     :
ProviderName                 : \\jpbhpp2\c$
Purpose                      :
QuotasDisabled               : True
QuotasIncomplete             : False
QuotasRebuilding             : False
Size                         : 500000878592
Status                       :
StatusInfo                   :
SupportsDiskQuotas           : True
SupportsFileBasedCompression : True
SystemCreationClassName      : Win32_ComputerSystem
SystemName                   : WM2008R2ENT
VolumeDirty                  :
VolumeName                   :
VolumeSerialNumber           : 96B00597
無心 2024-12-25 07:28:23

对于网络共享监控,您可以使用RegistryKeyChangeEvent。

  1. RegistryKeyChangeEvent 位于 root\default 中。 (不是 .net 默认使用的 root\CIMV2)
  2. 挂载点信息存储在注册表中:HKEY_CURRENT_USER\Network。但是,RegistryKeyChangeEvent 无法监视 HKEY_CURRENT_USER(真糟糕)。因此,您必须通过以下方式访问它:HKEY_USERS\S-1-5-18\Network(其中 S-1-5-18 是您用户的 SID)。
  3. 要确定用户的 SID,请检查以下注册表路径:HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList。

最终代码应如下所示:

Dim m As New ManagementEventWatcher("root\default", "SELECT * FROM RegistryKeyChangeEvent WHERE Hive=""HKEY_USERS"" AND KeyPath=""<YOUR USER SID HERE>\\Network""") 
AddHandler m.EventArrived, AddressOf <YOUR HANDLER FUNCTION>
m.Start()

每次用户安装或卸载网络共享时,此代码都会调用处理函数。

For network share monitoring you can use RegistryKeyChangeEvent.

  1. RegistryKeyChangeEvent is located in root\default. (Not root\CIMV2 which is used by .net as default)
  2. Mount point information is stored in registry in: HKEY_CURRENT_USER\Network. But, RegistryKeyChangeEvent can't monitor HKEY_CURRENT_USER (bummer). Thus, you'll have to access it by: HKEY_USERS\S-1-5-18\Network (where S-1-5-18 is your user's SID).
  3. To determine your user's SID check the followind registry path: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList.

The final code should be something like this:

Dim m As New ManagementEventWatcher("root\default", "SELECT * FROM RegistryKeyChangeEvent WHERE Hive=""HKEY_USERS"" AND KeyPath=""<YOUR USER SID HERE>\\Network""") 
AddHandler m.EventArrived, AddressOf <YOUR HANDLER FUNCTION>
m.Start()

This code will call the handler function every time the user mounts or dismounts a network share.

与之呼应 2024-12-25 07:28:23

您可以侦听任何 VolumeChangeEvent,然后只需检查驱动器是否是网络驱动器:

DriveInfo info = new DriveInfo(driveLetter);
if(info.DriveType == DriveType.Network)
    //DoSomething

You can listen for any VolumeChangeEvent and then just check if the drive is a network drive:

DriveInfo info = new DriveInfo(driveLetter);
if(info.DriveType == DriveType.Network)
    //DoSomething
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文