ssh:检查隧道是否存在 [英] ssh: check if a tunnel is alive

查看:110
本文介绍了ssh:检查隧道是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个小bash脚本一条ssh隧道以从远程服务器中提取数据,因此它会提示用户:

I have written a small bash script which needs an ssh tunnel to draw data from a remote server, so it prompts the user:

echo "Please open an ssh tunnel using 'ssh -L 6000:localhost:5432 example.com'"

我想检查用户是否已打开此隧道,如果不存在隧道,则退出并显示错误消息.有什么方法可以查询ssh隧道,即检查本地端口6000是否真的通过隧道传输到该服务器?

I would like to check whether the user had opened this tunnel, and exit with an error message if no tunnel exist. Is there any way to query the ssh tunnel, i.e. check if the local port 6000 is really tunneled to that server?

推荐答案

这是我的测试.希望它有用.

This is my test. Hope it is useful.

# $COMMAND is the command used to create the reverse ssh tunnel
COMMAND="ssh -p $SSH_PORT -q -N -R $REMOTE_HOST:$REMOTE_HTTP_PORT:localhost:80 $USER_NAME@$REMOTE_HOST"

# Is the tunnel up? Perform two tests:

# 1. Check for relevant process ($COMMAND)
pgrep -f -x "$COMMAND" > /dev/null 2>&1 || $COMMAND

# 2. Test tunnel by looking at "netstat" output on $REMOTE_HOST
ssh -p $SSH_PORT $USER_NAME@$REMOTE_HOST netstat -an | egrep "tcp.*:$REMOTE_HTTP_PORT.*LISTEN" \
   > /dev/null 2>&1
if [ $? -ne 0 ] ; then
   pkill -f -x "$COMMAND"
   $COMMAND
fi

这篇关于ssh:检查隧道是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆