linux shell 检查端口开放

端口探测无非也就是telnet、nc的命令,用法基本如下:

[root@SY-68-2 ~]#echo "bye" | timeout 3 telnet www.baidu.com 81
Trying 61.135.169.121...
[root@SY-68-2 ~]#echo "bye" | timeout 3 telnet www.baidu.com 80
Trying 61.135.169.125...
Connected to www.baidu.com.
Escape character is '^]'.
Connection closed by foreign host.
[root@SY-68-2 ~]#
[root@SY-33-2 ~]# nc -z -w 5 www.baidu.com 80 && echo OK || echo Failed
Connection to www.baidu.com 80 port [tcp/http] succeeded!
OK
[root@SY-68-2 ~]# nc -z -w 5 www.baidu.com 81 && echo OK || echo Failed
Failed
[root@SY-68-2 ~]#

 

bash自身包含的一种方式:
/dev/tcp/host/port 和 /dev/udp/host/port

用法也很简单:

[root@SY-68-2 ~]# echo >/dev/tcp/www.baidu.com/80 && echo "port 80 is open" || echo "port 80 is closed"
port 80 is open
[root@SY-68-2 ~]#

但这种用法本身是不带超时时间设置的,幸好我们有timeout命令,组合起来便是:

[root@SY-68-2 ~]#timeout 5 bash -c "echo >/dev/tcp/www.baidu.com/80" > /dev/null 2>&1 && echo "port 80 is open" || echo "port 80 is closed"
port 80 is open
[root@SY-68-2 ~]#
[root@SY-68-2 ~]#timeout 5 bash -c "echo >/dev/tcp/www.baidu.com/8080" > /dev/null 2>&1 && echo "port 8080 is open" || echo "port 8080 is closed"
port 8080 is closed
[root@SY-68-2 ~]#
 

就是如此,写一个for循环,便可以批量检测了。

样例文件如下:

#cat ports
119.181.69.96 8080
220.181.111.188 80
119.181.20.18 8080
202.108.22.220 53

脚本和输出结果如下:

cat ports | while read line
do

IP=`echo $line |awk '{print $1}'`
  PORT=`echo $line |awk '{print $2}'`

timeout 5 bash -c "echo >/dev/tcp/$IP/$PORT" > /dev/null 2>&1 && echo "$IP $PORT is open" || echo "$IP $PORT is closed"

done

# sh test.sh
119.181.69.96 8080 is closed
220.181.111.188 80 is open
119.181.20.18 8080 is closed
202.108.22.220 53 is open

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值