I would like to modify my existing SSH connection via a shell script. So if I run an existing script remotely I would like it to open a new port to be tunnelled.

Interactively I can do this via:

ubuntu@6c1a17c3864c:~$ ~C
ssh> -R 9000:localhost:9000

As put much more clearly than I could: https://unix.stackexchange.com/questions/33557/using-an-already-established-ssh-channel.

Ideally I would like to use a shell script to interact via the escaped characters to adjust the existing connection.

I have looked at something like:

# Attempt 1
echo -n '\r\f \~\~C -L 9000:localhost:9000'
# Attempt 2
echo -e '\r\f\~\C -R 9000:localhost:9000'
printf '\~\C -L 9000:localhost:9000'
netstat -taln

As well as a few other combinations.

I have verified that both echo and printf are shell builtins.

I'm using Bash 4.3.11 x86_64-pc-linux-gnu.

  • you would probably need expect script to achieve this. But why? You can define port forwarding on command-line much easier.
    – Jakuje
    Feb 13, 2016 at 10:06
  • I was hoping to be able to define a set of bash functions that could modify the existing ssh session. I'm not great at this really low level stuff. But can't see any reason it couldn't be done in bash. Expect might work well though. I'll see what I can do there to get it to play nicely.
    – Luke Exton
    Feb 13, 2016 at 10:12
  • The problem is that these escape chars are NOT evaluated by bash, but locally by your ssh client.
    – Jakuje
    Feb 13, 2016 at 10:14
  • So the escape chars I want to send would need to be evaluated by the ssh client on my local machine right? Rather than bash on the remote end. Even sending this via tcl/expect then wouldn't evaluate it on the client side?
    – Luke Exton
    Feb 13, 2016 at 10:21
  • expect should do that, but I didn't try yet. There are some references.
    – Jakuje
    Feb 13, 2016 at 10:24

1 Answer 1


You would need expect script to achieve this. The problem is that these escape chars are NOT evaluated by bash, but locally by your ssh client. Example that should do the job:

#!/usr/bin/expect -f
set timeout 10
 exp_internal 1
spawn telnet $argv
expect "login:"
send "mylogin\n"
expect "Password:"
send "mypass\n"
expect '~$'
# Send some commands


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.