Нашел полезные статейки по работе с HV. Автор: Алексей Кибкало
Оригиналы здесь:
Делегирование прав на Hyper-V
Нaстройка удаленного доступа к Hyper-V | Для системного администратора
По умолчанию Hyper-V разрешает создание и управление виртуальными машинами только администраторам. Сегодня мы поговорим о том, как делегировать эти права пользователям, не обладающими правами администратора сервера.
Hyper-V используют новую модель авторизации пользователей — Authorization Management Framework, которая позволяет гибко настроить права пользователей на виртуальные машины. Модель очень хорошо продумана и имеет ряд интересных моментов, которые я обязательно как-нибудь затрону. Сейчас же мне придется сообщить некую вводную информацию про эту модель, чтобы затем показать настройки делегирования. Итак, термины:
Операция (Operation)
Основной кирпичик модели авторизации — представляет собой действие, которое пользователь может произвести. Примерами операций модели являются op_Create_VM, позволяющая создать виртуальную машину и op_Start_VM, соответственно, запускающая виртуальную машину.
Задача (Task)
Задача — это группа операций, требуемых для выполнения некоторых действий. По умолчанию мы не создаем никаких заданий, но если бы мы могли создать задачу control_VM, то нам бы потребовалось добавить в эту группу операции по запуску (op_Start_VM), остановке (op_Stop_VM), приостановке (op_Pause_VM) и перезапуску (op_Restart_VM) для выполнения необходимых в задаче действий.
Роль (Role)
Роль определяет должность, круг задач или зону ответственности для пользователя. Например, может потребоваться роль Virtual_Network_Admin. Эта роль будет иметь права на все операции и задачи, связанные с виртуальными сетями. При необходимости эту роль можно будет назначать пользователям.
Область (Scope)
Область позволяет вам указать, какие объекты управляются конкретными ролями. Если у вас есть система, и вы хотели бы быть дать пользователю административный доступ к некому набору виртуальных машин в ней, вам потребуется создать область, содержащую эти конкретные виртуальные машины, а затем применить ваши настройки к данной области.
Область по умолчанию (Default Scope)
Область по умолчанию присваивается виртуальным машинам, для которых явно не задана другая область.
Hyper-V может хранить настройки модели авторизации в Active Directory или в локальном файле в формате XML. По умолчанию после установки роли Hyper-V настройки хранятся в файле, который находится по адресу: %programdata%MicrosoftWindowsHyper-VInitialStore.xml. Для того, чтобы изменить настройки, вам потребуется:
- Запустить приложение MMC. (Для этого выберите пункт Run в Start Menu или нажмите комбинацию клавиш ‘Windows Key + R’, затем выполните mmc.exe).
- В меню File выбрать Add/Remove Snap-in.
- Добавить Authorization Manager.
- В дереве консоли (левой панели ) выбрать Authorization Manager, затем в меню Action выбрать пункт Open Authorization Store.
- Выбрать XML file в предлагаемом диалоге Select the authorization store type: и открыть файл по указанному выше пути. (Папка programdata является скрытой, так что проще будет скопировать путь целиком).
- Выберите InitialStore.xml, затем Microsoft Hyper-V services, далее Role Assignments и в конце концов Administrator.
- В меню Action выберите Assign Users and Groups, затем From Windows and Active Directory, далее выберите пользователя, которому хотите делегировать права на управления Hyper-V. Нажмите OK и закройте окно MMC. (При этом можно сохранить или отменить настройки MMC. Это не повлияет на изменения, внесенные вами в модель авторизации).
На этом ваша задача выполнена. Пользователь может полностью контролировать Hyper-V, не являясь администратором на этом сервере. Делегирование гранулярных прав на конкретные виртуальные машины осуществляется абсолютно таким же образом.
Нaстройка удаленного доступа к Hyper-V
Мы только что рассмотрели, как делегировать пользователю права на управление Hyper-V. Но этими правами пользователь сможет воспользоваться, только работая на сервере локально.
Для того, чтобы управлять гипервизором с другого компьютера, пользователю, который не является администратором, потребуется выполнить ряд настроек — как на стороне сервера, так и на стороне клиента.
Описанные в этой статье шаги применимы к версии RC0 гипервизора Hyper-V и RC0 версии клиентской утилиты управления Hyper-V Manager для Vista SP1 (x86 и x64).
Итак, на сервере следует выполнить следующие шаги:
- Разрешить в Windows Firewall правило «Windows Management Instrumentation (WMI)» следующей командой:
netsh advfirewall firewall set rule group=»windows management instrumentation (wmi)» new enable=yes
Внимание: в различных локализованных ОС встроенные правила брандмауэера могут назваться по-разному. Необходимо указать название правила именно так, как оно выглядит в инструментах управления Windows Firewall. Например, в русской версии Windows Server 2008 приведенная выше строка будет выглядеть так:
netsh advfirewall firewall set rule group=»Инструментарий управления Windows (WMI — входящий трафик)» new enable=yes
- Предоставить пользователю права на удаленный запуск (remote launch and activation) в DCOM. Это можно сделать как для конкретного пользователя или группы, так и для всех AUTHENTICATED USERS.
-
- Нажмите Start, выберите Run, запустите dcomcnfg.exe.
- В Component Services раскройте Computers, правой кнопкой нажмите на My Computer и выберите в меню пункт Properties.
- В My Computer Properties раскройте COM Security.
- В Launch and Activation Permissions выберите Edit Limits.
- В случае, если пользователь не указан в списке Groups of user names в окне Launch Permission, добавьте его кнопкой Add.
- В Launch Permission выберите пользователя или группу и в колонке Allow в Permissions for user укажите Remote Launch и Remote Activation. Нажмите OK.
- Предоставить пользователю права на удаленное управление (remote enable) в пространстве имен (namespace) rootCIMv2 и rootvirtualization. Это можно сделать как для конкретного пользователя или группы, или для AUTHENTICATED USERS.
-
- В Control Panel зайдите в Administrative Tools и запустите Computer Management.
- В Computer Management раскройте Services and Applications, правой кнопкой выберите WMI Control и нажмите Properties.
- В закладке Security выберите Advanced.
- В случае, если пользователь не указан в списке Permission в окне Advanced Security Settings, добавьте его кнопкой Add.
- В Advanced Security Settings выберите имя пользователя и нажмите Edit.
- В выпадающем меню Apply To окна Permission Entry выберите This namespace and subnamespaces и укажите Remote Enable в колонке Allow. Нажмите OK.
- Предоставьте пользователю права на Hyper-V.
- Перезагрузите сервер. (Если вы хотите избежать перезагрузки сервера, достаточно перезапустить следующие сервисы: winmgmt, vmms, vhdsvc & nvspwmi). При остановке winmgmt остальные роли стопнутся по депенденсам.
т.е. достаточно этих команд в командной строке (с правами администратора):
net stop winmgmt
а потом
net start winmgmt
net start vmms
net start vhdsvc
net start nvspwmi
Внимание: если сервер с установленной ролью Hyper-V, которым вы хотите управлять удаленно, используя локальную запись с правами администратора, не входит в домен, и при этом на сервере включен User Account Control (UAC), то имейте в виду следующее. По умолчанию к локальным учетным записям при неинтерактивном (в том числе сетевом) доступе применяется UAC Filtering. То есть, даже если вы являетесь администратором сервера, при попытке удалённого подключения UAC предоставит вам права стандартного пользователя. Поэтому в таком случае вам потребуется напрямую предоставить пользователю права на Hyper-V способом, описанным в предыдущей статье.
Настройки клиентского компьютера
Итак, сервер мы настроили. Теперь ряд настроек потребуется выполнить и на клиентском ПК с Vista SP1.
- Разрешить на Windows Firewall правило «Windows Management Instrumentation (WMI)» командой
netsh advfirewall firewall set rule group=»windows management instrumentation (wmi)» new enable=yes
В русской версии Windows Vista эта же команда выглядит следующим образом:
netsh advfirewall firewall set rule group=»Инструментарий управления Windows (WMI — входящий трафик)» new enable=yes
А на системах с ОС, предшествующими Windows Vista (Windows XP / 2003), для этого служит команда
netsh firewall set service RemoteAdmin enable
- На системах с ОС, предшествующих Vista (Windows XP / 2003), следует также добавить исключение для исполняемого файла Unsecapp.exe:
netsh firewall add allowedprogram program=%windir%system32wbemunsecapp.exe name=UNSECAPP
- Добавить в Windows Firewall исключение для исполняемого фалйла mmc.exe:
netsh firewall add allowedprogram program=%windir%system32mmc.exe name=»Microsoft Management Console»
- Если клиент или сервер находятся в рабочей группе или они находятся в разных доменах, между которыми нет доверительных отношений, то соединение от сервера до клиента, устанавливаемое для доставки результирующей информации, происходит анонимно. Анонимное соединение завершается неудачно с кодом ошибки 0x80070005 или 0x8007000e до тех пор, пока анонимному соединнеию не будет дано право Remote Access на DCOM клиента. Дать это право можно, выполнив следующие шаги:
-
- Нажмите Start, выберите Run, запустите dcomcnfg.exe.
- В Component Services раскройте Computers, правой кнопкой выберите My Computer и укажите Properties.
- В My Computer Properties раскройте COM Security.
- В Launch and Activation Permissions выберите Edit Limits.
- В окне Access Permissions выберите ANONYMOUS LOGON в списке Group or user names. В колонке Allow в Permissions for User укажите Remote Access и нажмите OK.
После выполнения всех описанных действий вы, наконец, получите возможность удаленно подключаться к серверу и управлять ролью Hyper-V.
To enable or disable a Remote WMI Connection, employ Command Prompt. Manage multiple WMI rules swiftly, enhancing system control. Enabling these rules allows WMI to accept remote connections and asynchronous callbacks from Unsecapp.exe. This comprehensive guide outlines the process for managing WMI traffic directly from the command prompt, providing valuable insights into controlling remote access and thereby optimizing system management.
Please see this detailed guide on Enable or Disable WMI Traffic Using Firewall UI. Other related guides: Windows Management Instrumentation: WMI Commands, MDM Bridge WMI Provider and Windows 10 MDM Capabilities, to know what software is installed on a system, see how to query a list of installed programs in Windows via Windows Settings, Control Panel, WMIC, PowerShell and Windows Registry, and How to setup and configure Remote Desktop Services via Standard Deployment on Windows Server.
Configuring Network Access via Command Prompt Rule Group
Please see this detailed guide on Windows Management Instrumentation: WMI Commands.
Enable WMI traffic through the firewall:
netsh advfirewall firewall set rule group="windows management instrumentation (wmi)" new enable=yes
The “Remote WMI Connection” command activates 8 vital WMI rules, enhancing remote system management. This results in seamless control and comprehensive monitoring.
The Remote WMI Connection significantly empowers control by streamlining system management by integrating 8 essential Windows Management Instrumentation (WMI) rules.
These rules are essential, providing data collection, remote management, and performance monitoring, thus bolstering system security and stability. Such automation significantly saves time and ensures the consistent application of essential settings, consequently contributing to a more robust and dependable IT infrastructure.
Steps to Turn Off
First, run the command prompt as administrator.
netsh advfirewall firewall set rule group="windows management instrumentation (wmi)" new enable=no
The command removes 8 rules added to the WMI, streamlining the configuration and improving system management.
If you’ve found this blog post on Remote WMI Connection helpful, please share your thoughts or questions in the comment section. Additionally, your feedback is greatly appreciated, and I’m here to assist with any inquiries.
Q: I have problem connecting to WMI service on host, to use WMI monitors. Are there any preliminary steps I should follow to use WMI monitors?
A: Before you begin using network monitoring tools to gather information from remote host via WMI, make sure that
- WMI services are enabled on the host to monitor
- remote access to WMI services is enabled on the host
Please follow the below steps to ensure both prerequisites are met.
1. Steps to enable remote WMI monitoring
Prior to allowing access to WMI services, make sure it is enabled. Starting from Windows XP, there’s “Windows Management Instrumentation” service available from Control Panel -> Administrative tasks -> Services. Find the service and make sure it is running and configured to auto-start at startup (startup type: Automatic).
1.1. Allow access to corresponding ports
Access to DCOM port (TCP port 135) should be granted for remote access, to allow calling remote WMI services. Use corresponding Windows firewall settings for incoming connections to TCP:135.
1.1.1. Windows XP/Windows Server 2003
To allow connecting to ports used to access WMI objects on Windows XP/Windows Server 2003 perform the following command (from cmd.exe window, run as administrator):
netsh firewall set service remoteadmin enable netsh firewall set service remoteadmin enable subnet netsh firewall set service remoteadmin enable custom <IP>,LocalSubnet
Note: use every next command if current one didn’t work. Use actual computer’s primary IP address instead of <IP>.
1.1.2. Windows Vista and later Windows versions
Use the below command to perform the same action for Windows Vista and later Windows versions:
netsh advfirewall firewall set rule group="windows management instrumentation (wmi)" new enable=yes
1.2. Authorize WMI users and set permissions
Important note: to perform WMI queries on a remote computer, the account with which you are logged on must be a member of
- local “Administrators” group or “Domain Admins” group (if computer is a member of domain)
- local “Distributed COM Users” group
Make sure to use proper credentials in IPHost Network Monitor’s Windows credentials for corresponding WMI monitor.
If you need to configure remote WMI access to Windows XP (SP2 or later) and/or Windows Server 2003, please follow these instructions.
If you are performing WMI access management for Vista or later Windows version (i.e., Windows 7, Windows 8/8.1, Windows 10 or Windows Server 2008 or newer versions), follow the steps below (note they should be performed on the remote system – the one you need to monitor via WMI).
- Make sure “Remote Registry” service is running.
- Open the WMI Control console: Click Start, click Run, type wmimgmt.msc and then click OK.
- In the console tree, right-click WMI Control , and then click Properties.
- Click the Security tab.
- Select the namespace for which you want to give a user or group access (usually, Root), and then click Security.
In the Security dialog box, click Add - In the Select Users, Computers, or Groups dialog box, enter the name of the object (user or group) that you want to add. Click Check Names to verify your entry and then click OK. You might have to change the location or click the Advanced button to query for objects. See the dialog box Help for more details. Click “Advanced” button to make sure the permissions are applied correctly:
You need at least “Remote Enable” and read access assigned; you can start with granting all access types and revoking unnecessary ones later (use the command-line check mentioned in section 2 below). - Ensure the “Applies to” option is set to “This namespace and subnamespaces”:
Use “Edit” control to change that if necessary. - Allow incoming traffic to RPC ports (TCP range 6001-6032); corresponding incoming rule in Windows firewall should allow the ports as shown below:
- Add the host that sends remote WMI requests to the list of trusted hosts: run Power Shell as Administrator and issue these commands:
Set-Item WSMan:\localhost\Client\TrustedHosts -Value <hostname>
where <hostname> is the host that sends remote WMI requests. Note: add all known host’s DNS names via these commands, if there are more than single hostname.
2. Test remote WMI access
After the above steps are done, before actually starting corresponding WMI monitor, try executing simple WMI query to the remote computer. On local system (where IPHost is installed), open PowerShell as Administrator and issue command like this:
Get-WmiObject -Namespace "root\cimv2" -Class Win32_LogicalDisk -ComputerName REMOTE_HOST -Credential DOMAIN\User
replacing REMOTE_HOST with actual DNS name or IP address of the remote host (for which WMI monitor should be set up) and DOMAIN\User with actual domain and user names to authenticate (use computer network name as domain name if logging in as local user).
If everything is set up and credentials are valid, the command will list some information on local disk drives of the remote host.
If an error is reported instead, please check the above mentioned steps to make sure all the actions has been performed.
Important: you can only use a single set of credentials to access a given remote Windows system. If you attempt to connect to the same remote system with different set of credentials, the connection will fail (that’s a Windows restriction).
Troubleshooting
“The object exporter specified was not found”
If all the setup steps are performed, but a test WMI query returns error “The object exporter specified was not found”, it may be a result of attempting to connect to remote host, specified by IP address, residing behind a NAT (network address translation) firewall.
Quick solution: define an entry for IP address in question in hosts file:
%SystemRoot%\System32\drivers\etc\hosts
For example, if IP address is 0.1.2.3, add entry like this:
0.1.2.3 host0123
and use its host name (“host0123” in the above example) instead of plain IP address, to connect to the remote host and run WMI queries.
Related topics
Related links
20 Replies
Accepted Answer
This article applies to PRTG Network Monitor 16 or later
Monitoring WMI Sensors Outside a Domain
If the server on which PRTG is installed is part of a domain, whereas a few target machines are not, WMI monitoring often fails with the following error:
Connection could not be established (80070005: Access Denied …)
This article lists a few possible steps to resolve this issue to successfully monitor target machines outside your Windows domain.
Basic Steps
- First of all, please check if the correct credentials are used, especially if the hostname is entered in the field Domain or Computer Name in PRTG. You can try to use localhost here, especially in the settings of the parent group (if all devices in this group are outside of the domain, of course). Please do not leave this field empty!
- Verify if any firewalls in between PRTG and the target machine(s) may be interfering with connections on port 135.
- Check the access rights to the target machine. You can either try accessing as a local user with corresponding rights or as a domain admin:
- If you want to use a local user to monitor the target machine (no matter if workgroup or domain machine), set up this user account as following.
Note: This approach does not work with a domain user!- Open the Computer/Server Management tool on the target machine.
- Navigate to System | Local Users and Groups | Groups.
- Add the local user to Distributed COM Users and to Performance Monitor Users.
- Navigate to Services and Applications below in the management panel.
- Right-click WMI Control and choose Properties.
- Select the Security tab.
- Navigate to the namespace you are interested in (for example, Root\CIMV2).
- Click the Security button.
- Add the local user and give these permissions: Execute Methods, Enable Account, and Remote Enable.
- Start DCOMCNFG.exe
- Navigate to Component Services | Computers | My Computer.
- Right-click My Computer and choose Properties.
- Select the COM Security tab.
- In section Launch and Activation Permissions click Edit Limits…
- Add the local user and allow these permissions: Local Launch, Remote Launch and Remote Activation.
- Monitoring with a local user user account should now work. Otherwise, try using a domain admin as described below.
- Check the access permissions on all computers running a PRTG probe with WMI sensors (can be local probe system, systems with remote probes, on every node in a cluster setup):
- Start DCOMCNFG.exe on each system running a PRTG probe.
- Navigate to Component Services | Computers | My Computer.
- Right-click My Computer and choose Properties.
- Select the COM Security tab.
- In section Access Permissions click Edit Limits…
- Add the group Everyone and allow the permission Remote Access.
- Confirm and restart the computer.
- The next thing you should try is to configure the PRTG Probe service to run under a domain administrator account. Sometimes the access rights of the System Account under which the PRTG Probe runs by default are not sufficient. Even though it may sound awkward to use a domain administrator account to query a machine outside of a domain, do try this, as we have actually seen cases where this option got the WMI sensors (for this particular target) to work.
- If you want to use a local user to monitor the target machine (no matter if workgroup or domain machine), set up this user account as following.
- Ensure that Remote Management is enabled on on the target server. See Microsoft TechNet: Configure Remote Management in Server Manager (Windows Server 2012)
- If the target host(s) are accessible with our WMI Tester tool, but PRTG still insists on showing the 80070005 error, try using «localhost» as «domain or computer name» in the Windows credentials section of the device’s settings.
The next options have to be differentiated by the Windows version running on the target machine:
Windows 7
- Open the control panel, head to “System and Security”, and then click on “Windows Firewall”
- Click on “Advanced Settings” and then, for both Inbound and Outbound Rules, do the following:
- To enable WMI traffic passing the firewall, select all checkboxes for “Windows Management Instrumentation”. Confirm this by closing the windows.
- Open a command prompt (as administrator) and enter the following line to set another firewall group rule:
netsh advfirewall firewall set rule group="windows management instrumentation (wmi)" new enable=yes
- Eventually reboot the target machine. It should now be possible to monitor with WMI.
- Add the monitoring user to the Performance Monitor Users group
- UAC blocks some (not all) WMI counters, resulting in error 80041003: The current user does not have permission to perform the action. . You can add the following registry key to disable this feature of UAC.
Path:
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
Add a new DWORD value:
Name: LocalAccountTokenFilterPolicy
Value: 1- Note: This disables some of the protection provided by UAC. Specifically, any remote access to the server using an administrator security token is automatically elevated with full administrator rights, including access to the root folder.
More information can be found here: http://support.microsoft.com/kb/951016
We have also seen cases where it was necessary to disable the UAC completely to get WMI Monitoring running.
- Note: This disables some of the protection provided by UAC. Specifically, any remote access to the server using an administrator security token is automatically elevated with full administrator rights, including access to the root folder.
Windows XP/2003
- Head to “Start”->”Run…” and start the registry editor (regedit)
- Navigate to the following key:
HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\LSA\
- Make sure that “ForceGuest” is set to “0”
- Eventually reboot the target machine. It should now be possible to monitor with WMI.
- For further reference please see http://support.microsoft.com/default.aspx?scid=kb;en-us;290403
Windows Vista/2008 (R2)
- Open the control panel, head to the Windows firewall
- Click on “Change Settings” and then please select the “Exceptions” tab
- To enable WMI traffic passing the firewall, select the check box for “Windows Management Instrumentation (WMI)”. Confirm this with Ok.
- Open a command prompt (as administrator) and enter the following line to set another firewall group rule:
netsh advfirewall firewall set rule group="windows management instrumentation (wmi)" new enable=yes
Note: The name of the group is language dependent and must be translated for non-English Windows versions! So, if you run this command on a German Windows version, you have to replace windows management instrumentation (wmi) by Windows-Verwaltungsinstrumentation (WMI). - Eventually reboot the target machine. It should now be possible to monitor with WMI.
- For further reference please see: http://msdn.microsoft.com/en-us/library/aa822854(VS.85).aspx
- Add the monitoring user to the Performance Monitor Users group
the given solution doesn’t work in my network
PRTG Server ist installed on WinXP Pro SP3 (in a domain) and should monitor a Win2k8 (not in a domain)
is there another solution ?
Michael
I’m trying to set it up for win 7 Professional
After adding the WMI rules to the firewall I open a command prompt (as administrator) and enter the following line to set another firewall group rule:
netsh advfirewall firewall set rule group="windows management instrumentation (wmi)" new enable=yes
I get an error :
«Aucune règle ne correspond aux critères spécifiés»
No rule matches the criteria specified
????
Please check if WMI connection works if you turn off the firewall, to make sure that the firewall settings are the cause.
I have just turn off the firewall but the result is the same.
It’s strange because I was able to get all the list of WMI sensor. It means that my account and password for accessing my windows machine is correct.
Dear Maurice,
as for the firewall rule, it seems you are using a French Windows, therefore the correct French Term for «windows management instrumentation (wmi)» has to be used. Furthermore, please check if the user you are using is correctly entered in the user group of DCOM-Users.
Best Regards.
Where I need to check if the user is correctly entered in the user group DCOM-Users ?
In the Computer Management (Windows: Start->Settings->Control Panel->Administrative Tools->Computer Management), please add the user to the «Distributed COM Users»-Group.
Thanks. I was able to add my user to this DCOM group.
But I get always this error message :
"Connection could not be established (80041003: The current user does not have permission to perform the action. - Host: 195.49.12.XXX, User: YYY, Password: ***, Domain: ntlmdomain:srv-forum) (code: PE015)"
About the firewall, I have setup this Input rules :
Windows Management Instrumentation (WMI-In)
Windows Management Instrumentation (DCOM-In)
Windows Management Instrumentation (ASync-In)
and this output rule :
Infrastructure de gestion Windows (WMI-Out)
What I am missing ??
Finally I was able to make it working.
This link is the way to go :
http://bit.ly/dhjcSz
Now my problem of remote access from PRTG 8 is solved.
Here is one thing we’ve added to our article above:
- If the target host(s) are accessible with our WMI Tester tool, but PRTG still insists on showing the 80070005 error, try using «localhost» as «domain or computer name» in the Windows credentials section of the device’s settings.
Kind regards,
— Volker
I followed most of the instructions above and still couldn’t get it to work. I kept getting the 80041003 error. I finally found a solution, that didn’t involve using an administrator account for the Probe machine or for the target DMZ account, and I didn’t have to turn off UAC, and I didn’t have to edit the registry.
The remote machine in this case is a Server 2008 R2 machine. I’m using a normal user account. I added this account to «Distributed COM Users» and «Performance Monitor Users». Doesn’t seem to work without these two groups.
Here’s what I did. Brought up the management panel (right click on the computer icon, and select manage). I then found the «WMI Control» (right below Services), right-clicked on Properties, then went to the Security tab. I clicked on the namespace I was interested in (in my case, root/CIMV2) and then hit the Security button. I added the user I was trying to access with and gave it the following Permissions: Execute Methods, Provider Write, Enable Account, and most importantly, Remote Enable. This last permission is key.
Once I did that, I had no problem adding WMI/counter sensors.
Which settings are mandatory when I use Windows 10?
Christian, I’m afraid we do not have an extensive list for a work group Windows 10, and how to monitor it with PRTG via WMI. Please try the tips in this very article here. Otherwise there is always the alternative of installing a Remote Probe on the target host, because local WMI monitoring does not need authentication (as per Microsofts design) and thus is much less troublesome in this scenario with work group machines.
Putting localhost in as the domain name for the credentials fixed my issue (PE015). I had changed the monitoring user for a few hosts that were off domain and started getting heaps of PE015 errors. Apparently «.» or blank is no good as the domainame — but «localhost» works fine which is heaps better that putting a different local hostname into the domain feild for each set of credentials.
To accomplish this I have created an PowerShell Script.
Especially the Firewall part was tricky to set up.
Use it on your own Risk.
Initial Release: Version: 1.0.0.0 10.September.2019
Current Release: Version: 1.0.1.0 11.September.2019
Changelog:
1.0.1.0 Fixed Parameter «-WmiNamespaceInheritPermissions» was not in use.
Added Comment to UAC section
#Requires -RunAsAdministrator <# .Synopsis This script is to create an local user account which is used to query this local computer over PRTG and WMI and open the Windows Firewall to allow WMI Remoting .DESCRIPTION 1. Create an Local user with the iads WinNT:// system provider 2. Put Local user into the local groups (international found by SID not by name, with the help of WMI Win32_Group class) "Distributed COM Users" SID: S-1-5-32-562 and "Performance Monitor Users" SID: S-1-5-32-558 3. Grant User permissions to the target WMI Namespace 4. Enable Windows-Firewall rule to allow WMI Access using the CMD command "netsh advfirewall firewall ..." because PowerShell commands do not support Rule-Groups. (!!! Atention !!! this command is international translated and language dependent !!!!!) eg. for german: netsh advfirewall firewall set rule group="Windows-Verwaltungsinstrumentation (WMI)" new enable=yes eg. for english: netsh advfirewall firewall set rule group="windows management instrumentation (wmi)" new enable=yes 5. This Script do not touch the UAC (registry key)! UAC can in some cases filter information through WMI so that the information is not as complete as it could be. Some are recommend turning off UAC filtering on the target machine. It can be done by setting a registry key. Change it on your own Risk! HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system\LocalAccountTokenFilterPolicy = 1 See: Microsoft documentation "User Account Control and WMI" https://docs.microsoft.com/de-de/windows/win32/wmisdk/user-account-control-and-wmi?redirectedfrom=MSDN This Script is designed to run local on the target computer who is accessed by PRTG and Windows Management Instrumentation (WMI). If you like to run this script remote on the target Computer, run this script with Invoke-Command. For documentation of the user account flags, search kewords are: "win32 api iads ADS_USER_FLAG_ENUM" The ADS_USER_FLAG_ENUM enumeration defines the flags used for setting user properties in the directory. These flags correspond to values of the userAccountControl attribute in Active Directory when using the LDAP provider, and the userFlags attribute when using the WinNT system provider. See: https://docs.microsoft.com/en-us/windows/win32/api/iads/ne-iads-ads_user_flag_enum Copyright 2019 Peter Kriegel (modified MIT License) Permission is hereby granted, free of charge, to any person obtaining a copy of this script and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: THIS SCRIPT IS NOT SUPPORTED UNDER ANY SUPPORT PROGRAM OR SERVICE. THE AUTHOR FURTHER DISCLAIMS ALL IMPLIED WARRANTIES INCLUDING, WITHOUT LIMITATION, ANY IMPLIED WARRANTIES OF MERCHANTABILITY OR OF FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK ARISING OUT OF THE USE OR PERFORMANCE OF THIS SCRIPT AND DOCUMENTATION REMAINS WITH YOU. IN NO EVENT THE AUTHOR OR ANYONE ELSE INVOLVED IN THE CREATION, PRODUCTION, OR DELIVERY OF THIS SOFTWARE BE LIABLE FOR ANY DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SCRIPT OR DOCUMENTATION, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. IT IS UP TO YOU, THAT YOU HAVE READ AND UNDERSTOOD WHAT THIS SCRIPT IS GOING TO PROCESS BEFORE YOU RUN IT. IF YOU REPUBLISH THIS SCRIPT, CREDIT THE AUTHOR AND PROVIDE A LINK TO THE ORIGIN! End of Copyright .NOTES Author: Peter Kriegel Initial Release: Version: 1.0.0.0 10.September.2019 Current Release: Version: 1.0.1.0 11.September.2019 Changelog: 1.0.1.0 Fixed Parameter "-WmiNamespaceInheritPermissions" was not in use. Added Comment to UAC section #> # Start variables to set param ( # ComputerName to add the User and to modify the Firewall [String]$ComputerName = $Env:COMPUTERNAME, # Username to add [String]$UserName = 'PRTGquery', # Password for the User; If it is leaved blank, the password is requested in interactive mode!!! [String]$UserPassword, # Fullname of the User (only for description) [String]$UserFullname = 'PRTG user', # Userflags of the new created User account; see Microsoft documentation of the "ADS_USER_FLAG_ENUM" enumeration [Int]$UserFlags = 64 + 65536, # ADS_UF_PASSWD_CANT_CHANGE + ADS_UF_DONT_EXPIRE_PASSWD # Description for the new created User account [String]$UserDescription = 'Query this Computer with PRTG', # WMI Namespace who the user is granted permissions. [String]$WmiNamespace = 'root/cimv2', # the User permissions to grant to the WMI-Namespace. (default here is least privilege as read only) [ValidateSet('Enable','MethodExecute','FullWrite','PartialWrite','ProviderWrite','RemoteAccess','ReadSecurity','WriteSecurity')] [String[]]$WmiNamespacePermissions = @('Enable','MethodExecute','ReadSecurity','RemoteAccess'), # If true the user permissions is inherited even to sub namespaces of the given namespace, if false only the Namespace is granted for the user [Bool]$WmiNamespaceInheritPermissions = $True, # add / modify firewall groupname to your language! (we have MUI environment and try to use the englisch version too, so a message like "No rules match the specified criteria." is normal) [String[]]$WindowsFirewallRuleGroupNames = @('Windows-Verwaltungsinstrumentation (WMI)','windows management instrumentation (wmi)') ) # Query / convert Password for the User $PwEqualOrQuit = $False $Pwd1 = $Null $Pwd2 = $Null If(-Not ([String]::IsNullOrEmpty(($UserPassword.Trim())))) { $Pwd1 = ConvertTo-SecureString -String $UserPassword -AsPlainText -Force $UserPassword = $Null } Else { Do { $Pwd1 = Read-Host "Enter password for the user $UserName (Q or q to quit)" -AsSecureString If ([Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Pwd1)) -ieq 'q') { $Pwd1 = $Null $PwEqualOrQuit = $True } Else { $Pwd2 = Read-Host "Reenter password for the user $UserName (Q or q to quit)" -AsSecureString If ([Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Pwd2)) -ieq 'q') { $Pwd1 = $Null $PwEqualOrQuit = $True } } If(-Not $PwEqualOrQuit) { If ([Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Pwd1)) -ceq [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Pwd2))) { $PwEqualOrQuit = $True } Else { Write-Host "`nPasswords dont match!`nTry again`n" } } } while (-Not $PwEqualOrQuit) If ($Null -eq $Pwd1) { Write-Host 'User has quitted!' Return } Else { # Write-Host "Passwords matched!" } } # Create new local user Try { $Computer = [ADSI]"WinNT://$ComputerName,Computer" $LocalUser = $Computer.Create("User", $UserName) $LocalUser.SetPassword(([Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($Pwd1)))) $LocalUser.UserFlags = $UserFlags $LocalUser.SetInfo() $LocalUser.Put('Fullname', $UserFullname) $LocalUser.SetInfo() $LocalUser.Put('Description', $UserDescription) $LocalUser.SetInfo() } Catch { Write-Error $Error[0] Return } # Add User to groups <# To access WMI and performance data remotely and If a target computer is outside of a domain or the user is an local account, the user has to be a member of the local "Distributed COM Users" group and of the "Performance Monitor Users" group on the local machine. Additionally you have to grant permissions (read) to a WIM / CIM namespace (and subtree). For an example Namespace Root/CIMV2 If the user needs access to all the namespaces, you can set the settings at the Root level (Root). You have to recurse the permissions to the sub-namespaces with the security setting of "This namespace and subnamespaces"! "Distributed COM Users" SID: S-1-5-32-562 Name: BUILTIN\Distributed COM Users Description: An alias. A group for COM to provide computerwide access controls that govern access to all call, activation, or launch requests on the computer. "Performance Monitor Users" SID: S-1-5-32-558 Name: BUILTIN\Performance Monitor Users Description: An alias. Members of this group have remote access to monitor this computer. To set a non Domain User into the local "Administrators" group to access WMI / CIM does not worked. #> # Get Groups by SID Get-WMIObject -Class 'Win32_Group' -Filter "LocalAccount='True' AND (SID='S-1-5-32-562' OR SID='S-1-5-32-558')" -ComputerName $ComputerName | ForEach-Object { # add User to Groups $AdsiGroup = [ADSI]"WinNT://$ComputerName/$($_.Name),group" $AdsiGroup.psbase.Invoke('Add',([ADSI]"WinNT://$ComputerName/$UserName").path) } Function Set-WMINamespacePermissions { <# .Synopsis A Script for modifying the current security descriptor of a WMI namespace. .DESCRIPTION A Script for modifying the current security descriptor of a WMI namespace. .EXAMPLE Set-WMINamespacePermissions.ps1 -namespace root/cimv2 -account "contoso\AD - Remote WMI Access" -operation Add -permissions Enable .EXAMPLE Set-WMINamespacePermissions.ps1 root/cimv2 add steve Enable,RemoteAccess .NOTES Original Content by Steve Lee Blog links: https://blogs.msdn.microsoft.com/wmi/2009/07/20/scripting-wmi-namespace-security-part-1-of-3/ https://blogs.msdn.microsoft.com/wmi/2009/07/23/scripting-wmi-namespace-security-part-2-of-3/ https://blogs.msdn.microsoft.com/wmi/2009/07/27/scripting-wmi-namespace-security-part-3-of-3/ Modified by Graeme Bray and Peter Kriegel (converted into a Function and fixed a Bug with inheritance) Original "Set-WMINameSpaceSecurity.ps1", taken from: https://gallery.technet.microsoft.com/Set-WMI-NameSpace-Security-5081ad6d Disclaimer The sample scripts are not supported under any Microsoft standard support program or service. The sample scripts are provided AS IS without warranty of any kind. Microsoft further disclaims all implied warranties including, without limitation, any implied warranties of merchantability or of fitness for a particular purpose. The entire risk arising out of the use or performance of the sample scripts and documentation remains with you. In no event shall Microsoft, its authors, or anyone else involved in the creation, production, or delivery of the scripts be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the sample scripts or documentation, even if Microsoft has been advised of the possibility of such damages. #> Param ( [parameter(Mandatory=$true,Position=0)][string] $namespace, [parameter(Mandatory=$true,Position=1)][string] $operation, [parameter(Mandatory=$true,Position=2)][string] $account, [parameter(Position=3)][string[]] $permissions = $null, [bool] $allowInherit = $false, [bool] $deny = $false, [string] $computerName = ".", [System.Management.Automation.PSCredential] $credential = $null) Process { $ErrorActionPreference = "Stop" Function Get-AccessMaskFromPermission($permissions) { $WBEM_ENABLE = 1 $WBEM_METHOD_EXECUTE = 2 $WBEM_FULL_WRITE_REP = 4 $WBEM_PARTIAL_WRITE_REP = 8 $WBEM_WRITE_PROVIDER = 0x10 $WBEM_REMOTE_ACCESS = 0x20 $WBEM_RIGHT_SUBSCRIBE = 0x40 $WBEM_RIGHT_PUBLISH = 0x80 $READ_CONTROL = 0x20000 $WRITE_DAC = 0x40000 $WBEM_RIGHTS_FLAGS = $WBEM_ENABLE,$WBEM_METHOD_EXECUTE,$WBEM_FULL_WRITE_REP,` $WBEM_PARTIAL_WRITE_REP,$WBEM_WRITE_PROVIDER,$WBEM_REMOTE_ACCESS,` $READ_CONTROL,$WRITE_DAC $WBEM_RIGHTS_STRINGS = "Enable","MethodExecute","FullWrite","PartialWrite",` "ProviderWrite","RemoteAccess","ReadSecurity","WriteSecurity" $permissionTable = @{} for ($i = 0; $i -lt $WBEM_RIGHTS_FLAGS.Length; $i++) { $permissionTable.Add($WBEM_RIGHTS_STRINGS[$i].ToLower(), $WBEM_RIGHTS_FLAGS[$i]) } $accessMask = 0 foreach ($permission in $permissions) { if (-not $permissionTable.ContainsKey($permission.ToLower())) { throw "Unknown permission: $permission`nValid permissions: $($permissionTable.Keys)" } $accessMask += $permissionTable[$permission.ToLower()] } $accessMask } if ($PSBoundParameters.ContainsKey("Credential")) { $remoteparams = @{ComputerName=$computer;Credential=$credential} } else { $remoteparams = @{ComputerName=$computerName} } $invokeparams = @{Namespace=$namespace;Path="__systemsecurity=@"} + $remoteParams $output = Invoke-WmiMethod @invokeparams -Name GetSecurityDescriptor if ($output.ReturnValue -ne 0) { throw "GetSecurityDescriptor failed: $($output.ReturnValue)" } $acl = $output.Descriptor $OBJECT_INHERIT_ACE_FLAG = 0x1 $CONTAINER_INHERIT_ACE_FLAG = 0x2 $computerName = (Get-WmiObject @remoteparams Win32_ComputerSystem).Name if ($account.Contains('\')) { $domainaccount = $account.Split('\') $domain = $domainaccount[0] if (($domain -eq ".") -or ($domain -eq "BUILTIN")) { $domain = $computerName } $accountname = $domainaccount[1] } elseif ($account.Contains('@')) { $domainaccount = $account.Split('@') $domain = $domainaccount[1].Split('.')[0] $accountname = $domainaccount[0] } else { $domain = $computerName $accountname = $account } $getparams = @{Class="Win32_Account";Filter="Domain='$domain' and Name='$accountname'"} $win32account = Get-WmiObject @getparams if ($win32account -eq $null) { throw "Account was not found: $account" } switch ($operation) { "add" { if ($permissions -eq $null) { throw "-Permissions must be specified for an add operation" } $accessMask = Get-AccessMaskFromPermission($permissions) $ace = (New-Object System.Management.ManagementClass("win32_Ace")).CreateInstance() $ace.AccessMask = $accessMask if ($allowInherit) { # $ace.AceFlags = $OBJECT_INHERIT_ACE_FLAG + $CONTAINER_INHERIT_ACE_FLAG <- Bug !!!! $ace.AceFlags = $CONTAINER_INHERIT_ACE_FLAG } else { $ace.AceFlags = 0 } $trustee = (New-Object System.Management.ManagementClass("win32_Trustee")).CreateInstance() $trustee.SidString = $win32account.Sid $ace.Trustee = $trustee $ACCESS_ALLOWED_ACE_TYPE = 0x0 $ACCESS_DENIED_ACE_TYPE = 0x1 if ($deny) { $ace.AceType = $ACCESS_DENIED_ACE_TYPE } else { $ace.AceType = $ACCESS_ALLOWED_ACE_TYPE } $acl.DACL += $ace.psobject.immediateBaseObject } "delete" { if ($permissions -ne $null) { throw "Permissions cannot be specified for a delete operation" } [System.Management.ManagementBaseObject[]]$newDACL = @() foreach ($ace in $acl.DACL) { if ($ace.Trustee.SidString -ne $win32account.Sid) { $newDACL += $ace.psobject.immediateBaseObject } } $acl.DACL = $newDACL.psobject.immediateBaseObject } default { throw "Unknown operation: $operation`nAllowed operations: add delete" } } $setparams = @{Name="SetSecurityDescriptor";ArgumentList=$acl.psobject.immediateBaseObject} + $invokeParams $output = Invoke-WmiMethod @setparams if ($output.ReturnValue -ne 0) { throw "SetSecurityDescriptor failed: $($output.ReturnValue)" } } } # Set User permissions to WMI-Namespace Set-WMINamespacePermissions -namespace $WmiNamespace -operation 'add' -account "$ComputerName\$UserName" -permissions $WmiNamespacePermissions -allowInherit $WmiNamespaceInheritPermissions -ComputerName $ComputerName # Set firewall rules ForEach ($FwGroupName in $WindowsFirewallRuleGroupNames) { & 'netsh' @('advfirewall','firewall','set','rule','group=' + $FwGroupName ,'new','enable=yes') }
Disclaimer: The information in the Paessler Knowledge Base comes without warranty of any kind. Use at your own risk. Before applying any instructions please exercise proper system administrator housekeeping. You must make sure that a proper backup of all your data is available.
The VisualSVN Server Manager console uses
Windows Management Instrumentation (WMI) for remote administration.
Connecting to WMI remotely requires that you configure the Windows Firewall
to allow network connections to WMI on the remote computer. This article describes
how to configure the Windows Firewall to enable VisualSVN Server Remote Administration
in various environments.
Incorrect Windows Firewall settings are usually identified by receiving the «RPC Server
Unavailable» error message when trying to remotely connect to the VisualSVN Server
using the management console:
Cannot connect to WMI namespace ‘\\server-2008\root\VisualSVN’: The RPC server is unavailable. (0x800706ba)
Windows Firewall configuration should be done locally on the server by the user with
administrator rights. While Windows Firewall can be configured using the Control Panel,
you may find it easier to use the netsh command lines. Appropriate command lines
for the most widely used Windows versions are listed below.
Configuring Firewall for VisualSVN Server 5.0 and later
To allow administrative access to the server through the firewall, please
enable the VisualSVN Remote Server Administration inbound rules. Follow these steps:
- Open Windows Defender Firewall.
- Click Allow an app or feature through Windows Firewall.
- Find the VisualSVN Remote Server Administration firewall rule group and select the Domain profile.
- Click OK.
Enabling the firewall rules allows remote administrative access to VisualSVN Server.
Configuring Firewall for VisualSVN Server 4.3 and older
Run the following command in elevated command prompt:
netsh advfirewall firewall set rule group=»windows management instrumentation (wmi)» new enable=yes
On Windows Server 2008 or newer operating systems, the mentioned command line
must be executed in the elevated command prompt.
If you would rather use the Firewall UI than the netsh commands above, use
the following steps on the server:
- In the Control Panel, click Security and then click Windows Firewall.
- Click Change Settings, and then click the Exceptions tab.
-
In the Exceptions window, select the check box for Windows Management Instrumentation
(WMI) to enable WMI traffic through the firewall. To disable WMI traffic, clear the
check box.
For further details, see the article
Setting up a Remote WMI Connection at MSDN.
Note that enabling the mentioned Windows Firewall rules allows all network connections
to WMI on the server. In other words, you are enabling remote connections
to the whole WMI, not only VisualSVN Server Remote Administration. But only users
who are authorized to work with WMI will have appropriate permissions to connect. Please
consider Microsoft’s
Security TechCenter in order to find out how to configure your server securely.
See also
KB25: Configuring Remote Administration