SSH to Server, Execute Command, and Maintain Connection
I want to write a script that opens a terminal with different tabs, logon to a server using ssh
in each tab and execute a command in each tab. For example: htop
.
The below script opens a terminal with 4 tabs all logged in on the server. But if I try to add the htop
command in the cmd=
line it does not work anymore...
#bin/bash
tab="--tab"
cmd="bash -c 'ssh user@host';bash"
foo=""
for i in 1 2 3 4; do
foo+=($tab -e "$cmd")
done
gnome-terminal "${foo[@]}"
exit 0
I have tried this...
cmd="bash -c 'ssh user@host htop';bash"
...because the ssh --help
says that the syntax for ssh
is:
usage: ssh [user@]hostname [command]
Solution 1:
In its simplest form:
ssh -t user@host "command; bash"
-t
is the critical part here. It forces the host to allocate a virtual terminal to the process, which allows it to stay open.
If you just want to run htop on a load of servers, you can omit the bash
at the end but that does mean if you quit htop, you'll drop back to a local terminal.