亲宝软件园·资讯

展开

Python利用tkinter和socket实现端口扫描

所谓独醉 人气:0

题目

请设计并实现一款主机端口扫描程序。程序根据用户输入的域名或IP地址,可以查询该主机的开放的端口号。 例如:

并有一定的异常处理

参考code

import tkinter
from tkinter import *
import socket
import tkinter.messagebox


class CheckPort:
    def __init__(self):
        window = Tk()
        window.title("端口扫描")
        window.geometry("600x500")
        frame1 = Frame(window)
        frame1.pack()
        Label(frame1, text="IP地址、域名:", bg="#f0f0f0").grid(row=0, column=1, pady=3)
        Label(frame1, text="起始端口(最小为1):", bg="#f0f0f0").grid(row=1, column=1, pady=3)
        Label(frame1, text="结束端口(最大为65535):", bg="#f0f0f0").grid(row=2, column=1, pady=3)
        self.searchText = StringVar()
        Entry(frame1, textvariable=self.searchText, justify=LEFT).grid(row=0, column=2)
        self.originPort = IntVar()
        Entry(frame1, textvariable=self.originPort, justify=LEFT).grid(row=1, column=2)
        self.endPort = IntVar()
        Entry(frame1, textvariable=self.endPort, justify=LEFT).grid(row=2, column=2)
        Button(frame1, text="扫描", command=self.getRes).grid(row=3, column=1, columnspan=2, pady=3)
        frame2 = Frame(window).pack()
        self.resText = Text(frame2, height=50, width=500, wrap=WORD)
        self.resText.pack()

        window.mainloop()

    def getRes(self):
        try:
            ip = socket.gethostbyname(self.searchText.get())
            str1 = ""
            if 1 <= self.originPort.get() <= self.endPort.get() <= 65535:
                for port in range(self.originPort.get(), self.endPort.get() + 1):
                    try:
                        socket.setdefaulttimeout(1)
                        client = socket.socket()
                        client.connect((ip, port))
                        client.shutdown(1)
                        str1 += f"{ip}:{port}已开放\n"
                    except Exception as e:
                        str1 += f"{ip}:{port}未开放\n"
                        pass
                str1 += f"扫描完成\n"
                self.resText.insert(END, str1)
            else:
                self.errorHandle("请输入正确的端口号!")

        except:
            self.errorHandle("请输入正确的域名或者ip地址!")

    def errorHandle(self, message):
        tkinter.messagebox.showerror(title="error", message=message)


CheckPort()

加载全部内容

相关教程
猜你喜欢
用户评论