Run remote ssh command using command_line switch

I have never really been a fan of allowing root access to a server as you can achieve the same results in a more controlled manner by doing the following:

create a config file in the /config/.ssh dir:

Host host
HostName 192.168.1.X
User user
IdentityFile /config/.ssh/id_rsa
Port 22
StrictHostKeyChecking no

which means your commands are now as follows:

command_on: "ssh host 'sudo echo 1 > /sys/class/gpio/gpio108/value'"

Note: make sure you chmod the .ssh dir as 700 and the everything in the .ssh dir as 600

If you are running sudo commands make sure you add the line to the sudoers file on the remote host:

user ALL = (root) NOPASSWD: /bin/echo 1 > /sys/class/gpio/gpio108/value
user ALL = (root) NOPASSWD: /bin/systemctl shutdown
user ALL = (root) NOPASSWD: /bin/systemctl poweroff -i

Note: user = 1000 host of remote server

1 Like

Great tip for systems that allow it. I’m SSHing into some partially-liberated Android 8 wall panel that for some reason is resistant to SSH as any other user than root and doesn’t have various basic system binaries.

Long-term, it’d be great to transition to a solution using MQTT and hopefully a replacement AOSP rom. That’s the end goal, but that’s not really relevant to this conversation.

You can still allow root, but using PWD is not ideal.

If it shows ssh it’s most likely capable of supporting Public key Auth which will still allow for better layer of security.

Yes, i’m using the -i parameter in the commands above, which specifies the key file. Even had to go through the hassle of finding supported common algorithms since the recent OpenSSH deprecation of older ones knocked out a lot of what was supported in Android 8.

Oh yeah off-course I forgot about that :slight_smile:

You should therefore be able to just specify +ssh-rsa as the option and you should be good

Host host
HostName 192.168.1.X
User user
IdentityFile /config/.ssh/id_rsa
Port 22
StrictHostKeyChecking no
PubkeyAcceptedAlgorithms +ssh-rsa
HostkeyAlgorithms +ssh-rsa

For someone from the future learning from this thread, this is how I set up my comand_line switch using HASS 2024.8.3:

#configuration.yaml

command_line:
  - switch:
      name: Kodi
      command_on: "ssh -o StrictHostKeyChecking=no -i /config/.ssh/id_ed25519 [email protected] 'sudo service xbmc start'"
      command_off: "ssh -o StrictHostKeyChecking=no -i /config/.ssh/id_ed25519 [email protected] 'sudo service xbmc stop'"
      command_state: "ssh -o StrictHostKeyChecking=no -i /config/.ssh/id_ed25519 [email protected] 'sudo service xbmc status | grep -q start'"
      unique_id: "switch.rpi_kodi"
      scan_interval: 60