从一个bash脚本如何快速查找端口445是否在服务器上打开/监听。
我已经试过几个办法了,但我想快点: 1. lsof -i:445(需要数秒) 2. netstat -an |grep 445 |grep LISTEN(需要数秒) 3.Telnet(不返回) 4. 服务器上没有Nmap、netcat
知道一种不先枚举然后再grep的方法将会很好。
从一个bash脚本如何快速查找端口445是否在服务器上打开/监听。
我已经试过几个办法了,但我想快点: 1. lsof -i:445(需要数秒) 2. netstat -an |grep 445 |grep LISTEN(需要数秒) 3.Telnet(不返回) 4. 服务器上没有Nmap、netcat
知道一种不先枚举然后再grep的方法将会很好。
当前回答
基于Spencer Rathbun的回答,使用bash:
true &>/dev/null </dev/tcp/127.0.0.1/$PORT && echo open || echo closed
其他回答
如果你使用的是iptables,试试:
iptables -nL
or
iptables -nL | grep 445
你可以这样使用netstat来获得更快的结果:
在Linux上:
netstat -lnt | awk '$6 == "LISTEN" && $4 ~ /\.445$/'
在Mac:
netstat -anp tcp | awk '$6 == "LISTEN" && $4 ~ /\.445$/'
这将输出在端口上侦听的进程列表(本例中为445),如果端口空闲,则不输出任何内容。
ss -tl4 '( sport = :22 )'
2毫秒够快吗?
添加冒号可以在Linux上工作
基于Spencer Rathbun的回答,使用bash:
true &>/dev/null </dev/tcp/127.0.0.1/$PORT && echo open || echo closed
你可以使用netcat。
nc ip port < /dev/null
连接到服务器,然后直接重新关闭连接。如果netcat不能连接,它将返回一个非零退出码。退出码存储在变量$?举个例子,
nc ip port < /dev/null; echo $?
当且仅当netcat成功连接到端口时返回0。