I made a port scanner today and the GUI is very unpolished for now, but when testing it I noticed that when pressing "Scan ports" it does nothing.
I cant find anything obvious in my code. What did I miss?
import socket
import PySimpleGUI as sg
def scan_ports(target_ip, start_port, end_port):
print(f"Scanning ports on {target_ip}...")
for port in range(start_port, end_port + 1):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(1)
result = sock.connect_ex((target_ip, port))
if result == 0:
print(f"Port {port} is open")
sock.close()
except KeyboardInterrupt:
print("Scan interrupted by user.")
break
except socket.error:
print("Couldn't connect to server.")
break
def port_scan_window():
layoutport = [
[sg.Text(" IP: Starting port: Ending port:")],
[sg.Button("Scan ports", key="-SCAN-"), sg.Input(key="-PORTIP-"), sg.Input(key="-START-"), sg.Input(key="-END-")],
[sg.Output(size=(30,20))],
[sg.Button("Exit")]
]
port_window = sg.Window('Port scanner', layoutport)
while True:
event, values = port_window.Read()
if event in (None, "Scan ports"):
print("Scanning " + values["-PORTIP-"] + " for Open ports")
scan_ports(target_ip=values["-PORTIP-"], start_port=values["-START-"], end_port=values["-END-"])
elif event in (None, "Exit"):
break
port_window.Close()
port_scan_window()
The event
is -SCAN-
as you defined it in sg.Button("Scan ports", key="-SCAN-")
.
So this should work:
if event in (None, "-SCAN-"):
The event would have been Scan ports
if you hadn't used key
:
sg.Button("Scan ports")
or if you had set key
to 'Scan ports'
:
sg.Button("Scan ports", key='Scan ports')
In addition, the event
is None
when you close the window. So you are calling scan_ports
when the X
button is pressed.
You might want to use:
if event == "-SCAN-":
or
if event == "Scan ports":
instead.