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.
Requirement
Suppose you want to run a script firmware_update.sh 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 ngelinux@server1.ngelinux.com "sudo ~nglinux/firmware_update.sh";
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 server1.ngelinux.com server2.ngelinux.com server3.ngelinux.com server4.ngelinux.com $ for i in `cat hosts`; do echo Password@123 | ssh -o "StrictHostKeyChecking no" -tt ngelinux@$i "sudo ~nglinux/firmware_update.sh" ; 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.