首頁 > 軟體

Python利用tkinter和socket實現埠掃描

2022-12-05 14:00:57

題目

請設計並實現一款主機埠掃描程式。程式根據使用者輸入的域名或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()

到此這篇關於Python利用tkinter和socket實現埠掃描的文章就介紹到這了,更多相關Python埠掃描內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com