Put your Windows PC to Sleep or execute anything else with OpenHAB

Hey there =)

Today I figured out how to put your Windows PC to Sleep from OpenHAB. This is NOT about shutting it off but to put it to SLEEP. However I guess with using this strategy you can shut it down as well as execute anything in the command line of the Target PC.
There are plenty of tutorials to shut your pc down however I could not find one to put it to sleep.

  1. Install OpenSSH on the Host/Target-PC (the PC you want to execute your commands on):
    There is a great and SUPER SIMPLE tutorial from Microsoft: Erste Schritte mit OpenSSH fĆ¼r Windows | Microsoft Learn This site is in German but on the top right there is a switch ā€œAuf Englisch lesenā€ which toggles the site to use English.

  2. Try the ssh connection from your OpenHAB-Server:
    a) sudo -u openhab ssh user@target
    b) it establishes a connection
    c) close the ssh connection with exit

  3. To open a ssh connection to your server in a script (which is what we have to do) your script has to be not asked for a password for the for user of the target pc. In order to accomplish that type these instructions on your OpenHAB-Server. I am assuming your server is running on Linux. When using Windows as a server this commands should only be somewhat different.
    a) sudo -u openhab ssh-keygen -t rsa
    Dont enter a password for the file when asked. If youā€™d so so running the script later wonā€™t work.
    This generates a pair of unique ssh keys to authenticate

    b) The contents of the just generated id_rsa.pub file have to put into C:\Users\USER\.ssh\authorized_keys. To accomplish that a just copied the file to the OpenHAB-Samba Share folder.
    To do this use: sudo cp /var/lib/openhab2/.ssh/id_rsa.pub /srv/openhab2-conf
    Now you can grab on your windows pc and attach the complete content of id_rsa.pub to the end of C:\Users\USER\.ssh\authorized_keys.
    c) You may want to restart the ssh server with Restart-Service sshd executed in the Windows PowerShell started as administrator.

  4. Test the ssh connection from your OpenHAB-Server again:
    a) sudo -u openhab ssh user@target
    b) this time you should not be asked for a password
    c) close the ssh connection with exit

  5. Now comes the simple and routine parts:
    a) Create a script to put your pc to sleep with touch /etc/openhab2/scripts/pc_to_sleep.sh
    b) Everything in between of the ā€™ ā€™ can be deleted and replaced with anything you want to execute in the command line of the host pc. This is the code to put the pc to sleep.
    c) sudo chown openhab:openhab /etc/openhab2/scripts/pc_to_sleep.sh
    d) sudo chmod 770 /etc/openhab2/scripts/pc_to_sleep.sh

#!/bin/bash

ssh -o "StrictHostKeyChecking no" USER@HOST 'powercfg -hibernate off  &&  start /min "" %windir%\System32\rundll32.exe powrprof.dll,SetSuspendState Standby  &&  ping -n 3 127.0.0.1  &&  powercfg -hibernate on'

exit 0
  1. Configure OpenHAB:

exec.whitelist

/etc/openhab2/scripts/pc_to_sleep.sh

XXX.items

Switch  Asterix_Power   "PC"                 
Switch  Asterix_WOL     "Wake-on-LAN Asterix"        {wol="255.255.255.255#MAC-ADRESS"}
Switch  Asterix_ToSleep "PC Energiesparmodus"        {channel="exec:command:Command_Asterix_ToSleep:run"}

exec.things (the exec binding has to be installed)

Thing exec:command:Command_Asterix_ToSleep [command="/etc/openhab2/scripts/pc_to_sleep.sh", interval=0]

XXX.rules

rule "PC an/aus"
when
    Item Asterix_Power received command
then
    if (receivedCommand == ON) {
        logInfo("Rule triggered", "Rule \"trigger_things_with_switches.rules: PC an/aus: an\" started")
        Asterix_WOL.sendCommand(ON)
    } else {
        logInfo("Rule triggered", "Rule \"trigger_things_with_switches.rules: PC an/aus: aus\" started")
        PC_ToSleep.sendCommand(ON)
    }
end

XXX.sitemap

Switch item=Asterix_WOL label="PC" mappings=[ON="AN"]

Now you are able to turn your pc on and off with OpenHAB.
I hope I could help you. If you have any questions hit me up =)

Greetings,
Felix

5 Likes

Thanks for this, very interesting!

Thanks for the code, thats a great idea!
For openhab 3, some pathes need to be changed. I struggeld with the authentication, thats because of some Changes in Windows 10:

After commenting out those two lines from the bottom of sshd_config it works well.

The ECMA / Javascript for openHAB3:

var log = Java.type("org.slf4j.LoggerFactory").getLogger("org.openhab.model.script.Rules.pc_to_sleep");
var Exec = Java.type('org.openhab.core.model.script.actions.Exec');
var Duration = Java.type('java.time.Duration');

////////////////////////////////////////////////////////////////////////

execRes = Exec.executeCommandLine(Duration.ofSeconds(10),'/etc/openhab/scripts/pc_to_sleep.sh');

log.info("pc_to_sleep.sh: " + execRes);

The script for hibernate mode:

 #!/bin/bash

ssh -o "StrictHostKeyChecking no" user@host 'start /min "" %windir%\System32\rundll32.exe powrprof.dll,SetSuspendState &&  ping -n 3 127.0.0.1'

exit 0

Update: Works with Windows 11.

3 Likes

Just wanted to say thanks for this. Iā€™ve recently started using windows 11 and it is having an issue not going to sleep per its settings. But it was a good time to do this setup and trigger sleep off of my office status on/off.

The only issue i had was with the permissions for the public key file on win11 under openssh. Beyond that it works like a charm, thx!

I have used this for a long while now, easy setup etc.

withe this rule

rule "Desktop OFF"
when
	Item Desktop changed from ON to OFF
then
	sendHttpGetRequest("http://192.168.*.*:5001")
end

Just thought I would add this to this thread as it may be useful to some.

1 Like

Can you please clarify with permissions are needed? Anything special? The standard is 644 and should work, doesnā€™t it?

Thanks for sharing Remote Shutdown Manager, @Adrian_Hills. Iā€™ve been perfectly satisfied with Assistant Computer Control, but I donā€™t use ACC for anything other than putting my PC to sleep. RSM is a much more direct solution that was super easy to implement.

You bet. My daily ID for use with windows 11 is an admin ID (I know, I know :)) meaning that for passwordless auth with openssh server the public key must have ONLY admin permissions. If you have any local permissions setup at all it wonā€™t work and will prompt for a password.

Iā€™m tempted to actually try out a couple of the other methods above that were since listed, but I like the fact that Iā€™m not dependent on any other services or applications with a direct call via SSH.

Cheers

1 Like

Hi guys, Iā€™m trying to figure out how to start a virtual machine on my Truenas system from within openhab. So far i have a working ssh connection between the systems (passwordless auth) and a working script on the NAS that starts the server. I can ssh to the machine and run the script from there with the ssh user specified for openhab, I can run a script file that connects and starts the c/m from openhab cli, everything is working. But I cannot for the life of me figure out how to get that working with the exec binding. All possible commands are on the whitelist but when I flick my switch the exec items status turns on and off within a second and nothing happens. It seems like that I might need to add a wait in the script because it kills the script to early?

 #!/bin/bash

ssh -o "StrictHostKeyChecking no" openhab@192.168.178.10 'sudo ./mnt/VM/scripts/start_vm'

exit 0

Maybe someone can help :slight_smile: thanks a lot!

Did you tey executeCommandLine instead of exec binding?

Just tried it, no difference.

My code looks as follows

configuration: {}
triggers:
  - id: "1"
    configuration:
      itemName: WindowsVM_Switch
      command: ON
    type: core.ItemCommandTrigger
conditions: []
actions:
  - inputs: {}
    id: "2"
    configuration:
      type: application/vnd.openhab.dsl.rule
      script: executeCommandLine(Duration.ofSeconds(30),
        "/etc/openhab/scripts/wake_windowsvm.sh")
    type: script.ScriptAction

I have no idea what is going on, is there a way that i can log on as the actual openhab process user to check if i can run the script there? Because every other way works, it just seems openhab cannot run the script.
The weird thing is it seems like with the exec-binding itā€˜s actually running the script because i get the output (0) but i feel like itā€˜s not waiting on completion of the ssh commandā€¦

Run

sudo su -s /bin/bash openhab

this will give you a shell with privileges of user openhab.
Then execute your script.

What you also can do is to enter a code line in your script that writes output to a logfile e.g. /tmp/My.log.

echo "`/bin/date`: This script was executed" >> /tmp/My.log

Now it seems like Iā€™m making some progress. Iā€™ve found out that the openhab user cannot read the .ssh file as it seems. Or it cannot see it. The user with which Iā€™m logging in via ssh is called openhab3, when I run the script withthis user everything works. Iā€™ve created the ssh keypair as described in the first post.

I feel like I have to recreate the keypair while logged in with openhabā€˜s user?

@edit: forget what I said, it seems like that during experimentation my ssh keypair got fd up, generated a new one and now itā€™s working with the exec binding.