Saturday, October 29, 2022

[SOLVED] Bash script pass ssh command to remote server and bring back the prompt

Issue

I am restarting bunch of remote servers via bash script but the script waits for me to break before moving on.

#!/bin/bash
main()
{
        hostlist=("server1" "server2")
        echo -e "----- Reatsrting all servers -----"
        for host in ${hostlist[@]};
        do
                echo "----- Restarting $host -----"
                ssh -t $host "sudo reboot -f now"
                echo "----- Restart of $host complete -----"
        done
        echo "----- All servers restarted -----"
}
main

The result of above script is

----- Reatsrting all servers -----
----- Restarting server1 -----
packet_write_wait: Connection to 10.10.1.11 port 22: Broken pipe
----- Restart of server1 complete -----
----- Restarting server2 -----
packet_write_wait: Connection to 10.10.1.12 port 22: Broken pipe
----- Restart of server2 complete -----
----- All servers restarted -----

If you notice the "packet_write_wait: Connection to ...", this happens as the server takes time to restart and i have to manually break it by hitting enter, when i do that i get the packet_write_wait line and the script moves on with next code.

Is there a way by which i can just shoot the restart command and forget so i can move on with the rest of the script (get my prompt back without manually intervening)?


Solution

Putting it all together, with the advice from comments.

#!/bin/bash
main()
{
        hostlist=("server1" "server2")
        echo -e "----- Reatsrting all servers -----"
        for host in ${hostlist[@]};
        do
                echo "----- Restarting $host -----"
                ssh -t $host 'sudo reboot -f now &'
                echo "----- Restart of $host complete -----"
        done
        echo "----- All servers restarted -----"
}
main


Answered By - James Risner
Answer Checked By - Marilyn (WPSolving Volunteer)