Sign up ×
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
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

3 Answers 3

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

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
chgrp your_group

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

And you do ssh user@XXXX '/path/to/' 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

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/ serveruser@server:~/.ssh/authorized_keys

allow sudo without password for your user


    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

share|improve this answer

Your Answer


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.