3

I want to execute a shell script on a remote server, and the script should be run by root with no password required (or use sudo in the script). Can anyone give me some suggestions?

Kevin
  • 40,767
Dan
  • 141

3 Answers3

6

Beside solutions with sudo, that can be script-friendly be configured (no extra password-prompt for specific commands) or setuid solutions which are not easy to do secure, I suggest the usage of ssh public-key authorization with the command= restriction.

For this, you need to enable password-less login to the root user if not yet done (PermitRootLogin without-password in /etc/ssh/sshd_config) and add your (or better a special for this case created) ssh public key to /root/.ssh/authorized_keys with a command= argument like described in this answer.

jofel
  • 26,758
2

You don't need to place your root password in script.

Solution A

suid your script on the server , and make it read / executable only by root or your user group.

chmod 4750 script.sh
chgrp your_group script.sh

Don't forget to join your user into that group.

And you do ssh user@XXXX '/path/to/script.sh' to execute the script.

Solution B

Create a SSH key , and copy public key to the remote server. This way you'll have to login as root , but also password-less. (Remeber to decrypt your private key with openssl)

It's very dangerous if you lost your private key.

daisy
  • 54,555
0

The save solution without root users

on the client generate an ssh-key

client: ssh-keygen

copy it to the server

server: mkdir ~/.ssh

client: scp ~/.ssh/id_rsa.pub serveruser@server:~/.ssh/authorized_keys

allow sudo without password for your user

server:

visudo
    serveruser ALL=(ALL) NOPASSWD: /usr/bin/foo /usr/sbin/bar

now you can run commands like that

client: ssh serveruser@server 'sudo foo && bar'

//some servers my require ssh -t ... to use sudo

Goody
  • 1