Rpc shutdown windows 11

I will show you how to create Home Assistant Wake on Lan (WoL) switch to turn on your desktop computer. As well as how to use Home Assistant RPC shutdown add-on to turn off a Windows PC with a click of button.

Home Assistant Wake On Lan & Home Assistant RPC Shutdown (HOW-TO)

Using Home Assistant you can control many things and probably you already doing this, but after you read this you will add your computer to the list. Let start this!

Table of Contents

What is Wake on LAN (WoL)?

Wake on Lan is a standard that allows a computer to be awakened by a network message called magic packet. To use the Wake On LAN, your computer should support this feature and it have to be always connected to your network. You can use Wake on LAN regardless of the installed Operating System as this feature is usually controlled by the motherboard of your device.

After you finish reading this you will be able to create a Home Assistant Wake on LAN Switch, Script or Automation that will awaken any device that supports WoL.

What is RPC Shutdown?

On the opposite side to turn off a Windows PC from Home Assistant you will need the Home Assistant RPC Shutdown add-on. The RPC Shutdown add on is available in the Add-On store in Home Assistant and you can install it with 1 click.

If you don’t have Home Assistant yet, or your Home Assistant is without the Supervisor menu (Add-on store) check these two tutorials of mine and you will have everything that is needed in no time:

  • Home Assistant Supervised 👉 LINK
  • Home Assistant OS 👉 LINK

How to Enable Wake On Lan in BIOS?

First of all you have to check that the device that you want to turn on remotely support the Wake On Lan functionality. Check your motherboard manual or enter in the BIOS (usually by hitting the Del, button or a specific functions keys during the startup of your system).

Every motherboard vendor is having different place and even different wording for the Wake On Lan feature, so you’ll have to search for it a bit in the BIOS menus or in the manuals.

Home Assistant Wake On Lan & Home Assistant RPC Shutdown (HOW-TO) 1

Wake On LAN in AMI BIOS
Home Assistant Wake On Lan & Home Assistant RPC Shutdown (HOW-TO) 2

Wake on LAN in Lenovo BIOS
Home Assistant Wake On Lan & Home Assistant RPC Shutdown (HOW-TO) 3

Wake on LAN in Award BIOS
To unlock Home Assistant Wake On Lan you have to enable Wake On Lan feature in the BIOS

Enable Wake on Magic Packet in Windows 10

Sometimes it is necessary to enable wake on magic packet option on your network adapter in Windows and this is how I did it in Windows 10.

Right click on the Start menu > Device Manager > Network Adapters > right click on your network adapter and select Properties > Advanced > Wake on magic packet > Enabled.

Enable Wake On Magic Packet in Windows 10 Device Manager data-lazy-src=

Enable Wake On Magic Packet in Windows 10 Device Manager > Network Adapters before Adding Home Assistant Wake On Lan switch \ script \ automation.

It is time to add and configure the Home Assistant Wake on Lan integration.

Add the following text in configuration.yaml file and you will have the Wake on LAN platform enabled in your Home Assistant.

# configuration.yaml entry
wake_on_lan:

You will need to restart your Home Assistant before start using the Wake on LAN integration, but don’t do that yet. We will add the Home Assistant Wake On LAN switch in the next section and we will restart afterwards.

Add Home Assistant Wake on LAN switch

Only adding the things described in the above section in Home Assistant configuration is not enough. You may want to have a switch, script or automation in Home Assistant that will wake a specific PC or multiple PCs. This is what you can do for a Home Assistant Wake on LAN switch:

First, you will need the MAC address of the PC of your interest. You can get the MAC address either from your router interface or from the Windows command prompt using the ipconfig /all command.

Getting the MAC / Physical Address using ipconfig /all command to add the value in the Home Assistant Wake On Lan switch

Getting the MAC / Physical Address using ipconfig /all command to add the value in the Home Assistant Wake On Lan switch

Second, you have to add the following YAML in the configuration.yaml file using text editor or add-on like File Editor.

# configuration.yaml entry
switch:
  - platform: wake_on_lan
    mac: 20:cf:30:32:f7:89
    name: “a3-pc” 

Make sure that you do the following things:

  • If you already have switch: section in your configuration.yaml file add only the last 3 lines under your existing section.
  • Change the mac: value with your MAC address.
  • Change the name: to something meaningful for you (e.g. hostname of the device)
  • Save the changes and restart Home Assistant.

Test the Home Assistant WoL switch

Let’s quickly test if the Home Assistant Wake on LAN switch can actually wake our PC.

You can add a button to the Home Assistant Lovelace UI by click on the three dot menu in the upper right corner > Edit Dashboard > Add Card > Button Card > as entity select your newly created switch (i.e. switch.a3_pc) > Save

Adding the Home Assistant WoL Switch as button card

Adding the Home Assistant WoL Switch as button card

Before the actual test you have to put your computer to sleep. If you shut it down the Wake on LAN may or may not work.

I have to put my Windows PC to sleep to be able to use Wake On LAN successfully from Home Assistant.

And now when your PC fell asleep 💤 and you have a Button card with your WoL switch in Home Assistant – you can just press it and your PC will rise from the dead. 🎉

Home Assistant RPC Shutdown add-on 

Okay Wake on LAN Is working, but what if you want to turn off a Windows PC from Home Assistant? The Home Assistant RPC shutdown add-on available in the Home Assistant store will save the day. Let’s install it

Open your Home Assistant and press, the “c” button to invoke the search bar, type add-on and choose Navigate Add-On store. Then search for RPC Shutdown or save the hassle and click on the link below, which will lead you to the same place.

Home Assistant Wake On Lan & Home Assistant RPC Shutdown (HOW-TO) 4

Click on the Install button to have your RPC Shutdown add-on.

After the installation we will need the IP, username and password of the windows machine to configure properly the RPC shutdown add-on. This is an example configuration for my Windows PC, of course you can add multiple computers as well (just add more aliases).

computers:
  - alias: a3-pc
    address: 10.0.0.45
    credentials: smash%thelike
    delay: 0
    message: >-
      Home Assistant is shutting down this PC. This cannot be canceled. Please
      save your work!

Make sure that you do the following changes under the Configuration tab in RPC shutdown add-on:

  • Change the alias: with something meaningful for you (e.g. hostname of the device)
  • Change the address: value with the IP address of the computer that you want to wake (Get it from your router interface or use again the ipconfig /all command from Windows command prompt)
  • Change the credentials: values with your Windows user & pass (i.e. user%pass)
  • Save the changes and start the RPC shutdown add-on from the Info tab.

Add Home Assistant RPC Shutdown switch

To test if the shutdown of a Windows PC from Home Assistant is working – we will edit our switch that we created in the Add Home Assistant Wake on LAN switch section above.

Go back to your configuration.yaml file and add another 6 lines under the existing WoL switch, so your code at the end should look similar to the one below.

# Example configuration.yaml entry
switch:
  - platform: wake_on_lan
    mac: 20:cf:30:32:f7:89
    name: “a3-pc” 
    host: 10.0.0.45
    turn_off:
      service: hassio.addon_stdin
      data:
        addon: core_rpc_shutdown
        input: a3-pc

The things that you have to change here are the following:

  • The value of the host: parameter with the IP of the machine that you want to shutdown.
  • The value of the input: parameter, where the value should be exactly the same as the alias in the RPC shutdown configuration. In my case the value everywhere is my windows pc hostname (a3-pc).
  • Save the changes and restart Home Assistant.

After Home Assistant has started – you can try to shutdown the Windows PC (a.k.a the victim) by pressing the same button that wake our PC earlier in the Home Assistant UI.

If your computer shut down correctly – you are done with this guide and you don’t have to do anything else, except you can show off in the comments section below.

If your computer doesn’t want to shutdown, check the RPC Shutdown Logs section and continue reading.

What If RPC shutdown is not working?

If you see any of the errors below in the RPC shutdown log section:

Could not initialise pipe winreg. Error was NT_STATUS_OBJECT_NAME_NOT_FOUND
Shutdown of remote machine failed result was: WERR_CALL_NOT_IMPLEMENTED
Home Assistant Wake On Lan & Home Assistant RPC Shutdown (HOW-TO) 5

Shutdown of remote machine failed result was: WERR_CALL_NOT_IMPLEMENTED
Home Assistant Wake On Lan & Home Assistant RPC Shutdown (HOW-TO) 6

Could not initialise pipe winreg. Error was NT_STATUS_OBJECT_NAME_NOT_FOUND

Also the Home Assistant RPC shutdown is not working – you have to do several extra steps. Namely to start a Remote Registry service, to create a WMI firewall rule and to add a local policy in your Windows registry.

Don’t worry it is easy, not that easy as subscribing to my newsletter, but I will show you all of the steps.

Start Remote Registry Service in Windows

Click on Start menu > select Run > Type services.msc and click OK > In the Services window search for Remote Registry service > Double click on it and set the Startup type: to Automatic > Click Apply > Finally start the service by click on Start button.

Start Remote Registry Service in windows if Home Assistant RPC Shutdown is not working

You can try again to shutdown your PC from Home Assistant after you start the Remote Registry service, but most probably you will fail, so keep reading.

Allow WMI in Windows Firewall

We have to create a simple Firewall Rule. Here is how:

Click on the Start button and type “allow” > Click on the Allow an app through Windows Firewall result > in the opened window scroll down until you see Windows Management Instrumentation (WMI) > Click on Change settings button and tick the checkbox under the Private column > finally click OK button.

Allow Windows Management Instrumentation (WMI) in Windows Firewall

Allow Windows Management Instrumentation (WMI) in Windows Firewall

You can try again to shutdown your PC from Home Assistant after you allow the Windows Management Instrumentation (WMI) in the Windows Firewall, but most probably you will fail, so keep reading.

Adding Local Policy in Windows Registry

It is Time to edit the Windows registry just a little bit :

Add a 32-bit DWORD named “LocalAccountTokenFilterPolicy” with a value of “1” (without quotes) under the following path in the windows registry: HKEY_LOCAL_MACHINE/SOFTWARE/Microsoft/Windows/CurrentVersion/Policies/System

Or download and start the following LATFP.reg file that I made, which is doing the exact same thing 👉 LINK

Adding the LocalAccountTokenFilterPolicy 32bit DWORD will allow most probably allow the Home Assistant RPC Shutdown

Adding the LocalAccountTokenFilterPolicy 32bit DWORD will allow most probably allow the Home Assistant RPC Shutdown

After this last step you can try again the Home Assistant RPC Shutdown and this time it should work. Congratulations 🥂

Support My Work

If you want to secure this site existence you can become one of my Patreons where you will receive early access to my content, exclusive content and depending of the tier – free access to my paid Smart Home Guide.

Of course there are other support options available and you can check them here 👉 LINK

With that being said, stay safe and don’t forget – Home Smart, but not hard!

Thank you for watching and I will see you in my next article.

Provide feedback

Saved searches

Use saved searches to filter your results more quickly

Sign up

Appearance settings

If your looking for an inexpensive way to setup an automatic turning on and shutting off of your windows computer systems, using WOL and RPC are an excellent way to do that, you can even setup a Linux server for controlling the timing for turning the systems on/off and it isn’t too difficult to manage. I will do a post soon about setting up a linux server to run WOL and RPC Shutdown scripts. If your looking to set one up the quick and dirty version is:


Requirements SAMBA, Windows Admin and Password, Linux Admin and Password


Put startup/shutdown scripts in /etc/cron.daily


Startup
sudo -i -u $linuxAdminUser -p $password wakeonlan -i $IPADDRESS $MACADDRESS


Shutdown
sudo -i -u $linuxAdminUser -p $password net rpc shutdown -I $IPADDRESS -U $WindowsADM%$password -t 1 -f


Use Crontab to setup scheduling

Crontab schedule



For more information about crontab, you can visit this link about crontab




Here are the break down of the examples above

00 12 * * 5 user command



at minute 00, hour 12, * — no value (day of the month), * — no value (month), 5  the fifth day of the week (friday), user to run the script and script to run.


So the following example «00 12 * * 5 root /etc/cron.daily/shutdown.sh»

at minute 00, at 12 pm, on friday run as root the script shutdown in /etc/cron.daily

Setting up the Windows 10 Client

For setting up WOL/RPC shutdown, you have to have your windows clients prepped with the proper firewall rules and user accounts for privileged access.

  • An administrator account (not called administrator as windows 10 upgrades disables this with each update)


  • RPC and Remote Access Firewall Rules Allowing (I also allow ICMP and Ping) for remote management with services such as lansweeper and FOG


  • Updated Intel network driver


One thing I have noticed recently is that the manufacturer driver doesn’t seem to work with WOL.  Working with some Lenovo m93 and m900 series and and HP {put hp model here} doing a full windows reinstall/reset breaks WOL.  Even getting an up-to-date manufacturer driver WOL doesn’t seem to work which is extremely odd. A major difference I can account for this is the update to the intel proset tools for their network driver which brings a GUI interface back to add and remove VLANs to Windows 10.

Nic Driver settings to enable WOL in Windows 10

Enable WOL in Windows 10.  In Windows 7 unchecking the computer to turn off the device would leave the device on but in windows 10 it disables all power management and turns it off.  For WOL to work you have to enable «Only allow a magic packet to wake the computer option»

Wake on Link Settings — Disabled

Wake on Magic Packet — Endabled

Wake on Pattern Match — Enabled

Wait for Link — Auto

Even with these settings being enabled and no errors WOL would not go.  I had S3, S4 and S5 enabled in the bios, which would enable WOL to work, but when I send the WOL packet the system stays off.

Version 25 of the Intel network driver and proset tools

Intel Proset software and drivers

Adapter driver Options

Teaming and Vlans

Once I updated the driver to version 25 WOL started working for my windows client.


RPC shutdown from Linux


sudo -i -u $linuxAdminUser -p $password net rpc shutdown -I $IPADDRESS -U $WindowsADM%$password -t 1 -f

RPC SHUTDOWN ERROR

To fix this issue

Manual Registry Hack

Open regedit.exe through the start menu search or run box, and then navigate down to the following key, creating a new key if it doesn’t exist.

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System

Change the LocalAccountTokenFilterPolicy to 1


On the right-hand side, add a new 32-bit DWORD value named LocalAccountTokenFilterPolicy and set the value to 1.

To remove this tweak you can set the value to 0 or just delete the key.

With this setup you will be able to startup and shutdown any pc you have listed in your startup and shutdown scripts.





References

Понадобилось мне добавить в Home Assistant свой игровой PC. А именно возможность включения и выключения.

Возможность включение я разберу в другой статье, а в этой расскажу про выключение.

Быстрое гугление наводит на:

net rpc shutdown

Но я использую Home Assistant в Hass.io на малинке, а там не так просто доустановить отсутствующие утилиты. Нужен был способ исключительно на Python.

Я нашёл интересную библиотеку pypsexec и решил оформить её в виде компонента HA. Библиотека создаёт исполняемые exe-шники в папке Windows и запускает их через службы Windows, которые так же создаёт. Я решил немного поправить этот подход и обойтись только созданием служб Windows. Вот что получилось:

/config/custom_components/psexec/__init__.py

«»» Компонент добавляет службу `psexec.exec` удаленного выполнения команд на компьютерах Windows через протокол `SMB 2`. В момент выполнения на удалённом компьютере создаётся и запускается служба Windows, выполняющая указанную команду. По завершению выполнения служба удаляется. Удалённый пользователь должен быть администратором. Если на удалённом компьютере включен UAC — необходимо внести правки в реестр: «` Windows Registry Editor Version 5.00 [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System] «LocalAccountTokenFilterPolicy»=dword:00000001 «` Если удалённый Windows старый (например win7) — необходимо указывать параметр `encrypt=false`. Подробности тут: https://pypi.org/project/pypsexec/ Пример использования (создаст в корне диска C файл out.txt): «` script: smb_remote: sequence: — service: psexec.exec data: host: 192.168.1.123 username: user password: pass encrypt: false command: cmd.exe /c echo Hello World > c:\out.txt «` Для засыпания компьютера необходимо отправить команду: «` cmd.exe /c start /b shutdown.exe /h «` — `cmd.exe /c` — выполняет далее указанную команду (для start нет exe файла) — `start /b` — запускает следующую команду в фоне (нельзя дожидаться окончания выполнения shutdown — мы его не дождёмся) — `shutdown.exe /h` — отправляет компьютер в сон (или гибернацию в зависимости от настроек компьютера) Компонент протестирован в HA на Windows и в Hass.io на Raspberry Pi 3. «»» import logging _LOGGER = logging.getLogger(__name__) DOMAIN = «psexec» def setup(hass, config): def exec(call): import uuid from smbprotocol.connection import Connection from smbprotocol.session import Session from pypsexec.scmr import Service host = call.data.get(‘host’) username = call.data.get(‘username’) password = call.data.get(‘password’) encrypt = call.data.get(‘encrypt’, True) command = call.data.get(‘command’) try: connection = Connection(uuid.uuid4(), host) connection.connect() session = Session(connection, username, password, require_encryption=encrypt) session.connect() service = Service(‘HomeAssistant’, session) service.open() try: service.create(command) except: _LOGGER.exception(«Can’t create service») try: service.start() except: # Произвольный EXE-файл не может быть полноценной Службой, # поэтому даже при успешном выполнении мы будем получать ошибку pass try: service.delete() except: _LOGGER.exception(«Can’t delete service») service.close() connection.disconnect() except: _LOGGER.exception(f»Can’t connect to: «) hass.services.register(DOMAIN, ‘exec’, exec) return True

/config/custom_components/psexec/manifest.json

{ «domain»: «psexec», «name»: «PsExec», «documentation»: «https://www.home-assistant.io/», «dependencies»: [], «codeowners»: [ «AlexxIT» ], «requirements»: [ «pypsexec» ] }

Для появления соотвествующей службы в Home Assistant необходимо включить компонент в configuration.yaml

psexec:

Пример использования и краткое описание приведены в комментариях к коду.

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


Allows you to shut down a Windows computer with a service call from Home Assistant.

{
  "computers": [
    {
      "alias": "test-pc",
      "address": "192.168.0.1",
      "credentials": "user%password"
    }
  ]
}
  • computers (Required): A list of computer objects to shutdown from Home-Assistant.
  • computers/alias (Required): Set an alias for this record which becomes the name for the input.
  • computers/address (Required): IP address or NetBIOS name of the computer for the shutdown.
  • computers/credentials (Required): Credentials for logging into computer. Use a % as the delimiter of username and password.

Home Assistant

Use the following inside Home Assistant service call to use it:

service: hassio.addon_stdin
data:
  addon: core_rpc_shutdown
  input: test-pc

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Ноутбук не находит вай фай windows 7
  • Пропал доступ к интернету windows 7
  • Что такое служба активации windows
  • Как поставить windows 10 на mac через bootcamp
  • Не работает предпросмотр pdf в проводнике windows 10