[Xia Chong Yu Bing] Test whether the server port is open (command line, Python)

1 Introduction

Interface testing is mainly used for interaction points between external systems and between internal subsystems. It defines specific interaction points, and then uses these interaction points to conduct data exchanges through some special rules, that is, protocols. Interaction.

Why can a server be a Web server, an FTP server, or a mail server at the same time? One of the important reasons is that various services use different ports to provide different services, such as: usually TCP/IP protocol It is stipulated that Web uses port 80, FTP uses port 21, etc., and the mail server uses port 25. In this way, through different ports, the computer can communicate with the outside world without interfering with each other.

Insert image description here

2. Command line

2.1 telnet

2.1.1 Tool introduction

The Telnet protocol is a member of the TCP/IP protocol suite and is the standard protocol and main method for Internet remote login services. It provides users with the ability to complete remote host work on their local computer. Telnet is based on the tcp/ip protocol, so it can only be used to detect whether the tcp port is open.
Insert image description here
Insert image description here

2.1.2 Tool configuration

telnet ip port

In the past, when testing the opening of a certain port on the server, we usually used the netstat –ano|findstr “port number” command on the server to view it.
But sometimes the port is opened on the server, but the client may not be able to access it. So how to verify on the client whether the machine can normally access the server port? You can use the telnet command to view it.
Enter the command to check whether telnet is configured.

telnet

Insert image description here
It was found that the telnet command was not found. If it prompts "Not an internal or external command", you need to enable telnet in "Programs and Features".
Need to configure it. Select "Programs and Features" in the Control Panel, and select "Turn Windows features on or off" on the "Programs and Features" interface. In the pop-up "Windows Functions" window, check the Telnet server and Telnet client and save the settings. After the setting is completed, you need to reopen a command line window to run the telnet command. Running telnet in the command window opened before setting is invalid. The specific steps are as follows:
Insert image description here
Control Panel - Programs - Start or turn off Windows functions - Check Telnet client.
Insert image description here
Insert image description here

2.1.3 Tool usage

Then test the telnet command again.

telnet

Insert image description here
The configuration is successful.
Let's try testing a non-existent port again.

telnet 127.0.0.1 80

Insert image description here
The prompt reported an error.
Let’s try testing Baidu again.

telnet www.baidu.com 80

Insert image description here
Enter "telnet IP address or domain name port number" in the CMD command box. If a black form pops up, it means the connection is successful.
Then proceed as follows:

ctrl+]
st

Insert image description here

2.2 curl

2.2.1 Tool introduction

curl is a commonly used command line tool used to request web servers. Its name means client's URL tool.

curl is very powerful, with dozens of command line parameters. If you are proficient, you can completely replace graphical interface tools such as Postman.

curl supports DICT, FILE, FTP, FTPS, GOPHER, GOPHERS, HTTP, HTTPS, IMAP, IMAPS, LDAP, LDAPS, MQTT, POP3, POP3S, RTMP, RTMPS, RTSP, SCP, SFTP, SMB, SMBS, SMTP, SMTPS, TELNET, TFTP, WS and WSS. curl supports TLS certificates, HTTP POST, HTTP PUT, FTP uploads, HTTP form-based uploads, proxies (SOCKS4, SOCKS5, HTTP and HTTPS), HTTP/2, HTTP/3, cookies, user+password authentication (Basic, Plain , Digest, CRAM-MD5, SCRAM-SHA, NTLM, Negotiate, Kerberos, Bearer tokens and AWS Sigv4), file transfer recovery, proxy tunneling, HSTS, Alt-Svc, unix domain sockets, HTTP compression (gzip, brotli and zstd), etags, parallel transfers, DNS over HTTPS, etc.

2.2.1 Tool download

2.2.1 Tool usage

curl ip:port

Let’s try testing Baidu again.

curl www.baidu.com

Insert image description here

curl 127.0.0.1
# or
curl 127.0.0.1:5000

Insert image description here

2.3 wget

2.3.1 Tool introduction

The command-line utility uses HTTP, HTTPS, and FTP protocols to retrieve files.
Wget is a powerful and convenient command-line download tool that can retrieve and obtain files from the Internet through HTTP and FTP protocols (the two most widespread Internet protocols).

2.3.2 Tool download

https://eternallybored.org/misc/wget/
Insert image description here

2.3.2 Tool usage

wget ip:port
# or
wget localhost:5000

Insert image description here

2.4 nc

2.4.1 Tool introduction

The nc command is a powerful network tool. nc is the abbreviation of netcat, which is known as the Swiss Army Knife of the Internet industry. Because it is short, concise and practical, it is designed to be a simple and reliable network tool.
For example, everyone is familiar with using telnet to test tcp ports, and nc can support testing linux tcp and udp ports, and is often used for port scanning. It is even possible to use nc as a server to listen to specified ports in TCP or UDP mode for simple simulation tests. .

nc(netcat) is a simple Unix tool that uses TCP or UDP protocols to read and write data between network connections.

2.4.2 Tool installation

Tool installation command:

yum install nc -y

2.4.3 Tool usage

# nc -z -v -n 127.0.0.1 6379
# nc -z -v -n 172.17.26.137 6379
# nc -z ip port 或 nc -v -w 1 ip -z port
# nc –uz IP port(u代表UDP)

nc -v -w 1  ip -z port
# or
nc -v -w 1  localhost -z 80

Insert image description here

2.5 ssh

2.5.1 Tool introduction

SSH (Secure Shell) is a network security protocol that implements secure access and file transfer services through encryption and authentication mechanisms.
Insert image description here

  • The difference between SSH and other transfer protocols
    • Traditional remote login and file transfer methods, such as Telnet and FTP, use plain text to transmit data, which has many security risks. As people pay more attention to network security, these methods have gradually become less accepted.

    • The SSH protocol provides secure network services in an insecure network environment by encrypting and verifying network data. As a secure alternative to Telnet and other insecure remote shell protocols, the SSH protocol has been widely used around the world, and most devices support the SSH function.
      Insert image description here

  • The difference between SSH and SSL
    • SSH and SSL are both network security protocols that improve the security of data transmitted between two devices through encryption and authentication. However, there are differences in the effectiveness methods and service goals of SSH and SSL.
    • SSH creates a secure tunnel between two devices so that commands and data can be sent securely between the two devices. For example, if the client logs in to a server remotely through SSH, it can safely remotely manage the server and execute the desired commands on the server.
    • SSL uses an SSL certificate to ensure the secure transmission of data between two devices, rather than executing commands like SSH. For example, if a user accesses a server with an SSL certificate installed and HTTPS enabled through a browser, data can be transmitted securely between the browser and the server.
    • SSH is like a car, we can't see what's inside this closed car. SSL is like a closed container. We can transport it by different means of transportation, but we cannot see what is in the container.

SSH is a very commonly used tool on Linux systems. Through SSH Client we can connect to a remote machine running SSH Server. The basic usage of SSH Client is:

ssh -v -p port username@ip
# or
ssh user@remote -p port

user is your user name on the remote machine. If not specified, it defaults to the current user.
remote is the address of the remote machine, which can be IP, domain name, or an alias mentioned later.
port is the port that the SSH Server monitors. If not If specified, the default value is 22

  • windows
    Insert image description here
  • linux
    Insert image description here

2.5.2 Tool usage

ssh -v -p port username@ip

2.6 nmap

2.6.1 Tool introduction

nmap ("Network Mapper") is an open source tool for network exploration and security auditing. It is designed to quickly scan large-scale networks, although it will work equally well on a single host.

The nmap scanner has three main basic functions. First, it detects whether a group of hosts is online. Second, it scans host ports, sniffs the network services provided, and can also infer the operating system used by the host. You can also deeply detect UDP or TCP ports, down to the operating system used by the host; you can also record all detection results into logs in various formats for further analysis and operations.

2.6.2 Tool installation

yum install nmap -y
#or
sudo apt install nmap

Insert image description here

2.6.2 Tool usage

nmap 127.0.0.1 -p 80

Insert image description here
Port detection successful! ! !

nmap 127.0.0.1 -p 8080

Insert image description here
Failed to detect port! ! !

查看当前开放的端口:nmap localhost;
查看主机端口(1024-65535)中开放的端口:nmap -p 1024-65535 localhost;
探测目标主机开放的端口:nmap -PS ip 地址;
探测所列出的目标主机端口:nmap -p22,80,3306 ip 地址;
探测目标主机操作系统类型、端口服务名称、版本信息:nmap -sV -O localhost。
  • Scan All TCP Ports with Range
    We can specify the port range using the -p option. We know that the TCP port number is between 65535 and 65535. We will use -p0-65535 as option to scan all TCP ports. We did not specify the TCP protocol because the default protocol for Nmap port scanning is TCP.
nmap -p0-65535 192.168.122.1
  • Faster Scan For All Ports
    If we want to scan all ports, it will take a lot of time. If the situation is not very urgent, we can use a faster scan with the -T5 parameter. This is Nmap's fastest scan level. This option is also available for UDP scanning.
nmap  -p0-65535 192.168.122.1 -T5

3、Python

3.1 sock.connect_ex

Use connect_ex of the socket module to determine whether the port is open

import socket

def check_port(ip, port):  
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  
    sock.settimeout(5)  
  
    try:  
        result = sock.connect_ex((ip, port))  
        if result == 0:  
            return True
        else:  
            return False
    except Exception as e:  
        print(f"错误: {
      
      str(e)}")  
    finally:  
        sock.close()

if __name__ == '__main__':      
    host = 'localhost'
    port = 8000
    if check_port(host, port):
        print(f'The port {
      
      port} on {
      
      host} is open.')
    else:
        print(f'The port {
      
      port} on {
      
      host} is closed.')

The execution results are as follows:
Insert image description here

3.2 sock.connect

import socket

def check_port(host, port):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(1)
        sock.connect((host, port))
        sock.close()
        return True
    except:
        return False
    finally:  
        sock.close()

if __name__ == '__main__':
    ret = check_port('127.0.0.1', 80)
    print("80: ", ret)
    ret = check_port('127.0.0.1', 8000)
    print("8000: ", ret)

Insert image description here

3.3 telnet command

telnet <IP地址> <端口>
import os  
  
def check_port(ip, port):  
    result = os.system(f"telnet {
      
      ip} {
      
      port}")   #windows
    # result = os.system(f"telnet {ip} {port} > /dev/null 2>&1")  #linux
    if result == 0:  
        print(f"端口 {
      
      port} 是开放的")  
    else:  
        print(f"端口 {
      
      port} 是关闭的")

if __name__ == '__main__':
    ret = check_port('127.0.0.1', 80)
    print("80: ", ret)

    # ret = check_port('127.0.0.1', 8000)
    # print("8000: ", ret)

Insert image description here

3.4 nc command

nc -zv <IP地址> <端口>
import os  
  
def check_port(ip, port):  
    result = os.system(f"nc -zv {
      
      ip} {
      
      port} > /dev/null 2>&1") 
    if result == 0:  
        print(f"端口 {
      
      port} 是开放的")  
    else:  
        print(f"端口 {
      
      port} 是关闭的")

if __name__ == '__main__':
    # ret = check_port('127.0.0.1', 80)
    # print("80: ", ret)

    ret = check_port('127.0.0.1', 8000)
    print("8000: ", ret)

3.5 ping command

ping <IP地址> -n <端口>
import os  
  
def check_port(ip, port):  
    # result = os.system(f"ping {ip} -n {port} > /dev/null 2>&1")  
    result = os.system(f"ping {
      
      ip} -n {
      
      port} ")  
    if result == 0:  
        print(f"端口 {
      
      port} 是开放的")  
    else:  
        print(f"端口 {
      
      port} 是关闭的")

if __name__ == '__main__':
    # ret = check_port('127.0.0.1', 80)
    # print("80: ", ret)

    ret = check_port('127.0.0.1', 8000)
    print("8000: ", ret)

Insert image description here

3.6 requests check http port

import requests  
  
def check_port(ip, port):  
    try:  
        response = requests.get(f"http://{
      
      ip}:{
      
      port}")  
        if response.status_code == 200:  
            print(f"端口 {
      
      port} 是开放的")  
        else:  
            print(f"端口 {
      
      port} 是关闭的")  
    except requests.exceptions.ConnectionError:  
        print(f"端口 {
      
      port} 是关闭的")
        
if __name__ == '__main__':
    # ret = check_port('127.0.0.1', 80)
    # print("80: ", ret)

    ret = check_port('127.0.0.1', 8000)
    print("8000: ", ret)

Insert image description here

3.7 Scapy library

Scapy is a powerful tool written in Python. Currently, many excellent network scanning attack tools use this module. You can also use this module in your own program to send, monitor and parse network data packets. This module is lower level than Nmap. You can more intuitively understand various scanning attack behaviors in the network.

Scapy is a Python program that allows users to send, sniff, analyze and forge network packets. This capability allows for the construction of tools capable of probing, scanning, or attacking networks.

Scapy is a powerful interactive package manipulation program. It is able to forge or decode packets for a large number of protocols, send them over the network, capture them, match requests and responses, and more. Scapy can easily handle most classic tasks such as scanning, tracing, probing, unit testing, attacks or network discovery. It can replace hping, arpsoof, arp-sk, arping, p0f and even parts of Nmap, tcpdump and tshark.

  • Install the Scapy library
pip install scapy

Insert image description here

  • code testing
from scapy.all import *  
  
def check_port(ip, port):  
    # 构造一个ICMP数据包,并发送到目标IP地址和端口  
    packet = IP(dst=ip) / ICMP() / Raw(load=str(port))  
    # 发送数据包并获取响应  
    response = sr1(packet, timeout=1)  
    # 检查响应是否为ICMP错误类型  
    if response is None or response.type != ICMP.DEST_UNREACH:  
        print(f"端口 {
      
      port} 是开放的")  
    else:  
        print(f"端口 {
      
      port} 是关闭的")

if __name__ == '__main__':
    # ret = check_port('127.0.0.1', 80)
    # print("80: ", ret)

    ret = check_port('127.0.0.1', 8000)
    print("8000: ", ret)

Insert image description here
An error occurred when running, hahahahahaha, waiting for the enthusiastic friends to tell me the solution.

Conclusion

如果您觉得该方法或代码有一点点用处,可以给作者点个赞,或打赏杯咖啡;╮( ̄▽ ̄)╭
如果您感觉方法或代码不咋地//(ㄒoㄒ)// ,就在评论处留言,作者继续改进;o_O???
如果您需要相关功能的代码定制化开发,可以留言私信作者;(✿◡‿◡)
感谢各位大佬童鞋们的支持!( ´ ▽´ )ノ ( ´ ▽´)! ! !

Guess you like

Origin blog.csdn.net/hhy321/article/details/133420436