Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
2  
What have you tried and why doesn't it work/what errors are you getting? –  Mat Apr 24 '12 at 8:10
    
i tried ssh, but i don't know how to run as a root. –  Dan Apr 24 '12 at 9:04
    
Do you have root access on the remote machine? –  Kevin Apr 25 '12 at 1: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 2:02
    
add comment

2 Answers 2

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.

share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.