How could I shutdown a remote host, in my network thru ssh, with a local host?
For the following I am assuming that the user you are going to use in remote-host
is the same you use in local-host
.
In order to do what you want, you have to first authorize your local-host
to connect to you remote-host
with no password. To do that you have to (as described here):
-
Install
ssh
:sudo apt-get install ssh
-
Create public and private keys using
ssh-key-gen
onlocal-host
by entering this command in yourlocalhost
:ssh-keygen
You should save the generated key in:
/home/yourusername/.ssh/id_rsa
Press enter twice to leave the passphrase empty.
Your identification has been saved in /home/yourusername/.ssh/id_rsa. Your public key has been saved in /home/yourusername/.ssh/id_rsa.pub. The key fingerprint is: XX:XX:XX:xX:XX:xX:XX:XX:XX:XX:XX:XX:XX:XX yourusername@local-host
-
Copy the public key to the
remote-host
usingssh-copy-id
:yourusername@local-host$ ssh-copy-id -i ~/.ssh/id_rsa.pub remote-host yourusername@remote-host's password: Now try logging into the machine, with: ssh remote-host
and check in
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.Note:
ssh-copy-id
appends the keys to theremote-host
’s/home/yourusername/.ssh/authorized_key
. -
Login to
remote-host
without entering the password:ssh remote-host yourusername@remote-host:~$
Access to
remote-host
with no password. Success!
Now you have to be able to execute sudo shutdown -P 0
with no password. You can do that by modifying /etc/sudoers
on remote-host
with visudo
. That way, user yourusername
can execute the shutdown
command with no password asked.
-
Login to the
remote-host
:ssh remote.host
-
Run:
sudo visudo
By running
visudo
, you edit/etc/sudoers
in a safe manner. -
Add this line to the file:
yourusername ALL = NOPASSWD: /sbin/shutdown
-
After doing that, get back to your
local-host
, create a new empty file and paste this line, modifying theremote-host
's name:ssh remote.host sudo shutdown -P 0
-
Save and close the file, right-click on it to go to its Properties → Permissions, and tick Execute this file as a program.
Script done!