Execute SSH command remotely

Hello,

I want to run a command remotely on another Linux machine via SSH and save the result in an entity.
I used the following command, which works wonderfully in the SSH terminal in HA:

ssh -o LogLevel=QUIET userid@hostname -t "apt-get -qq update && apt-get -q -y --ignore-hold --allow-change-held-packages --allow-unauthenticated -s dist-upgrade | /bin/grep ^Inst | wc -l"

I ran ssh-keygen and ssh-copy-id in the terminal so that remote clients can log in without a password.

If I pack the whole thing into configuration.yaml, the command ends with error code 255.

- platform: command_line
    name: vzlooger Linux Update
    command : "ssh -o LogLevel=QUIET userid@hostname -t \"apt-get -qq update && apt-get -q -y --ignore-hold --allow-change-held-packages --allow-unauthenticated -s dist-upgrade | /bin/grep ^Inst | wc -l\""

Where is my mistake?

2 Likes

Thanks.
When I test my command from above under

docker exec -it homeassistant bash

the command executes and I get a result back.

The command is useless with PROTECTION MODE ENABLED.
Did you read the yellow text in your screenshot?

Of course not done.

In summary one can say:

  • SSH terminal protection mode off

  • docker exec -it homeassistant bash

  • ssh-keygen -t rsa
    no passphrase
    save in /config/.ssh/id_rsa.pub

  • ssh-copy-id -i /config/.ssh/id_rsa userid@hostname

  • ssh -o LogLevel=QUIET userid@hostname -i /config/.ssh/id_rsa -t “my command for remote host”

And then in configuration.yaml

sensor:
  - platform: command_line
    name: My Entity Name
    command : "ssh -o LogLevel=QUIET userid@hostname -i /config/.ssh/id_rsa -t \"my command for remote host\""
2 Likes

Thank you for this. It worked!! I had been working on it for hours. I had to modify it for my system. The .ssh folder on my system (HASS OS) is a subdirectory of the home directory. I ended up making a new directory config/.ssh/ to save the key. I also had a problem of shell_command finding my script. I put it in a subdirectory config/shell_scripts and the line under shell_command:
my_sciript: shell_scripts/my-script.sh