Python检查udp端口是否打开

时间:2017-03-17 21:13:19

标签: python udp

如果远程DNS服务器正在侦听端口53 UDP,我正在尝试使用Python 3.6进行检查。

这就是我的尝试:

def check_port(host, port):
    import socket
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.settimeout(1)
    try:
        result = s.connect_ex((host, port))
    except socket.gaierror:
        s.close()
        return 1
    s.close()
    return result  # 0 == Port is open

但即使端口接近,我也会一直得到0。 使用SOCK_STREAM尝试使用TCP就像魅力一样。

我也尝试过:

def check_port_udp(host, port):
    import socket
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.settimeout(1)
    try:
        s.sendto('ping'.encode(), (host, port))
        s.recvfrom(1024)
    except socket.timeout:
        s.close()
        print(1)
        return 1
    s.close()
    print(0)
    return 0  # 0 == Port is open

但即使打开了端口

,我也会获得1分

3 个答案:

答案 0 :(得分:2)

基本思路:向该端口发送DNS查询。如果有响应,则说明该端口已打开。

import random
import socket
import struct


class SendDNSPkt:
    def __init__(self,url,serverIP,port=53):
        self.url=url
        self.serverIP = serverIP
        self.port=port
    def sendPkt(self):
        pkt=self._build_packet()
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.settimeout(1)
        sock.sendto(bytes(pkt), (self.serverIP, self.port))
        data, addr = sock.recvfrom(1024)
        sock.close()
        return data

    def _build_packet(self):
        randint = random.randint(0, 65535)
        packet = struct.pack(">H", randint)  # Query Ids (Just 1 for now)
        packet += struct.pack(">H", 0x0100)  # Flags
        packet += struct.pack(">H", 1)  # Questions
        packet += struct.pack(">H", 0)  # Answers
        packet += struct.pack(">H", 0)  # Authorities
        packet += struct.pack(">H", 0)  # Additional
        split_url = self.url.split(".")
        for part in split_url:
            packet += struct.pack("B", len(part))
            for s in part:
                packet += struct.pack('c',s.encode())
        packet += struct.pack("B", 0)  # End of String
        packet += struct.pack(">H", 1)  # Query Type
        packet += struct.pack(">H", 1)  # Query Class
        return packet

def checkDNSPortOpen():
    # replace 8.8.8.8 with your server IP!
    s = SendDNSPkt('www.google.com', '8.8.8.8')
    portOpen = False
    for _ in range(5): # udp is unreliable.Packet loss may occur
        try:
            s.sendPkt()
            portOpen = True
            break
        except socket.timeout:
            pass
    if portOpen:
        print('port open!')
    else:
        print('port closed!')

if __name__ == '__main__':
    checkDNSPortOpen()

受此post

的启发

答案 1 :(得分:1)

以下代码可以帮助您扫描端口53 / udp:

from socket import *
import sys, time
from datetime import datetime

host = ''
ports = [53]

def scan_host(host, port, r_code = 1) : 
    try : 
        s = socket(AF_INET, SOCK_DGRAM)
        code = s.connect_ex((host, port))
        if code == 0 : 
            r_code = code
        s.close()
    except Exception, e : 
        pass
    return r_code

try : 
    host = raw_input("[*] Enter Target Host Address :  ")
except KeyBoardInterrupt : 
    sys.exit(1)

hostip = gethostbyname(host)

for port in ports : 
    try : 
        response = scan_host(host, port)
        if response == 0 : 
            print("[*] Port %d: Open" % (port))
    except Exception, e : 
        pass

您可以参考this example进一步了解端口扫描。

答案 2 :(得分:1)

为此目的我没有运气使用套接字。端口响应基于target application,并不像TCP那样标准。我总是使用netcat:

import os
ip = "127.0.0.1"
port = "<some_udp_port>"
''' send to /dev/null 2>&1 to suppress terminal output '''
res = os.system("nc -vnzu "+ip+" "+port+" > /dev/null 2>&1")
if res == 0:
    print("port alive")
else:
    print("port dead")

显然,这需要在Linux系统上运行。但是,如果您在Windows系统上安装了nmap,则可以尝试以下操作:

import os
ip = "127.0.0.1"
port = "<some_udp_port>"
res = os.system("ncat -vnzu "+ip+" "+port)
if res == 0:
    print("port alive")
else:
    print("port dead")