Compare commits

...
Author SHA1 Message Date
Deniz Şafak 6a854b2581 Improvements, bug fixes 2023-10-17 02:50:08 +03:00
Deniz Şafak 7c9ccb39e5 Update README.md 2023-10-15 02:30:10 +03:00
Deniz Şafak bd0ab39771 Fixed minor bugs 2023-10-15 02:14:06 +03:00
Deniz Şafak 2b64fd69bb Update HotspotAutoLogin.pyw 2023-10-14 04:10:02 +03:00
Deniz Şafak c08620677f Update README.md 2023-10-14 04:04:44 +03:00
Deniz Şafak ffdfe53dfd Update HotspotAutoLogin.pyw
Added functionality for Ethernet networks.
2023-10-14 03:55:50 +03:00
Deniz Şafak 638233a901 Delete examples/Log.png 2023-10-13 14:55:50 +03:00
Deniz Şafak 15a646b833 Update README.md 2023-10-13 14:55:36 +03:00
Deniz Şafak d710811ec0 Add files via upload 2023-10-13 14:55:24 +03:00
Deniz Şafak e3f8c59baf Add files via upload 2023-10-13 14:54:00 +03:00
Deniz Şafak f0477fa63e Delete examples/Log.png 2023-10-13 14:53:41 +03:00
Deniz Şafak ab2f468230 Update HotspotAutoLogin.pyw
Fixed the issue of not being able to access the login URL even though network is connected.
2023-10-13 14:48:49 +03:00
Deniz Şafak 61dedb8592 Update README.md 2023-10-12 02:27:11 +03:00
Deniz Şafak 9c70bf1480 Update README.md 2023-10-12 01:32:15 +03:00
Deniz Şafak 40fda390bb Update README.md 2023-10-12 01:30:18 +03:00
Deniz Şafak f22d91d733 Update README.md 2023-10-12 01:29:57 +03:00
Deniz Şafak 89fd7ee615 Update README.md 2023-10-12 01:28:41 +03:00
Deniz Şafak f17a881e86 Update README.md 2023-10-12 01:27:20 +03:00
Deniz Şafak 3ff98344a1 Update README.md 2023-10-12 01:26:07 +03:00
4 changed files with 158 additions and 96 deletions
+143 -84
View File
@@ -1,62 +1,89 @@
import logging, sys, traceback
# Log all errors to a log.txt file
def log_exception(exctype, value, tb):
logging.exception("Uncaught exception: {0}".format(str(value)))
logging.exception("Traceback: {0}".format(''.join(traceback.format_tb(tb))))
logging.shutdown()
sys.exit(1)
sys.excepthook = log_exception
# Log all messages except DEBUG to a log.txt file
logging.basicConfig(filename='log.txt', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
import json
import os
import requests
import time
import subprocess
import pystray
from PIL import Image
import threading
import tkinter as tk
from PIL import Image
from collections import deque
from datetime import datetime
import os
from urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS += 'HIGH:!DH:!aNULL'
try:
requests.packages.urllib3.contrib.pyopenssl.DEFAULT_SSL_CIPHER_LIST += 'HIGH:!DH:!aNULL'
except AttributeError:
# no pyopenssl support used / needed / available
pass
# Load configuration from file
with open("config.json", "r") as f:
config = json.load(f)
# Your authentication payload and URL
# Your payload
payload = config["payload"]
url = config["url"]
# Convert the expected SSID to lowercase (or uppercase)
expected_ssid = config["ssid"].lower()
if (config["ssid"]):
expected_ssid = config["ssid"]
expected_ssid_lower = config["ssid"].lower()
else:
config["ssid"] = "Wi-Fi"
expected_ssid = config["ssid"]
expected_ssid_lower = None
def is_internet_available():
try:
# Try to send a simple HTTP GET request to a known website
response = requests.get("https://www.google.com")
response = requests.get("https://www.google.com", timeout=10)
# If the request was successful, it means the internet is available
return response.status_code == 200
except requests.ConnectionError:
# If an exception is raised, there's no internet connectivity
return True
except (requests.ConnectionError, requests.RequestException):
return False
# Function to get the currently connected WiFi SSID using system commands (for Windows)
def get_connected_wifi_ssid():
# Function to get the currently connected SSID using system commands (for Windows)
def get_connected_network():
try:
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
output = subprocess.check_output(["netsh", "wlan", "show", "interfaces"], startupinfo=startupinfo).decode("utf-8")
lines = output.split("\n")
for line in lines:
# Get Wi-Fi SSID
wifi_output = subprocess.check_output(["netsh", "wlan", "show", "interfaces"], startupinfo=startupinfo).decode("utf-8")
wifi_lines = wifi_output.split("\n")
wifi_ssid = None
for line in wifi_lines:
if "SSID" in line:
ssid = line.strip().split(": ")[1]
return ssid
return None
wifi_ssid = line.strip().split(": ")[1]
break
if wifi_ssid is not None:
return wifi_ssid
elif wifi_ssid is None:
# Check if connected to Ethernet
ethernet_output = subprocess.check_output(["netsh", "interface", "show", "interface"], startupinfo=startupinfo).decode("utf-8")
ethernet_lines = ethernet_output.split("\n")
for line in ethernet_lines:
if "Connected" in line:
if "Ethernet" in line:
return "Ethernet"
else:
return False
except subprocess.CalledProcessError:
return None
return False
headers = {
"Content-Type": "application/json"
"Content-Type": "application/json;charset=UTF-8",
"Connection": "keep-alive",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
}
# Function to add a message to the log file (txt)
@@ -64,22 +91,12 @@ def save_to_file(message):
# Get the current date and time
now = datetime.now()
timestamp = now.strftime("%Y-%m-%d %H:%M:%S")
# Format the message with the timestamp
formatted_message = f"({timestamp}) {message}\n"
# Open the file in append mode and write the formatted message
with open("log.txt", "a") as f:
f.write(formatted_message)
# Flag to control the main loop
running = True
# Function to gracefully exit the application
def exit_application(icon, item):
icon.stop()
os._exit(0)
# Queue to store log messages
log_messages = deque(maxlen=20)
log_dialog = None
@@ -113,87 +130,112 @@ def get_last_log_messages():
return list(log_messages)
# Function to show the log dialog
def show_log_dialog(icon, item):
global log_dialog, log_text
if log_dialog:
log_dialog.deiconify()
update_log()
log_dialog_open = False
def show_log_dialog():
global log_dialog, log_text, log_dialog_open
if log_dialog_open == False:
log_dialog_open = True
if log_dialog:
log_dialog.deiconify()
update_log()
else:
log_dialog = tk.Tk()
log_dialog.title("Log Messages")
log_text = tk.Text(log_dialog)
log_dialog.geometry("1024x500")
log_frame = tk.Frame(log_dialog)
log_frame.pack(fill=tk.BOTH, expand=True)
log_text = tk.Text(log_frame, wrap=tk.WORD)
log_text.pack(fill=tk.BOTH, expand=True)
update_log()
log_dialog.protocol("WM_DELETE_WINDOW", hide_log_dialog)
log_dialog.mainloop()
else:
log_dialog = tk.Tk()
log_dialog.title("Log Messages")
log_text = tk.Text(log_dialog)
log_dialog.geometry("1024x500")
log_frame = tk.Frame(log_dialog)
log_frame.pack(fill=tk.BOTH, expand=True)
log_text = tk.Text(log_frame, wrap=tk.WORD)
log_text.pack(fill=tk.BOTH, expand=True)
update_log()
log_dialog.protocol("WM_DELETE_WINDOW", hide_log_dialog)
log_dialog.mainloop()
hide_log_dialog()
# Function to hide the log dialog
def hide_log_dialog():
global log_dialog
global log_dialog, log_dialog_open
log_dialog_open = False
if log_dialog:
log_dialog.withdraw()
log_dialog = None
# Create the system tray icon
def create_system_tray_icon():
image = Image.open("icon.png")
menu = pystray.Menu(
pystray.MenuItem('Show Log', show_log_dialog),
pystray.MenuItem('Show Log', show_log_dialog, default=True),
pystray.MenuItem('Exit', exit_application)
)
icon = pystray.Icon("my_icon", image, "WIFI Autologin", menu)
icon = pystray.Icon("my_icon", image, "HotspotAutoLogin", menu)
icon.run()
# Function to check network status
running = True
errorcount = 0
sleepcount = config["check_every_second"]
connected_ssid_lower = None
def check_network_status():
errorcount = 0
sleepcount = config["check_every_second"]
global running, errorcount, sleepcount, connected_ssid_lower
while running and errorcount < 10:
connected_ssid = get_connected_wifi_ssid()
if connected_ssid and connected_ssid.lower() == expected_ssid:
if is_internet_available():
errorcount = 0
connected_ssid = get_connected_network()
if (connected_ssid):
connected_ssid_lower = connected_ssid.lower()
if (connected_ssid) and ((connected_ssid_lower == expected_ssid_lower) or (connected_ssid == "Ethernet")):
if (is_internet_available()):
sleepcount = config["check_every_second"]
message = "Connected to "+config["ssid"]+" and internet connection is available. Checking again in "+str(sleepcount)+" seconds..."
message = "Connected to {} and internet connection is available. Checking again in {} seconds...".format(connected_ssid, str(sleepcount))
errorcount = 0
add_to_log(message)
else:
message = "Connected to "+config["ssid"]+", but internet connection is down. Running the script..."
sleepcount = 3
time.sleep(sleepcount)
message = "Connected to {} but internet is down. Sending the request in {} seconds...".format(connected_ssid, str(sleepcount))
add_to_log(message)
save_to_file(message)
# Semd the request and ignore SSL errors
# Send the request and handle potential errors
try:
response = requests.post(url, data=json.dumps(payload), headers=headers, verify=False)
# Update SSL cipher list
try:
requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS += 'HIGH:!DH:!aNULL'
except AttributeError as e:
# no pyopenssl support used / needed / available
add_to_log("Error when adding to DEFAULT_CIPHERS: {}".format(e))
save_to_file("Error when adding to DEFAULT_CIPHERS: {}".format(e))
pass
time.sleep(1)
response = requests.post(url, data=json.dumps(payload), headers=headers, verify=False, timeout=10)
message = "Request sent."
add_to_log(message)
save_to_file(message)
# Check the response status code
if response.ok:
# Success!
errorcount = 0
sleepcount = 10
message = "Request was successful. Connection established! Checking the internet connection in " + str(sleepcount) + " seconds..."
add_to_log(message)
save_to_file(message)
else:
errorcount += 1
sleepcount = 10 # Sleep ... seconds before trying again
message = "Request failed with status code: {}. Trying again in {} seconds... (Errors: {}/10)".format(response.status_code, str(sleepcount), errorcount)
add_to_log(message)
save_to_file(message)
except requests.exceptions.RequestException as e:
# Catch the exception and add a delay before trying again
errorcount += 1
sleepcount = 10
message = "Failed to send request: {e}".format(e=e)+" Trying again in "+str(sleepcount)+" seconds... (Errors: "+str(errorcount)+"/10)"
message = "Failed to send request: {}. Trying again in {} seconds... (Errors: {}/10)".format(e, str(sleepcount), str(errorcount))
add_to_log(message)
save_to_file(message)
time.sleep(sleepcount)
continue
# Check the response status code
if response.status_code == 200:
# Success!
errorcount = 0
sleepcount = config["check_every_second"]
message = "Request was successful. Connection established! Checking again in "+str(sleepcount)+" seconds..."
add_to_log(message)
save_to_file(message)
else:
errorcount += 1
sleepcount = 10 # Sleep ... seconds before trying again
message = "Request failed with status code: {}".format(response.status_code)+" Trying again in "+str(sleepcount)+" seconds... (Errors: "+str(errorcount)+"/10)"
add_to_log(message)
save_to_file(message)
else:
sleepcount = 10 # Sleep ... seconds before trying again
message = "Not connected to "+config["ssid"]+" Checking again in "+str(sleepcount)+" seconds..."
message = "Not connected to target {} or any Ethernet. Checking again in {} seconds...".format(expected_ssid, str(sleepcount))
add_to_log(message)
save_to_file(message)
@@ -203,14 +245,31 @@ def check_network_status():
add_to_log(message)
save_to_file(message)
time.sleep(5)
running = False
os._exit(0)
def open_log_dialog_thread():
log_thread = threading.Thread(target=show_log_dialog)
log_thread.start()
if __name__ == '__main__':
# Create a Tkinter window to run the main loop
root = tk.Tk()
# Create a thread for the system tray icon
tray_thread = threading.Thread(target=create_system_tray_icon)
tray_thread.daemon = True # Set as a daemon thread so it exits when the main program exits
tray_thread.daemon = True
tray_thread.start()
# Open Log Messages at startup
open_log_dialog_thread()
# Start the network status checking in the main thread
check_network_status()
# Start the Tkinter main loop
root.mainloop()
# Wait for all threads to finish
tray_thread.join()
+15 -12
View File
@@ -1,16 +1,17 @@
# HotspotAutoLogin Wi-Fi/Hotspot Autologin Script (Automate WEB Logins)
HotspotAutoLogin is a script that designed to automate the login process for public Wi-Fi or hotspot networks that require web-based authentication. This script is intended for situations where you often connect to networks that require a web login, such as public hotspots in cafes, hotels, or airports. The script continuously monitors your network connection and automatically logs you in when necessary.
# HotspotAutoLogin: Wi-Fi/Hotspot Autologin Script (Automate WEB Logins)
> # [Download the Latest Executable (.exe) Release](../../releases)
![Example Log.](/examples/Logs.png)
HotspotAutoLogin is a script that designed to automate the login process for Wi-Fi or hotspot networks that require web-based authentication. This script is intended for situations where you often connect to networks that require a web login, such as public hotspots in cafes, hotels, or airports. The script continuously monitors your network connection and automatically logs you in when necessary.
> # [Download the Latest Executable (.exe) Release](https://github.com/denizsafak/HotspotAutoLogin/releases/latest)
> You can download the executable (.exe) version of the same script, making it easy to use without the need to install Python or other libraries.
![Example Log.](/examples/Log.png)
## `How It Works`
### Network Monitoring
The script will continuously monitor your network connection. When you connect to the specified SSID but there is no internet access, it will attempt to log in automatically.
### Auto Login
### Autologin
If you are connected to the correct SSID but lack internet access, the script attempts to log in by sending an POST request to the provided URL with the specified credentials. If the login is successful (status code 200), the script will continue monitoring.
### Logging
@@ -23,7 +24,7 @@ The script reads its configuration from a config.json file. This file contains t
> [!IMPORTANT]
> ### Python Requirements
> If you are running it **directly with Python**, you need to install this specific library:
> If you are running it **directly with Python**, you need to install all the libraries that's used in the script and you need to install this specific library:
> ```
> python -m pip install requests "urllib3<2"
> ```
@@ -39,7 +40,7 @@ When you run the script, a system tray icon will appear. Right-click on the icon
You can view the log of the script's actions by clicking the "Show Log" option in the system tray menu.
## `How to Configure the config.json?`
`"payload":` You need to find your own payload values. These are the values that your browser sends when you try to login with your credentials. For example username, phone number, password... To find that:
`"payload":` You need to find your own payload values. These are the values that your browser sends when you try to login with your credentials. For example username, phone number, password, etc. To find that:
- When you're in the login page, open your browser's Developer Tools, press F12 or Ctrl + Shift + I (or Cmd + Option + I on Mac) to open the Developer Tools. Alternatively, you can right-click anywhere on the page and select "Inspect" or "Inspect Element."
- **Navigate to the Network Tab:** In the Developer Tools, click on the "Network" tab at the top.
- **Trigger the POST Request:** Perform the action that sends the POST request. **(Try to login with incorrect password)**. The network tab will capture all network requests made by the page, including the POST request.
@@ -53,19 +54,21 @@ In the "Payload" tab, you can find your form data or request payload that displa
![Example Request.](/examples/Request.png)
`"ssid":` This is your network's SSID. For example "MyHome_5G"
> [!NOTE]
> **If you are using a wired (ethernet) connection, you don't need to enter ssid. You can leave it blank.**
`"check_every_second":` The frequency of the script for checking your internet connection status. For example "100", it will try to access the internet every 100 seconds.
> ## Example useage:
>
> ![Example config.ini.](/examples/config.png)
![Example Request.](/examples/config.png)
## Dependencies
The script uses various Python libraries, including requests for making POST requests, pystray for creating the system tray icon, and tkinter for the log window. Make sure you have all the required libraries.
## Notes
- The script relies on the assumption that the web portal uses basic authentication. If the portal uses a more complex login mechanism, additional adjustments may be necessary.
- This script is primarily intended for Windows. Adaptations might be needed for other operating systems.
> [!NOTE]
> - The script relies on the assumption that the web portal uses basic authentication. If the portal uses a more complex login mechanism, additional adjustments may be necessary.
> - This script is primarily intended for Windows. Adaptations might be needed for other operating systems.
## Disclaimer
> Use this script responsibly and only on networks where you have the right to access and use the provided services. Unauthorized access to networks is illegal and unethical.
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 85 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB