Compare commits

...
Author SHA1 Message Date
Stone_RedandClaude Opus 5.5 12c5808dd0 Add Check Now button to skip the current wait
- "Check Now" in the tray menu and in the log window ends the current
  wait (the check_every_second interval, the auto mode network wait and
  the session expiry wait), so the connection is checked and the login
  is sent right away if needed.
- Document it in the README.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 21:13:13 +02:00
Stone_RedandClaude Opus 5.5 e9428675e9 Check quickly around the expected session expiry
Many portals log you out a fixed time after login (e.g. every 24 hours).
With check_every_second at 600, it could take up to 10 minutes to notice.

- New optional profile setting "session_hours" (also in the Add new dialog).
- The time of each successful login is saved per profile in
  session_state.json, so it survives restarts.
- While connected, the next check is timed to land 2 minutes before the
  expected expiry, then the connection is checked every 5 seconds until
  10 minutes after it, so the program logs in again within seconds.
- If still connected after that window, the session was renewed some
  other way and the normal interval is used again.
- Ignore runtime files (log.txt, session_state.json) in git.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 21:09:42 +02:00
Stone_RedandClaude Opus 5.5 53bf01733e Add Auto mode (network auto-detection) and Start with Windows
- Auto mode (Auto button or --auto): picks the profile matching the
  connected network instead of forcing one profile's SSID. Wi-Fi is
  matched by SSID; Ethernet profiles by whether their portal is reachable.
  Unknown networks are left alone. config.json is reloaded each check.
- Watches for network changes every 5 seconds while waiting, so switching
  between Ethernet and Wi-Fi is handled right away.
- Auto mode backs off instead of exiting after repeated errors.
- Start with Windows checkbox (HKCU Run key, --auto --background).
- --background flag to start without the log window.
- Resolve the program directory for both script and PyInstaller builds,
  so startup launches find config.json.
- Ignore Hyper-V/WSL vEthernet adapters when detecting Ethernet.
- Fix crash when pressing Enter in the profile list.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-07 19:30:29 +02:00
Deniz Şafak bbbb76d577 add .gitignore 2025-02-03 01:07:19 +03:00
Deniz Şafak 8c7b735cb1 Update README.md 2025-01-04 02:09:33 +01:00
Deniz Şafak 9b6d42aff5 v1.90fix4 2025-01-03 18:28:30 +03:00
Deniz Şafak 337c84e9a4 v1.90fix3 2025-01-01 18:56:54 +03:00
Deniz Şafak bcbad5b8f8 Update README.md 2025-01-01 04:02:31 +03:00
Deniz Şafak f55f09079a v1.90 2025-01-01 04:00:39 +03:00
Deniz Şafak 7ec6601554 v1.90fix2 2025-01-01 03:45:45 +03:00
Deniz Şafak 10c3b7f233 Add files via upload 2025-01-01 03:45:22 +03:00
Deniz Şafak bbc9be3b93 v.190fix 2025-01-01 03:39:27 +03:00
Deniz Şafak 2ff513099f v1.90 2025-01-01 03:11:00 +03:00
Deniz Şafak 54eea0ad63 Update README.md 2024-10-26 01:07:10 +03:00
Deniz Şafak fee77034f4 Update README.md 2024-10-26 01:06:56 +03:00
Deniz Şafak af880b0e92 Update README.md 2024-10-26 00:57:16 +03:00
Deniz Şafak c495415df9 v1.83 2024-10-26 00:48:35 +03:00
Deniz Şafak 10436f0b4f v1.83 2024-10-26 00:19:34 +03:00
Deniz Şafak 95e62523f4 v1.83 2024-10-25 23:52:59 +03:00
Deniz Şafak 05471f19ac v1.83 2024-10-25 23:52:43 +03:00
Deniz Şafak dcf2b5426f v1.83 2024-10-25 23:52:08 +03:00
Deniz Şafak 79f792f0b0 Update README.md 2024-08-23 18:15:18 +03:00
Deniz Şafak 1f0b3d7de1 Add files via upload 2024-07-22 23:11:58 +03:00
Deniz Şafak c7fec03add Update run.bat 2024-07-22 23:11:18 +03:00
8 changed files with 1275 additions and 115 deletions
+27
View File
@@ -0,0 +1,27 @@
# macOS system files
.DS_Store
._*
Thumbs.db
Desktop.ini
# Python artifacts
__pycache__/
**/__pycache__
*.py[cod]
*.so
*.exe
*.zip
*.tar.gz
# Virtual environments
env/
venv/
.env/
.venv/
# VS Code settings
.vscode/
# Runtime files
main/log.txt
main/session_state.json
main/last_known_directory.txt
+28 -6
View File
@@ -13,11 +13,11 @@ HotspotAutoLogin is a script that designed to automate the login process for Wi-
### Option 1: Executable Script ### Option 1: Executable Script
- If you don't want to install Python, you can download the precompiled executable version from the Releases section. - If you don't want to install Python, you can download the precompiled executable version from the Releases section.
[Download the Latest Executable (.exe) Release](https://github.com/denizsafak/HotspotAutoLogin/releases/latest) [Download the Latest Executable (.exe) Release](https://github.com/denizsafak/HotspotAutoLogin/releases/latest)
- Double-click on HotspotAutoLogin.exe to launch the application. The wallpaper information display will appear on your screen. - Double-click on HotspotAutoLogin.exe to launch the application.
### Option 2: Run with Python ### Option 2: Run with Python
- Clone or download the repository to your local machine. - Clone or [download the repository](https://github.com/denizsafak/HotspotAutoLogin/archive/refs/heads/main.zip) to your local machine.
- Install Python to your computer. - Extract from zip.
- Run "run.bat" file. - Run "run.bat" file.
## `Features` ## `Features`
@@ -26,12 +26,24 @@ HotspotAutoLogin is a script that designed to automate the login process for Wi-
- Any important events or actions taken by the script are logged both in a log file (log.txt) and in the log window that can be accessed via the system tray icon. - Any important events or actions taken by the script are logged both in a log file (log.txt) and in the log window that can be accessed via the system tray icon.
- The script reads its configuration from a config.json file. This file contains the necessary information, such as your login credentials, the URL of the authentication portal, the SSID (network name) to which you want to connect, and the frequency of network checks in seconds. - The script reads its configuration from a config.json file. This file contains the necessary information, such as your login credentials, the URL of the authentication portal, the SSID (network name) to which you want to connect, and the frequency of network checks in seconds.
## `Auto Mode & Start with Windows`
- **Auto mode:** Click the **Auto** button in the profile selection window (or run with `--auto`). Instead of using a single profile, the program looks at the network you are actually connected to and picks the matching profile automatically:
- **Wi-Fi:** the profile whose `ssid` matches the connected Wi-Fi (case-insensitive).
- **Ethernet:** profiles without an `ssid` are Ethernet profiles. The one whose login `url` is reachable on the current network is used.
- If the connected network doesn't match any profile, nothing is sent and the program just waits for a known network. It never forces a connection to another network in this mode.
- `config.json` is re-read on every check, so edits apply without restarting.
- **Start with Windows:** Tick **Start with Windows (Auto)** in the profile selection window. The program will then start at sign-in in Auto mode, in the background (tray icon only). Untick it to disable. This uses the current user's `Run` registry key, so no admin rights are needed.
- Command line flags: `--auto` (skip profile selection, use Auto mode) and `--background` (don't open the log window at startup). E.g. `run.bat --auto`.
## `Usage` ## `Usage`
- Edit the config.json file with your specific information, including your login credentials, the portal URL, the SSID of the network you want to connect to, and the check interval in seconds. [Click to learn how to Configure the config.json](#how-to-configure-the-configjson) - Edit the config.json file with your specific information, including your login credentials, the portal URL, the SSID of the network you want to connect to, and the check interval in seconds. [Click to learn how to Configure the config.json](#how-to-configure-the-configjson)
- When you run the script, a system tray icon will appear. Right-click on the icon to access options like showing the log or exiting the application. - When you run the script, a system tray icon will appear. Right-click on the icon to access options like showing the log or exiting the application.
- To check the connection right away instead of waiting for the next check, click **Check Now** in the tray menu or in the log window. If the internet is down, it logs in immediately.
- You can view the log of the script's actions by clicking the "Show Log" option in the system tray menu. - 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?` ## `How to Configure the config.json?`
> [!TIP]
> I recently, added "Add new" button to the program, so you can achieve the same thing without needing to edit the config.json.
![How to Animation.](/examples/howto.gif) ![How to Animation.](/examples/howto.gif)
@@ -46,6 +58,8 @@ HotspotAutoLogin is a script that designed to automate the login process for Wi-
`"url":` Enter the "Request URL" in the "Headers" tab here. `"url":` Enter the "Request URL" in the "Headers" tab here.
`"internet_check_url":` URL to check your internet connection. Program will try to access this address to check if you have internet connection. If 8.8.8.8 is accessible **before** you log into your network, change this.
![Example Request.](/examples/Request.png) ![Example Request.](/examples/Request.png)
@@ -53,6 +67,8 @@ HotspotAutoLogin is a script that designed to automate the login process for Wi-
`"check_every_second":` The frequency of the script for checking your internet connection status. For example "100", it will try to check the internet every 100 seconds. `"check_every_second":` The frequency of the script for checking your internet connection status. For example "100", it will try to check the internet every 100 seconds.
`"session_hours":` *(optional)* If your network logs you out a fixed time after logging in (for example every 24 hours), enter that here, e.g. `24`. The program remembers when it last logged in (in `session_state.json`) and checks the connection every 5 seconds from 2 minutes before the expected expiry until 10 minutes after it, so you are logged back in within seconds instead of waiting for the next `check_every_second` check.
> ## Example useage: > ## Example useage:
> >
@@ -60,9 +76,10 @@ HotspotAutoLogin is a script that designed to automate the login process for Wi-
{ {
"profiles": [ "profiles": [
{ {
"name": "My School Wi-Fi", "name": "Example Wi-Fi",
"ssid": "SCHOOL_WIFI_5G", "ssid": "EXAMPLE_WIFI_5G",
"url": "https://connect.schoolwifi.com/api/portal/dynamic/authenticate", "url": "https://connect.schoolwifi.com/api/portal/dynamic/authenticate",
"internet_check_url": "8.8.8.8",
"payload": { "payload": {
"username": "[email protected]", "username": "[email protected]",
"password": "123455678" "password": "123455678"
@@ -79,9 +96,10 @@ HotspotAutoLogin is a script that designed to automate the login process for Wi-
} }
}, },
{ {
"name": "My School ETHERNET", "name": "Example ETHERNET",
"url": "http://10.3.41.15:8002/index.php?zone=dormnet", "url": "http://10.3.41.15:8002/index.php?zone=dormnet",
"payload": "&auth_user=85795013%40myschool.com&auth_pass=123455678&redirurl=&accept=Login", "payload": "&auth_user=85795013%40myschool.com&auth_pass=123455678&redirurl=&accept=Login",
"internet_check_url": "8.8.8.8",
"headers": { "headers": {
"Content-Type": "application/x-www-form-urlencoded", "Content-Type": "application/x-www-form-urlencoded",
"Connection": "keep-alive", "Connection": "keep-alive",
@@ -97,6 +115,10 @@ HotspotAutoLogin is a script that designed to automate the login process for Wi-
} }
``` ```
> [!CAUTION]
> Recent Windows updates restricts third-party apps from accessing Wi-Fi names unless location services are enabled. To fix this, turn on location services in your settings. For more details, check the article from 04/02/2024 [Changes to API behavior for Wi-Fi access and location](https://learn.microsoft.com/en-us/windows/win32/nativewifi/wi-fi-access-location-changes).
> [!NOTE] > [!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. > - 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. > - This script is primarily intended for Windows. Adaptations might be needed for other operating systems.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

After

Width:  |  Height:  |  Size: 101 KiB

+847 -97
View File
File diff suppressed because it is too large Load Diff
+10 -8
View File
@@ -1,12 +1,13 @@
{ {
"profiles": [ "profiles": [
{ {
"name": "NAME_OF_YOUR_PROFILE (WI-FI EXAMPLE)", "name": "Example Wi-Fi",
"ssid": "SSID_OF_YOUR_WIFI", "ssid": "EXAMPLE_WIFI_5G",
"url": "PAYLOAD_URL_HERE", "url": "https://connect.schoolwifi.com/api/portal/dynamic/authenticate",
"internet_check_url": "8.8.8.8",
"payload": { "payload": {
"username": "PLEASE WRITE YOUR OWN PAYLOAD VALUES HERE. THIS IS AN EXAMPLE", "username": "[email protected]",
"password": "PLEASE WRITE YOUR OWN PAYLOAD VALUES HERE. THIS IS AN EXAMPLE" "password": "123455678"
}, },
"headers": { "headers": {
"Content-Type": "application/json;charset=UTF-8", "Content-Type": "application/json;charset=UTF-8",
@@ -20,9 +21,10 @@
} }
}, },
{ {
"name": "NAME_OF_YOUR_PROFILE (ETHERNET EXAMPLE)", "name": "Example ETHERNET",
"url": "PAYLOAD_URL_HERE", "url": "http://10.3.41.15:8002/index.php?zone=dormnet",
"payload": "&auth_user=XXXX%40gmail.com&auth_pass=xxx&redirurl=&accept=Login", "payload": "&auth_user=85795013%40myschool.com&auth_pass=123455678&redirurl=&accept=Login",
"internet_check_url": "8.8.8.8",
"headers": { "headers": {
"Content-Type": "application/x-www-form-urlencoded", "Content-Type": "application/x-www-form-urlencoded",
"Connection": "keep-alive", "Connection": "keep-alive",
+359
View File
@@ -0,0 +1,359 @@
<!-- : Begin batch script
@echo off
REM PUSHD "%~dp0"
REM author: Badr Elmers 2021-2023
REM description: refrenv = refresh environment. this is a better alternative to the chocolatey refreshenv for cmd
REM version: 1.0
REM https://github.com/badrelmers/RefrEnv
REM https://stackoverflow.com/questions/171588/is-there-a-command-to-refresh-environment-variables-from-the-command-prompt-in-w
REM ___USAGE_____________________________________________________________
REM usage:
REM call refrenv.bat full refresh. refresh all non critical variables*, and refresh the PATH
REM debug:
REM to debug what this script do create this variable in your parent script like that
REM set debugme=yes
REM then the folder containing the files used to set the variables will be open. Then see
REM _NewEnv.cmd this is the file which run inside your script to setup the new variables, you
REM can also revise the intermediate files _NewEnv.cmd_temp_.cmd and _NewEnv.cmd_temp2_.cmd
REM (those two contains all the variables before removing the duplicates and the unwanted variables)
REM you can also put this script in windows\systems32 or another place in your %PATH% then call it from an interactive console by writing refrenv
REM *critical variables: are variables which belong to cmd/windows and should not be refreshed normally like:
REM - windows vars:
REM ALLUSERSPROFILE APPDATA CommonProgramFiles CommonProgramFiles(x86) CommonProgramW6432 COMPUTERNAME ComSpec HOMEDRIVE HOMEPATH LOCALAPPDATA LOGONSERVER NUMBER_OF_PROCESSORS OS PATHEXT PROCESSOR_ARCHITECTURE PROCESSOR_ARCHITEW6432 PROCESSOR_IDENTIFIER PROCESSOR_LEVEL PROCESSOR_REVISION ProgramData ProgramFiles ProgramFiles(x86) ProgramW6432 PUBLIC SystemDrive SystemRoot TEMP TMP USERDOMAIN USERDOMAIN_ROAMINGPROFILE USERNAME USERPROFILE windir SESSIONNAME
REM ___INFO_____________________________________________________________
REM :: this script reload environment variables inside cmd every time you want environment changes to propagate, so you do not need to restart cmd after setting a new variable with setx or when installing new apps which add new variables ...etc
REM This is a better alternative to the chocolatey refreshenv for cmd, which solves a lot of problems like:
REM The Chocolatey refreshenv is so bad if the variable have some cmd meta-characters, see this test:
REM add this to the path in HKCU\Environment: test & echo baaaaaaaaaad, and run the chocolatey refreshenv you will see that it prints baaaaaaaaaad which is very bad, and the new path is not added to your path variable.
REM This script solve this and you can test it with any meta-character, even something so bad like:
REM ; & % ' ( ) ~ + @ # $ { } [ ] , ` ! ^ | > < \ / " : ? * = . - _ & echo baaaad
REM refreshenv adds only system and user environment variables, but CMD adds volatile variables too (HKCU\Volatile Environment). This script will merge all the three and remove any duplicates.
REM refreshenv reset your PATH. This script append the new path to the old path of the parent script which called this script. It is better than overwriting the old path, otherwise it will delete any newly added path by the parent script.
REM This script solve this problem described in a comment by @Gene Mayevsky: refreshenv modifies env variables TEMP and TMP replacing them with values stored in HKCU\Environment. In my case I run the script to update env variables modified by Jenkins job on a slave that's running under SYSTEM account, so TEMP and TMP get substituted by %USERPROFILE%\AppData\Local\Temp instead of C:\Windows\Temp. This breaks build because linker cannot open system profile's Temp folder.
REM ________
REM this script solve things like that too:
REM The confusing thing might be that there are a few places to start the cmd from. In my case I run cmd from windows explorer and the environment variables did not change while when starting cmd from the "run" (windows key + r) the environment variables were changed.
REM In my case I just had to kill the windows explorer process from the task manager and then restart it again from the task manager.
REM Once I did this I had access to the new environment variable from a cmd that was spawned from windows explorer.
REM my conclusion:
REM if I add a new variable with setx, i can access it in cmd only if i run cmd as admin, without admin right i have to restart explorer to see that new variable. but running this script inside my script (who sets the variable with setx) solve this problem and i do not have to restart explorer
REM ________
REM windows recreate the path using three places at less:
REM the User namespace: HKCU\Environment
REM the System namespace: HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment
REM the Session namespace: HKCU\Volatile Environment
REM but the original chocolatey script did not add the volatile path. This script will merge all the three and remove any duplicates. this is what windows do by default too
REM there is this too which cmd seems to read when first running, but it contains only TEMP and TMP,so i will not use it
REM HKEY_USERS\.DEFAULT\Environment
REM ___TESTING_____________________________________________________________
REM to test this script with extreme cases do
REM :: Set a bad variable
REM add a var in reg HKCU\Environment as the following, and see that echo is not executed. if you use refreshenv of chocolatey you will see that echo is executed which is so bad!
REM so save this in reg:
REM all 32 characters: & % ' ( ) ~ + @ # $ { } [ ] ; , ` ! ^ | > < \ / " : ? * = . - _ & echo baaaad
REM and this:
REM (^.*)(Form Product=")([^"]*") FormType="[^"]*" FormID="([0-9][0-9]*)".*$
REM and use set to print those variables and see if they are saved without change ; refreshenv fail dramatically with those variables
REM invalid characters (illegal characters in file names) in Windows using NTFS
REM \ / : * ? " < > | and ^ in FAT
REM __________________________________________________________________________________________
REM __________________________________________________________________________________________
REM __________________________________________________________________________________________
REM this is a hybrid script which call vbs from cmd directly
REM :: The only restriction is the batch code cannot contain - - > (without space between - - > of course)
REM :: The only restriction is the VBS code cannot contain </script>.
REM :: The only risk is the undocumented use of "%~f0?.wsf" as the script to load. Somehow the parser properly finds and loads the running .BAT script "%~f0", and the ?.wsf suffix mysteriously instructs CSCRIPT to interpret the script as WSF. Hopefully MicroSoft will never disable that "feature".
REM :: https://stackoverflow.com/questions/9074476/is-it-possible-to-embed-and-execute-vbscript-within-a-batch-file-without-using-a
if "%debugme%"=="yes" (
echo RefrEnv - Refresh the Environment for CMD - ^(Debug enabled^)
) else (
echo RefrEnv - Refresh the Environment for CMD
)
set "TEMPDir=%TEMP%\refrenv"
IF NOT EXIST "%TEMPDir%" mkdir "%TEMPDir%"
set "outputfile=%TEMPDir%\_NewEnv.cmd"
REM detect if DelayedExpansion is enabled
REM It relies on the fact, that the last caret will be removed only in delayed mode.
REM https://www.dostips.com/forum/viewtopic.php?t=6496
set "DelayedExpansionState=IsDisabled"
IF "^!" == "^!^" (
REM echo DelayedExpansion is enabled
set "DelayedExpansionState=IsEnabled"
)
REM :: generate %outputfile% which contain all the new variables
REM cscript //nologo "%~f0?.wsf" %1
cscript //nologo "%~f0?.wsf" "%outputfile%" %DelayedExpansionState%
REM ::set the new variables generated with vbscript script above
REM for this to work always it is necessary to use DisableDelayedExpansion or escape ! and ^ when using EnableDelayedExpansion, but this script already solve this, so no worry about that now, thanks to God
REM test it with some bad var like:
REM all 32 characters: ; & % ' ( ) ~ + @ # $ { } [ ] , ` ! ^ | > < \ / " : ? * = . - _ & echo baaaad
REM For /f delims^=^ eol^= %%a in (%outputfile%) do %%a
REM for /f "delims== tokens=1,2" %%G in (%outputfile%) do set "%%G=%%H"
For /f delims^=^ eol^= %%a in (%outputfile%) do set %%a
REM for safely print a variable with bad charachters do:
REM SETLOCAL EnableDelayedExpansion
REM echo "!z9!"
REM or
REM set z9
REM but generally paths and environment variables should not have bad metacharacters, but it is not a rule!
if "%debugme%"=="yes" (
explorer "%TEMPDir%"
) else (
rmdir /Q /S "%TEMPDir%"
)
REM cleanup
set "TEMPDir="
set "outputfile="
set "DelayedExpansionState="
set "debugme="
REM pause
exit /b
REM #############################################################################
REM :: to run jscript you have to put <script language="JScript"> directly after ----- Begin wsf script --->
----- Begin wsf script --->
<job><script language="VBScript">
REM #############################################################################
REM ### put you code here #######################################################
REM #############################################################################
REM based on itsadok script from here
REM https://stackoverflow.com/questions/171588/is-there-a-command-to-refresh-environment-variables-from-the-command-prompt-in-w
REM and it is faster as stated by this comment
REM While I prefer the Chocolatey code-wise for being pure batch code, overall I decided to use this one, since it's faster. (~0.3 seconds instead of ~1 second -- which is nice, since I use it frequently in my Explorer "start cmd here" entry) –
REM and it is safer based on my tests, the Chocolatey refreshenv is so bad if the variable have some cmd metacharacters
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Set WshShell = WScript.CreateObject("WScript.Shell")
filename=WScript.Arguments.Item(0)
DelayedExpansionState=WScript.Arguments.Item(1)
TMPfilename=filename & "_temp_.cmd"
Set fso = CreateObject("Scripting.fileSystemObject")
Set tmpF = fso.CreateTextFile(TMPfilename, TRUE)
set oEnvS=WshShell.Environment("System")
for each sitem in oEnvS
tmpF.WriteLine(sitem)
next
SystemPath = oEnvS("PATH")
set oEnvU=WshShell.Environment("User")
for each sitem in oEnvU
tmpF.WriteLine(sitem)
next
UserPath = oEnvU("PATH")
set oEnvV=WshShell.Environment("Volatile")
for each sitem in oEnvV
tmpF.WriteLine(sitem)
next
VolatilePath = oEnvV("PATH")
set oEnvP=WshShell.Environment("Process")
REM i will not save the process env but only its path, because it have strange variables like =::=::\ and =F:=.... which seems to be added by vbscript
REM for each sitem in oEnvP
REM tmpF.WriteLine(sitem)
REM next
REM here we add the actual session path, so we do not reset the original path, because maybe the parent script added some folders to the path, If we need to reset the path then comment the following line
ProcessPath = oEnvP("PATH")
REM merge System, User, Volatile, and process PATHs
NewPath = SystemPath & ";" & UserPath & ";" & VolatilePath & ";" & ProcessPath
REM ________________________________________________________________
REM :: remove duplicates from path
REM :: expand variables so they become like windows do when he read reg and create path, then Remove duplicates without sorting
REM why i will clean the path from duplicates? because:
REM the maximum string length in cmd is 8191 characters. But string length doesnt mean that you can save 8191 characters in a variable because also the assignment belongs to the string. you can save 8189 characters because the remaining 2 characters are needed for "a="
REM based on my tests:
REM when i open cmd as user , windows does not remove any duplicates from the path, and merge system+user+volatil path
REM when i open cmd as admin, windows do: system+user path (here windows do not remove duplicates which is stupid!) , then it adds volatil path after removing from it any duplicates
REM ' https://www.rosettacode.org/wiki/Remove_duplicate_elements#VBScript
Function remove_duplicates(list)
arr = Split(list,";")
Set dict = CreateObject("Scripting.Dictionary")
REM ' force dictionary compare to be case-insensitive , uncomment to force case-sensitive
dict.CompareMode = 1
For i = 0 To UBound(arr)
If dict.Exists(arr(i)) = False Then
dict.Add arr(i),""
End If
Next
For Each key In dict.Keys
tmp = tmp & key & ";"
Next
remove_duplicates = Left(tmp,Len(tmp)-1)
End Function
REM expand variables
NewPath = WshShell.ExpandEnvironmentStrings(NewPath)
REM remove duplicates
NewPath=remove_duplicates(NewPath)
REM remove_duplicates() will add a ; to the end so lets remove it if the last letter is ;
If Right(NewPath, 1) = ";" Then
NewPath = Left(NewPath, Len(NewPath) - 1)
End If
tmpF.WriteLine("PATH=" & NewPath)
tmpF.Close
REM ________________________________________________________________
REM :: exclude setting variables which may be dangerous to change
REM when i run a script from task scheduler using SYSTEM user the following variables are the differences between the scheduler env and a normal cmd script, so i will not override those variables
REM APPDATA=D:\Users\LLED2\AppData\Roaming
REM APPDATA=D:\Windows\system32\config\systemprofile\AppData\Roaming
REM LOCALAPPDATA=D:\Users\LLED2\AppData\Local
REM LOCALAPPDATA=D:\Windows\system32\config\systemprofile\AppData\Local
REM TEMP=D:\Users\LLED2\AppData\Local\Temp
REM TEMP=D:\Windows\TEMP
REM TMP=D:\Users\LLED2\AppData\Local\Temp
REM TMP=D:\Windows\TEMP
REM USERDOMAIN=LLED2-PC
REM USERDOMAIN=WORKGROUP
REM USERNAME=LLED2
REM USERNAME=LLED2-PC$
REM USERPROFILE=D:\Users\LLED2
REM USERPROFILE=D:\Windows\system32\config\systemprofile
REM i know this thanks to this comment
REM The solution is good but it modifies env variables TEMP and TMP replacing them with values stored in HKCU\Environment. In my case I run the script to update env variables modified by Jenkins job on a slave that's running under SYSTEM account, so TEMP and TMP get substituted by %USERPROFILE%\AppData\Local\Temp instead of C:\Windows\Temp. This breaks build because linker cannot open system profile's Temp folder. – Gene Mayevsky Sep 26 '19 at 20:51
REM Delete Lines of a Text File Beginning with a Specified String
REM those are the variables which should not be changed by this script
arrBlackList = Array("ALLUSERSPROFILE=", "APPDATA=", "CommonProgramFiles=", "CommonProgramFiles(x86)=", "CommonProgramW6432=", "COMPUTERNAME=", "ComSpec=", "HOMEDRIVE=", "HOMEPATH=", "LOCALAPPDATA=", "LOGONSERVER=", "NUMBER_OF_PROCESSORS=", "OS=", "PATHEXT=", "PROCESSOR_ARCHITECTURE=", "PROCESSOR_ARCHITEW6432=", "PROCESSOR_IDENTIFIER=", "PROCESSOR_LEVEL=", "PROCESSOR_REVISION=", "ProgramData=", "ProgramFiles=", "ProgramFiles(x86)=", "ProgramW6432=", "PUBLIC=", "SystemDrive=", "SystemRoot=", "TEMP=", "TMP=", "USERDOMAIN=", "USERDOMAIN_ROAMINGPROFILE=", "USERNAME=", "USERPROFILE=", "windir=", "SESSIONNAME=")
Set objFS = CreateObject("Scripting.FileSystemObject")
Set objTS = objFS.OpenTextFile(TMPfilename, ForReading)
strContents = objTS.ReadAll
objTS.Close
TMPfilename2= filename & "_temp2_.cmd"
arrLines = Split(strContents, vbNewLine)
Set objTS = objFS.OpenTextFile(TMPfilename2, ForWriting, True)
REM this is the equivalent of findstr /V /I /L or grep -i -v , i don t know a better way to do it, but it works fine
For Each strLine In arrLines
bypassThisLine=False
For Each BlackWord In arrBlackList
If Left(UCase(LTrim(strLine)),Len(BlackWord)) = UCase(BlackWord) Then
bypassThisLine=True
End If
Next
If bypassThisLine=False Then
objTS.WriteLine strLine
End If
Next
REM ____________________________________________________________
REM :: expand variables because registry save some variables as unexpanded %....%
REM :: and escape ! and ^ for cmd EnableDelayedExpansion mode
set f=fso.OpenTextFile(TMPfilename2,ForReading)
REM Write file: ForAppending = 8 ForReading = 1 ForWriting = 2 , True=create file if not exist
set fW=fso.OpenTextFile(filename,ForWriting,True)
Do Until f.AtEndOfStream
LineContent = f.ReadLine
REM expand variables
LineContent = WshShell.ExpandEnvironmentStrings(LineContent)
REM _____this part is so important_____
REM if cmd delayedexpansion is enabled in the parent script which calls this script then bad thing happen to variables saved in the registry if they contain ! . if var have ! then ! and ^ are removed; if var do not have ! then ^ is not removed . to understand what happens read this :
REM how cmd delayed expansion parse things
REM https://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912
REM For each parsed token, first check if it contains any !. If not, then the token is not parsed - important for ^ characters. If the token does contain !, then scan each character from left to right:
REM - If it is a caret (^) the next character has no special meaning, the caret itself is removed
REM - If it is an exclamation mark, search for the next exclamation mark (carets are not observed anymore), expand to the value of the variable.
REM - Consecutive opening ! are collapsed into a single !
REM - Any remaining unpaired ! is removed
REM ...
REM Look at next string of characters, breaking before !, :, or <LF>, and call them VAR
REM conclusion:
REM when delayedexpansion is enabled and var have ! then i have to escape ^ and ! ,BUT IF VAR DO NOT HAVE ! THEN DO NOT ESCAPE ^ .this made me crazy to discover
REM when delayedexpansion is disabled then i do not have to escape anything
If DelayedExpansionState="IsEnabled" Then
If InStr(LineContent, "!") > 0 Then
LineContent=Replace(LineContent,"^","^^")
LineContent=Replace(LineContent,"!","^!")
End If
End If
REM __________
fW.WriteLine(LineContent)
Loop
f.Close
fW.Close
REM #############################################################################
REM ### end of vbscript code ####################################################
REM #############################################################################
REM this must be at the end for the hybrid trick, do not remove it
</script></job>
+2 -2
View File
@@ -1,4 +1,4 @@
urllib3==1.26.18 urllib3==1.26.18
requests==2.31.0 requests==2.32.3
pystray==0.19.5 pystray==0.19.5
dnspython==2.6.1 dnspython==2.7.0
+2 -2
View File
@@ -10,7 +10,7 @@ set ACTIVATE_PATH=%VENV_PATH%\Scripts\activate
set CURRENT_DIR=%CD% set CURRENT_DIR=%CD%
set LAST_DIR_FILE=%PROJECTFOLDER%\last_known_directory.txt set LAST_DIR_FILE=%PROJECTFOLDER%\last_known_directory.txt
set refrenv=%PROJECTFOLDER%\refrenv.bat set refrenv=%PROJECTFOLDER%\refrenv.bat
set PYTHON_DOWNLOAD_URL=https://www.python.org/ftp/python/3.12.2/python-3.12.2-amd64.exe set PYTHON_DOWNLOAD_URL=https://www.python.org/ftp/python/3.12.4/python-3.12.4-amd64.exe
:: Display provided argument if any :: Display provided argument if any
if not "%~1"=="" ( if not "%~1"=="" (
@@ -163,4 +163,4 @@ if errorlevel 1 (
exit /b exit /b
) )
exit /b exit /b