无需安装工具,一行shell命令测试远程主机端口连通性

发布时间 2023-03-22 21:16:07作者: chyuhung

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.