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?

7
  • 2
    You can give the command directly as an argument: ssh your-server sudo shutdown now. Use a ssh key instead of ssh password (google). You still need to do something about the sudo password, though. Commented Mar 12, 2022 at 14:02
  • 3
    Does setting up passwordless ssh solve your issue? Commented Mar 12, 2022 at 14:13
  • @dirkt might need to be ssh -t ... Commented Mar 12, 2022 at 14:28
  • @roaima I can't think of a reason why -t would be needed. There's no TUI application involved. Commented Mar 12, 2022 at 18:20
  • @frabjous If sudo is configured with the “requiretty” option (default in some distributions), then it will reject attempts to use it in a session that has no tty... like when you run “ssh your-server any-command”. Commented Mar 13, 2022 at 19:44

3 Answers 3

1

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

ssh [email protected] 'shutdown'
1
  • Failed to set wall message, ignoring: Interactive authentication required. Failed to call ScheduleShutdown in logind, no action will be taken: Interactive authentication required. Commented Mar 30, 2022 at 19:17
1

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
1
  • sudo: a terminal is required to read the password; either use the -S option to read from standard input or configure an askpass helper Commented Mar 30, 2022 at 19:16
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(!).

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.