Python利用tkinter和socket實現端口掃描
題目
請設計並實現一款主機端口掃描程序。程序根據用戶輸入的域名或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端口掃描內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- python tkinter Entry控件的焦點移動操作
- Python GUI編程詳解
- Python Tkinter對話框控件使用詳解
- Python基礎之tkinter圖形化界面學習
- Python GUI之如何使用tkinter控件