linux - 在 Bash 脚本中将 Telnet 命令传递给 SSH

标签 linux bash shell ssh telnet

我正在尝试编写一个 bash 以首先通过 ssh 连接到服务器,然后从该服务器通过 telnet 连接到 ElastiCache Redis 端点。

我的代码如下:telnet.sh

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

我想调用我的 bash 脚本并让用户以交互方式连接到 Redis 集群,以便用户可以在调用 telnet.sh 后输入 redis cli 命令。

以上代码打开并连接到 redis 集群,但立即关闭 ssh session 。有没有办法保持与 Redis 集群的连接并将输入直接返回给用户?

谢谢!

最佳答案

不要用 heredoc 覆盖标准输入——用户交互需要它。相反,将要远程运行的脚本作为命令行参数传递给 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"

使用 printf %q 生成我们变量的 eval 安全版本可确保内容完全按照 telnet 命令传递-given -- 确保即使 endpoint='$(rm -rf $HOME)',该值也被远程 shell 解释为常量字符串。

关于linux - 在 Bash 脚本中将 Telnet 命令传递给 SSH,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42566860/

相关文章:

linux - 共享内存 : what's the difference between the key and the id?

bash - 在一个命令中创建临时文件并将输出重定向到它

linux - 文件权限的测试条件

bash - 从文本文件中删除特殊字符(<200c> <200d>

linux - 覆盖库文件导致段错误

linux - 随 secret 码变量消失

bash - Uniq 许多文件到位

bash - 确定远程机器上的空闲线程数

bash - 如果 .bash_profile 通常以任何方式获取 .bashrc,为什么不直接使用 .bashrc?

linux - 在几个文件夹上加速 GNU 查找