This question already has an answer here:
I'm trying to find UNIX or bash command to run a command after connecting to an ssh server. For example:
ssh name@ip "tmux list-sessions"
The above code works, it lists the sessions, but it then immediately disconnects. Putting it in the sshrc on the server side works, but I need to be able to type it in client side. I want to be able to run a command, it logs in, opens up the window, then runs the command I've set. Ive tried
[command] | ssh name@ip
ssh name@ip [command]
ssh name@ip "[command]"
ssh -t name@ip [command]
This isn't quite what you're looking for, but I've found it useful in similar circumstances.
I recently added the following to my
$HOME/.bashrc
(something similar should be possible with shells other than bash):I keep a
screen
session running on one particular machine, and I've had problems withssh
connections to that machine being dropped, requiring me to re-runscreen -dr
every time I reconnect.With that addition, and after creating that (empty) file in my home directory, I automatically have the
screen -dr
command in my history when my shell starts. After reconnecting, I can just type Control-P Enter and I'm back in my screen session -- or I can ignore it. It's flexible, but not quite automatic, and in your case it's easier than typingtmux list-sessions
.You might want to make the
history -s
command unconditional.This does require updating your
$HOME/.bashrc
on each of the target systems, which might or might not make it unsuitable for your purposes.You can use the
LocalCommand
command-line option if thePermitLocalCommand
option is enabled:For more details about the available options, see the
ssh_config
man page.will execute the command and then start up a login shell when it completes. For example: