找到快捷方式,如果一个端口是开放的Linux [英] Quick way to find if a port is open on Linux

查看:141
本文介绍了找到快捷方式,如果一个端口是开放的Linux的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从bash脚本我怎么能快速找到各个端口是否 445 是开/听的服务器上。

From a bash script how can I quickly find out whether a port 445 is open/listening on a server.

我已经尝试了几个选项,但我想要的东西快:结果
1. lsof的-i:445 (只需几秒钟)结果
2. 的netstat -an | grep的445 | grep的LISTEN (只需几秒钟)结果
3. 远程登录(它不返回)结果
4. 的nmap 的netcat 不是在服务器上可用

I have tried a couple of options, but I want something quick:
1. lsof -i :445 (Takes seconds)
2. netstat -an |grep 445 |grep LISTEN (Takes seconds)
3. telnet (it doesn't return)
4. nmap, netcat are not available on the server

这将是很高兴知道的,不一一列举后第一和里grep的方式。

It will be nice to know of a way that doesn't enumerate first and greps after that.

推荐答案

我最近发现了一个令人惊讶的是Bash的原生支持的 TCP连接文件描述符。使用方法:

A surprise I found out recently is that Bash natively supports tcp connections as file descriptors. To use:

exec 6<>/dev/tcp/ip.addr.of.server/445
echo -e "GET / HTTP/1.0\n" >&6
cat <&6

我使用6作为文件描述符,因为0,1,2的标准输入,标准输出,和标准错误。 5有时会被猛砸子进程的,所以3,4,6,7,8和9应该是安全的。

I'm using 6 as the file descriptor because 0,1,2 are stdin, stdout, and stderr. 5 is sometimes used by Bash for child processes, so 3,4,6,7,8, and 9 should be safe.

按下面的评论,来测试监听的本地服务器上的脚本中:

As per the comment below, to test for listening on a local server in a script:

exec 6<>/dev/tcp/127.0.0.1/445 || echo "No one is listening!"
exec 6>&- # close output connection
exec 6<&- # close input connection

要确定是否有人在听,试图通过回环连接。如果失败,则该端口是关闭的,否则我们不会允许访问。此后,关闭连接。

To determine if someone is listening, attempt to connect by loopback. If it fails, then the port is closed or we aren't allowed access. Afterwards, close the connection.

修改此为您的使用情况下,如发送电子邮件,在失败时退出脚本,或启动所需的服务。

Modify this for your use case, such as sending an email, exiting the script on failure, or starting the required service.

这篇关于找到快捷方式,如果一个端口是开放的Linux的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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