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.

0 0 votes
Article Rating
Notify of

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: