Skip to content
Advertisement

Pass Telnet Command to SSH in Bash Script

I’m trying to write a bash to first ssh into a server and then telnet from that server to a ElastiCache Redis endpoint.

My Code is the following: telnet.sh

#!/bin/bash
...
ssh -t -i $key_home ec2-user@$private_ip << EOF 
        telnet $endpoint $_port
    EOF

I would like to call my bash script and have the user interactively be connected to the Redis Cluster so that the user can enter redis cli commands after invoking telnet.sh.

The above code opens and connects to the redis cluster but immediately closes the ssh session. Is there a way to stay connected to the Redis Cluster and direct input back to the user?

Thanks!

Advertisement

Answer

Don’t override stdin with a heredoc — you need it for user interaction. Instead, pass your script to run remotely as a command-line argument to ssh.

#!/bin/bash
#      ^^^^-- bash, not /bin/sh, to ensure that printf %q is available
#             ...ksh can also be used if modified to not need printf -v.

# generate a script to run remotely
printf -v cmd 'telnet %q %q' "$endpoint" "$_port"

# run that script
ssh -t -i "$key_home" "ec2-user@$private_ip" "$cmd"

Using printf %q to generate an eval-safe version of our variables ensures that content is passed through to the telnet command exactly as-given — ensuring that even if endpoint='$(rm -rf $HOME)', that value is interpreted by the remote shell as a constant string.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement