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.
Would like to know if it asks for a login password as well, what change would be required in this command.
Yes we are mentioning the password with echo.
So it should not ask any other login password.
In case you want it to ask, you can use “read -p ” command and mention that input in password.
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” ; donetest@server1’s password:
have you heard of expect ? … try to google it, and install it on one system to get this done… if there is possibility of key, you can copy private key of a global user in your env, and mention it using -i in ssh…