shell命令组合工具积累:

74 篇文章 3 订阅
32 篇文章 3 订阅

判断pod到指定地址端口连通性

 pod里面不带telnet命令,怎么判断端口通不通呢?

用下面的命令:

timeout 1 bash -c 'cat < /dev/null > /dev/tcp/google.com/80'
$ echo $?
0
看返回结果:

结果是0就是通

结果是其他数字就是不通

nmap-ncat测试尚未使用的本地端口


availabletobindon() {
  port="$1"
  nc -w 2 -i 1 localhost "$port" 2>&1 | grep -v -q 'Idle timeout expired'
  return "$?"
}

在某些情况下,例如curl,telnet,nc o nmap等工具不可用,您仍然有机会使用wget

if [[ $(wget -q -t 1 --spider --dns-timeout 3 --connect-timeout 10  host:port; echo $?) -eq 0 ]]; then echo "OK"; else echo "FAIL"; fi

 

使用bash检查端口

$ ./test_port_bash.sh 192.168.7.7 22

端口22是开放的

脚本

HOST=$1
PORT=$2
exec 3> /dev/tcp/${HOST}/${PORT}
if [ $? -eq 0 ];then echo "the port $2 is open";else echo "the port $2 is closed";fi

在Bash中,使用伪设备文件进行TCP / UDP连接很简单。

脚本

#!/usr/bin/env bash
SERVER=example.com
PORT=80
</dev/tcp/$SERVER/$PORT
if [ "$?" -ne 0 ]; then
  echo "Connection to $SERVER on port $PORT failed"
  exit 1
else
  echo "Connection to $SERVER on port $PORT succeeded"
  exit 0
fi

 测试

$ ./test.sh 
Connection to example.com on port 80 succeeded

 这是单行(Bash语法):

</dev/tcp/localhost/11211 && echo Port open. || echo Port closed.

使用curl检测服务访问状态码

curl -I  -s -o /dev/null -w "%{http_code}\n"  www.baidu.com

 

参考连接:

https://stackoverflow.com/questions/4922943/test-if-remote-tcp-port-is-open-from-a-shell-script

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值