0

I have an Ubuntu server and I would like to shut it down from my laptop. I usually have to ssh into the server and type "sudo shutdown now" but it takes some time.

Is there any way to write a script to do this? How could I implement the ssh password?

terdon
  • 242,166

3 Answers3

1

Add Your public key to server, then send shutdown command:

ssh root@192.168.1.5 'shutdown'
DeviC3
  • 26
  • 1
  • Failed to set wall message, ignoring: Interactive authentication required. Failed to call ScheduleShutdown in logind, no action will be taken: Interactive authentication required. – Lolis4TheWin Mar 30 '22 at 19:17
1

This is just an example of what you could do. Modify for your own situation. There are a bunch of different ways to accomplish this with varying degrees of safety/security (eg. using sshpass with your password on the command line is really insecure and adding your user ssh key to root on the server is really, really insecure).

This assumes your user name is myuser.

On the server as root.

echo 'myuser ALL=(ALL) NOPASSWD: /usr/sbin/shutdown now' >> /etc/sudoers.d/99-myuser-shutdown

On the client/desktop/workstation as myuser:

ssh-keygen -t Ed25519 -N '' -f ~/.ssh/id_ed25519_shutdown

(echo -n 'command="/usr/bin/sudo /usr/sbin/shutdown now" ' && cat ~/.ssh/id_ed25519_shutdown.pub) | ssh myuser@server 'mkdir -pm 700 .ssh && cat >> .ssh/authorized_keys'

Now on the client to shutdown the server just do:

ssh -i ~/.ssh/id_ed25519_shutdown myuser@server

Even if your client user account gets hacked all they can do is shutdown the server. They won't have shell access on the server unless you add another key to authorized_keys or something and they certainly won't have root access(!).

CR.
  • 1,199
0

My suggestion is to use the sshpass command. However, initial authentication is required.

sshpass -p 'Password' ssh 192.168.xxx.xxx sudo shutdown -h now
  • sudo: a terminal is required to read the password; either use the -S option to read from standard input or configure an askpass helper – Lolis4TheWin Mar 30 '22 at 19:16