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?
-
i tried ssh, but i don't know how to run as a root. – Dan Apr 24 '12 at 09:04
-
Do you have root access on the remote machine? – Kevin Apr 25 '12 at 01:36
-
i have the root access remote machine. but i don't want to hard code the password in my local script because the password may be modified. – Dan Apr 25 '12 at 02:02
-
See also Copying protected files between servers in one line? – Gilles 'SO- stop being evil' Jul 11 '12 at 00:07
3 Answers
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.
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.

- 54,555
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

- 1