tmux new-window ssh to remote host, then execute command and stay login

4.1k Views Asked by At

I use tmux on a jump box. I'm trying to automate certain common scenarios. How can I do the following?:

  1. create new window
  2. ssh to remote host
  3. execute some commands on remote host (i.e.: cd and dot-slash something)
  4. stay logged in

I can do it with ssh:

ssh -t [email protected] "cd ~adarias/duncans/ServiceAgent/tests; bash -l -c 'mocha config_tests.js'; bash -l"

but not with tmux new-window:

tmux new-window -t mosdev -d -n 'debug & test' 'ssh -T [email protected] < .mosdev/scripts/test_config.sh; bash -l'

I put the shell commands in a separate file because I was having issues with nested quotes which I couldn't figure out how to work around.

.mosdev/scripts/test_config.sh:

#!/bin/bash
cd ~adarias/duncans/ServiceAgent/tests; bash -l -c 'mocha config_tests.js'; bash -l

The ssh session to the remote host doesn't stay open. Although the new window does, I get dropped back at a prompt on the jump box.

So, what am I missing here? How can I get that session to stay open?

1

There are 1 best solutions below

0
On

I believe the problem is the use of the ssh command.

From the end of the AUTHENTICATION section in man ssh:

The session terminates when the command or shell on the remote machine exits and all X11 and TCP connections have been closed.

So I think that what you're seeing is ssh's expected behavior.

As a workaround, try using tmux send-keys to tell the window to log-in and then execute your script:

tmux new-window -a -d -t mosdev -n debug-test
tmux send-keys -t mosdev:debug-test "ssh [email protected]" C-m
tmux send-keys -t mosdev:debug-test "cd ~adarias/duncans/ServiceAgent/tests; mocha config_tests.js" C-m

Couple of notes:

  • I changed the window name to something without spaces.
  • C-m is the return key.

I noticed that at the time of my answer the question is two months old. Have you solved this already? If so, how did you?