无需安装工具,一行shell命令测试远程主机端口连通性
for ip in 10.191.2.1 10.191.2.2; do for port in 22 80 443; do timeout 1 bash -c "echo >/dev/tcp/$ip/$port" && echo "$ip:$port:on" || echo "$ip:$port:off"; done; done
This code is a shell script that loops through two IP addresses and three ports for each IP address to check if the ports are open or closed. Here's how it works:
1.The outer loop uses a for statement to loop through two IP addresses: 10.191.2.1 and 10.191.2.2.
2.The inner loop also uses a for statement to loop through three port numbers: 22, 80, and 443.
3.Inside the inner loop, the timeout command is used to limit the amount of time the echo command can run for each port. The echo command is redirected to the /dev/tcp device file, which is a virtual file that allows you to connect to a remote host using TCP/IP.
4.If the connection is successful (i.e., the port is open), the script will output the IP address and port number followed by ":on". Otherwise, it will output the IP address and port number followed by ":off".
5.The entire process is repeated for each IP address and port combination.
Overall, this script is a simple way to check if certain ports are open on a remote host. It can be useful for troubleshooting network connectivity issues or checking the security of a network.
In addition, /dev/tcp is a virtual device file system available in Unix-based operating systems that allows you to access network sockets using standard file I/O operations.
In particular, /dev/tcp/host/port is a special path that can be used to connect to a TCP server running on the specified host and port. When you open this file using the cat command or any other utility that works with files, the operating system transparently establishes a TCP connection to the specified host and port, and allows you to read and write data to it as if it were a local file.
For example, the command cat < /dev/tcp/www.example.com/80 will connect to the web server running on port 80 of the www.example.com host and display the raw HTTP response on the terminal. This can be useful for debugging network issues or quickly testing if a remote service is reachable.
Note that /dev/tcp is not a real file system, but rather a set of special files that the operating system provides as a convenience to users and developers.
本文来自博客园,作者:chyuhung,转载请注明原文链接:https://www.cnblogs.com/chyuhung/p/17244328.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现