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.

0 0 votes
Article Rating
Subscribe
Notify of
guest

4 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Dinanshu Dua
Dinanshu Dua
1 year ago

Would like to know if it asks for a login password as well, what change would be required in this command.

Dinanshu Dua
Dinanshu Dua
Reply to  Saket Jain
1 year ago

Thanks Saket for your reply!!
in my case i dnt have the authority for password less login to my hosts. with password in echo, that issue is solved that it doesn’t asks to enter password during sudo command. However need to have a command that it should not ask for login password as well.

Would be grateful if you can help in this please

see below output

for i in cat hosts.txt; do echo test@123 | ssh -o “StrictHostKeyChecking no” -tt mv-core@$i “sudo tcpdump -w $i.pcap -i any port 3000 or port 8080” ; done
test@server1’s password: