Start and stop remote server via Home assistant

Recently i have been playing a lot with LLM’s and i wanted to run the open-webui software on a server. I will write a separate post about that and Ollama.

But the only machine i have that can run it, is an old desktop PC which uses about 50w idle which is a bit wasteful to run 24/7. So i was looking for a way to easily turn the machine on and off when needed preferrably remotely as well. I already run Home Assistant, so i managed i figured that would be a nice way to integrate it. This post describes how i did it:

Server status

The server status is made using the default Ping integration, which pings the server every 60 seconds.

- entity: binary_sensor.192_168_2_199

Turn on machine (‘Aanzetten’)

This is the Wake On Lan integration where you only need to configure the MAC address and nothing else. The device needs to be in the same network as Home Assistant.

What gave me the most trouble was activating Wake on Lan on the motherboard of the server. Support on Linux was lacking, so i needed to add a patch https://github.com/AndiWeiss/alx-wol

- type: button
  tap_action:
    action: perform-action
    perform_action: wake_on_lan.send_magic_packet
    target: {}
    data:
      mac: D4:3D:7E:D8:96:71
      broadcast_port: 9
  entity: button.wake_on_lan_d4_3d_7e_d8_96_71
  name: Aanzetten
  icon: mdi:power-on

Turn off machine with (‘Uitzetten’)

You cannot turn a machine off using Wake on Lan, but you can easily using SSH. A common way to execute SSH commands is by creating a so called shell command.

Important here is that the private key used for authentication needs to be in the config folder of home assistant itself. Note that i do use the docker container setup on a normal Raspbian installation.

shell_command:
  shutdown_plank_server: 'ssh -i /config/id_rsa -o "StrictHostKeyChecking=no" nigel@192.168.2.199 "sudo shutdown -h now"'

But by default it will ask a password when attempting to execute the command using sudo. You need to make an exception on the remote host to allow execution of this command without having to enter your password. Enter sudo visudo and add the following line. Enter which shutdown to find out what shutdown executable your user uses:

nigel ALL=(ALL) NOPASSWD: /usr/sbin/shutdown -h now

Now you can execute the shell command by binding it to a button for example:

- type: button
  tap_action:
    action: call-service
    service: shell_command.shutdown_plank_server
  name: Uitzetten
  icon: mdi:power-off

Hope that this helps someone. It actually didn’t help me, because after spending an entire afternoon to set this up i came to the conclusion that i didn’t actually need it! This is because i can easily run open-webui on both my personal and work laptop.. 😅