SSH to Server, Execute Command, and Maintain Connection

13,128

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.

Share:
13,128

Related videos on Youtube

Red
Author by

Red

Updated on September 18, 2022

Comments

  • Red
    Red almost 2 years

    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]

  • Red
    Red almost 11 years
    I tried cmd="bash -c 'ssh -t user@host htop';bash". It works but if I quit htop I drop back to local terminal and I don't want this happens
  • Oli
    Oli almost 11 years
    @Red Check your quotes - they're all over the place - you need to group htop and bash together so they're both run on the remote server. bash -c 'ssh -t user@host "htop;bash"' would be better but I don't see why you're trying to fry this thing in a bash wrapper in the first place. It isn't required - you're only running one command locally.
  • Red
    Red almost 11 years
    Thank you, now it works with cmd="ssh -t user@host htop;bash"
  • mc0e
    mc0e over 9 years
    A good answer, but there must be something better to use than bash in order not to terminate.
  • Oli
    Oli over 9 years
    @mc0e Depends what you want to do. This question is more about getting a useful shell after running your command. If you just want to pause, you could substitute bash for read.