How to run sudo command over ssh to remote servers via a script in Linux/Unix ?

Today in this post, we will look how to run a command with root user, i.e. using sudo on remote server.

And how to place it in a loop to execute on multiple servers together.

Suppose you want to run a script using root on a remote server.

Solution 1: To execute the command on one remote server.

### Write your sudo password in echo
$ echo Password@123 | ssh -o "StrictHostKeyChecking no" -tt "sudo ~nglinux/";


Solution 2: To run on multiple remote servers.

### Create a file hosts with list of servers on which you want to run command.
$ cat hosts

$ for i in `cat hosts`; do echo Password@123 | ssh -o "StrictHostKeyChecking no" -tt ngelinux@$i "sudo ~nglinux/" ; done

Similarly we can execute any command, for this to work seamless, we prefer to setup password less authentication to all your servers at first.

Leave a Reply

Your email address will not be published.