• PSA: Python script for selecting Tor exit nodes in Firefox Tor Browser

    From Maria Sophia@mariasophia@comprehension.com to comp.lang.python,alt.comp.os.windows-11,comp.sys.mac.system on Sun Nov 8 15:47:18 2026
    From Newsgroup: comp.sys.mac.system

    PSA: Python script for selecting Tor exit nodes in Firefox Tor Browser

    Below is python code which overcomes a Firefox Tor problem that I haven't
    been able to find a solution for, so last night I wrote the solution.

    Newsgroups: alt.comp.os.windows-10,alt.comp.software.firefox,alt.comp.microsoft.windows
    Subject: PSA: Setting the Windows Firefox Tor browser to use USA exit nodes
    Date: Sun, 8 Nov 2026 14:49:17 -0400
    Message-ID: <11cqg7d$2ml3$1@nnrp.usenet.blueworldhosting.com>

    This code defines a set of Tor exit nodes, so that when you visit web
    sites (e.g., mail servers) which are sensitive to location, it's static.

    However, if all we need is to set country codes, e.g., {us}, then this cross-platform script would be simpler for the country-code purpose alone.
    Windows:
    <https://github.com/gmolop/Tor-ExitNode-changer/blob/master/dist/tor_exitNode_changer.bat>
    Linux/macOS:
    <https://github.com/gmolop/Tor-ExitNode-changer/blob/master/dist/tor_exitNode_changer.sh>

    What I needed is pretty much so generic that I was initially shocked
    that the Firefox Tor Browser doesn't allow us to easily set exit nodes
    on the fly, so I first looked for apps that can do that for us.

    This can do it, but oh my God, it's too complicated, in terms of options.
    Windows
    <https://github.com/abysshint/tor-control-panel/releases/tag/v2.3.12.20>
    <https://github.com/abysshint/tor-control-panel/releases/download/v2.3.12.20/tor-control-panel-2.3.12.20-win64.exe>
    Name: tor-control-panel-2.3.12.20-win64.exe
    Size: 12134773 bytes (11 MiB)
    SHA256: D5A9A05318D6D99F85A6585A12FC324DB7ECBB8AACFC04E96CF56D481E7F076F

    If anyone knows of a program out there which will pop up a form asking
    you which exit nodes you want, please do let the team know about it.

    In the meantime, I wrote code that does just that, but what I thought
    would have taken only a half hour took 4 hours due to Tor complexities.

    The code below is NOT ported to macOS/Linux because I don't have those
    test jigs, but to make the script run seamlessly across Windows, Linux,
    and macOS, we can use Python's sys.platform to dynamically set the correct file paths and process-killing commands depending on the operating system.

    #!/usr/bin/env python3
    # ---------------------------------------------------------------------
    # torset.py
    # Manually set known-good Tor exit nodes for specific web-login profiles
    # ---------------------------------------------------------------------
    # Usage notes:
    # 1. Obtain desired US Tor exit relays:
    # https://metrics.torproject.org/rs.html#search/country:us%20flag:exit
    # For example:
    # "$688604204AF0C0473DFFA8CD2E186D1EEAEE6916"
    # "$B8FA90A8B7DA9B90A09AA04CD2E81E263AA8DA4C"
    # "$BD610AAEAE179EC259B022A178A75C70042407FB",
    # "$9C7B1DB2C5520B21E181EB945A01E9ABA42654A2",
    # 2. Enter their fingerprints in the profile definitions below
    # Profile 1
    # "$688604204AF0C0473DFFA8CD2E186D1EEAEE6916"
    # "$B8FA90A8B7DA9B90A09AA04CD2E81E263AA8DA4C"
    # Profile 2
    # "$BD610AAEAE179EC259B022A178A75C70042407FB",
    # Profile 3
    # "$9C7B1DB2C5520B21E181EB945A01E9ABA42654A2",
    # Note an exit node works also, e.g., "{us}"
    # 3. Run this script, which cleans stale sessions before starting
    # Tor and allowing the user the choice of setting exit nodes
    # 4. Allow Tor a bit of time to establish new circuits
    # 5. Verify the exit relay and exit IP before logging in
    # ---------------------------------------------------------------------
    # v2p8 20261108 Reverted profile exit nodes back to original configurations
    # v2p7 20261108 Converted native batch/PowerShell implementation to pure Python
    # v2p6 20261108 Improved documentation block details and accuracy
    # v2p5 20261108 Added new exit nodes and a profile configuration check
    # v2p4 20261108 Handled stale process cleanup cleanly in native batch
    # v2p3 20261108 Added automated cleanup of stale Tor/Firefox instances
    # v2p2 20261108 Added full bootstrap completion polling on cold start
    # v2p1 20261108 Fixed $tcp variable scope in try/finally block
    # v2p0 20261108 Added automated Tor Browser startup and port polling
    # v1p9 20261108 Added ControlPort error handling and response validation
    # v1p8 20261108 Cleaned up comments and clarified explanations
    # v1p7 20261108 Identify general-purpose ckts and compare exit fingerprints
    # v1p6 20261108 Display multi-line Tor circuit status via GETINFO
    # v1p5 20261108 Request new Tor circuits after profile selection
    # v1p4 20261108 Added multi-profile exit-node selection menu
    # v1p3 20261108 Set Profile 1 ExitNodes (two fingerprints) via SETCONF
    # v1p2 20261108 Added GETINFO status/bootstrap-phase
    # v1p1 20261108 Retrieve current ExitNodes configuration via GETCONF
    # v1p0 20261108 Tested Tor ControlPort via TCP cookie authentication
    # ---------------------------------------------------------------------
    # Summary:
    # 1. Present a multi-profile selection menu allowing the user to choose
    # between predefined exit-node configurations (or quit with Q).
    # 2. Terminate any stale or running instances of Firefox Tor Browser
    # to ensure a clean starting environment.
    # 3. Launch the Firefox Tor Browser executable automatically if it is
    # not currently running on the system.
    # 4. Poll local TCP port 9151 and monitor for the existence of Tor's
    # control authentication cookie file.
    # 5. Open a local TCP socket connection to Tor's ControlPort
    # (127.0.0.1:9151) once it becomes available.
    # 6. Authenticate the control session securely using the binary bytes
    # read from Tor's local control_auth_cookie.
    # 7. Poll Tor's bootstrap status via GETINFO until the bootstrap-phase
    # reports 100% completion.
    # 8. Apply the user's selected profile fingerprints to Tor's configuration
    # using the SETCONF ExitNodes command.
    # 9. Issue a SIGNAL NEWNYM command to force Tor to discard old circuits
    # and build new ones using the designated exit nodes.
    # 10. Verify that the active ExitNodes configuration matches the expected
    # profile fingerprints.
    # 11. Query active circuits (GETINFO circuit-status), parse their exit node
    # fingerprints and compare them against the profile whitelist.
    # 12. Output clear verification results to the user console and pause
    # before exiting, leaving the configured browser ready for secure use.
    # ---------------------------------------------------------------------
    import os
    import socket
    import subprocess
    import sys
    import time
    from pathlib import Path

    # --- Configuration & Paths ---
    COOKIE_PATH = Path(
    r"C:\app\browser\tbb\Tor Browser\Browser\TorBrowser\Data\Tor\control_auth_cookie"
    )
    TOR_EXE = Path(r"C:\app\browser\tbb\Tor Browser\Browser\firefox.exe")
    CONTROL_PORT = 9151

    # Define selectable profiles with your original exit node fingerprints
    PROFILES = {
    "1": {
    "name": "Profile 1",
    "exit_nodes": (
    "$688604204AF0C0473DFFA8CD2E186D1EEAEE6916,"
    "$B8FA90A8B7DA9B90A09AA04CD2E81E263AA8DA4C"
    ),
    },
    "2": {
    "name": "Profile 2",
    "exit_nodes": "$BD610AAEAE179EC259B022A178A75C70042407FB",
    },
    "3": {
    "name": "Profile 3",
    "exit_nodes": "$9C7B1DB2C5520B21E181EB945A01E9ABA42654A2",
    },
    }


    def main():
    # Step 1: Profile Selection Menu
    print("----------------------------------------")
    print(" Tor exit node selector ")
    print("----------------------------------------")
    print()
    print(" 1 for Profile 1")
    print(" 2 for Profile 2")
    print(" 3 for Profile 3")
    print(" Q to Quit")
    print()

    choice = input("Select profile [1,2,3] or Q to quit: ").strip().upper()
    if choice == "Q" or choice not in PROFILES:
    print("Exiting.")
    sys.exit(0)

    profile = PROFILES[choice]
    print(f"\nSetting {profile['name']}...")

    # Step 2: Clean up any stale or running Tor/Firefox instances
    print("Ensuring clean state by stopping any existing Tor instances...")
    try:
    subprocess.run(
    ["taskkill", "/f", "/im", "firefox.exe"],
    stdout=subprocess.DEVNULL,
    stderr=subprocess.DEVNULL,
    )
    except Exception:
    pass
    time.sleep(2)

    # Steps 3 & 4: Launch browser if needed and wait for ControlPort & cookie
    if not COOKIE_PATH.is_file():
    print("Tor Browser is not running. Starting Tor Browser automatically...")
    if not TOR_EXE.is_file():
    print(f"ERROR: Tor Browser executable not found at: {TOR_EXE}")
    sys.exit(1)
    subprocess.Popen([str(TOR_EXE)])
    print("Waiting for Tor Browser to initialize and open ControlPort (9151)...")

    start_time = time.time()
    ready = False
    while time.time() - start_time < 45:
    if COOKIE_PATH.is_file():
    try:
    test_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    test_sock.settimeout(2)
    test_sock.connect(("127.0.0.1", CONTROL_PORT))
    test_sock.close()
    ready = True
    break
    except (socket.error, OSError):
    pass
    time.sleep(2)

    if not ready:
    print(
    "ERROR: Timed out waiting for Tor Browser to start and open ControlPort"
    " 9151."
    )
    sys.exit(1)
    print("Tor Browser port is open.")

    # Step 6: Read authentication cookie bytes
    try:
    cookie_bytes = COOKIE_PATH.read_bytes()
    cookie_hex = cookie_bytes.hex().upper()
    except Exception as e:
    print(f"ERROR: Failed to read control authentication cookie: {e}")
    sys.exit(1)

    # Helper functions for Tor Control Protocol
    def read_tor_reply(sock_file):
    lines = []
    while True:
    line = sock_file.readline()
    if not line:
    raise RuntimeError("Tor closed the ControlPort connection unexpectedly.")
    decoded = line.decode("utf-8", errors="ignore").rstrip("\r\n")
    lines.append(decoded)
    if decoded.startswith("250+"):
    while True:
    data_line = sock_file.readline()
    if not data_line:
    raise RuntimeError(
    "Tor closed the connection during a data response."
    )
    d_decoded = data_line.decode("utf-8", errors="ignore").rstrip(
    "\r\n"
    )
    lines.append(d_decoded)
    if d_decoded == ".":
    break
    continue
    if len(decoded) >= 4 and decoded[3] == "-":
    continue
    break
    return lines

    def send_command(sock_file, command):
    sock_file.write((command + "\r\n").encode("utf-8"))
    sock_file.flush()
    reply = read_tor_reply(sock_file)
    if not reply or not reply[0].startswith("250"):
    raise RuntimeError(f"Tor rejected command: {command} -- {' '.join(reply)}")
    return reply

    # Step 5: Connect to ControlPort
    stream = None
    s = None
    try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(15)
    s.connect(("127.0.0.1", CONTROL_PORT))
    stream = s.makefile("rwb")

    # Authenticate session
    auth_reply = send_command(stream, f"AUTHENTICATE {cookie_hex}")
    print(f"Authentication: {auth_reply[0]}")

    # Step 7: Wait for Tor bootstrap completion (100%)
    print("Waiting for Tor bootstrap to complete...")
    bootstrap_complete = False
    b_start = time.time()
    while time.time() - b_start < 60:
    try:
    bootstrap_reply = send_command(stream, "GETINFO status/bootstrap-phase")
    for line in bootstrap_reply:
    if "PROGRESS=100" in line:
    bootstrap_complete = True
    break
    if bootstrap_complete:
    break
    except Exception:
    pass
    time.sleep(2)

    if not bootstrap_complete:
    raise RuntimeError("Timed out waiting for Tor to finish bootstrapping.")
    print("Tor bootstrap complete (100%).")

    # Step 8: Apply selected profile ExitNodes via SETCONF
    config_reply = send_command(stream, "GETCONF ExitNodes")
    print(f"Exit configuration: {' '.join(config_reply)}")

    setconf_reply = send_command(
    stream, f"SETCONF ExitNodes={profile['exit_nodes']}"
    )
    print(f"SETCONF response: {setconf_reply[-1]}")

    # Step 9: Signal NEWNYM to clear circuits and build new ones
    newnym_reply = send_command(stream, "SIGNAL NEWNYM")
    print(f"NEWNYM response: {newnym_reply[-1]}")

    time.sleep(3)

    # Step 10: Verify new ExitNodes configuration matches expected
    config_reply = send_command(stream, "GETCONF ExitNodes")
    print(f"New exit configuration: {' '.join(config_reply)}")

    actual_line = None
    for item in config_reply:
    if item.startswith("250 ExitNodes="):
    actual_line = item
    break

    if not actual_line:
    raise RuntimeError("Could not verify the new ExitNodes configuration.")

    actual_text = actual_line.replace("250 ExitNodes=", "")
    actual_nodes = [
    fp.strip().lstrip("$").upper() for fp in actual_text.split(",") if fp
    ]
    expected_nodes = [
    fp.strip().lstrip("$").upper()
    for fp in profile["exit_nodes"].split(",")
    if fp
    ]

    if set(actual_nodes) != set(expected_nodes):
    raise RuntimeError("ExitNodes verification failed: fingerprint mismatch.")
    print("ExitNodes verification: Match")

    allowed = {fp: True for fp in expected_nodes}

    # Step 11: Inspect circuit-status and compare exit fingerprints
    circuit_reply = send_command(stream, "GETINFO circuit-status")
    print("\nGeneral-purpose circuits")
    print("-------------------------")

    found = False
    for line in circuit_reply:
    if "BUILT" not in line or "PURPOSE=GENERAL" not in line:
    continue
    fields = line.split()
    if len(fields) < 3:
    continue

    circuit_id = fields[0]
    hops = fields[2].split(",")
    last_hop = hops[-1].split("~")[0].lstrip("$").upper()
    found = True

    print(f"\nCircuit: {circuit_id}")
    print(f"Exit fingerprint: {last_hop}")
    if last_hop in allowed:
    print("Profile comparison: Match")
    else:
    print("Profile comparison: Not in profile")

    if not found:
    print("No built general-purpose circuits found.")

    print("\nCircuit inspection complete.")
    print("Tor control session completed successfully.")

    except Exception as e:
    print(f"\nError: {e}", file=sys.stderr)
    sys.exit(1)
    finally:
    if stream:
    try:
    stream.close()
    except Exception:
    pass
    if s:
    try:
    s.close()
    except Exception:
    pass

    # Step 12: Output final success message and pause before exit
    print("\ntorset completed successfully.")
    input("Press Enter to continue . . . ")


    if __name__ == "__main__":
    main()
    # ---------------------------------------------------------------------
    # end of torset.py
    # ---------------------------------------------------------------------
    --
    Helpful suggestions from people are why Usenet still remains invaluable.
    --- Synchronet 3.22a-Linux NewsLink 1.2
  • From Maria Sophia@mariasophia@comprehension.com to comp.lang.python,alt.comp.os.windows-11,comp.sys.mac.system on Mon Nov 9 10:27:21 2026
    From Newsgroup: comp.sys.mac.system

    Maria Sophia wrote:
    The code below is NOT ported to macOS/Linux because I don't have those
    test jigs, but to make the script run seamlessly across Windows, Linux,
    and macOS, we can use Python's sys.platform to dynamically set the correct file paths and process-killing commands depending on the operating system.

    Turns out porting to macOS/Linux was pretty simple so I did it, but I did
    not test except on Windows (so I ask someone on those platforms to test).

    #!/usr/bin/env python3
    # ---------------------------------------------------------------------
    # torset.py
    # Manually set known-good Tor exit nodes for specific web-login profiles
    # ---------------------------------------------------------------------
    # Usage notes:
    # 1. Obtain a set of desired known-to-be-working US Tor exit relays:
    # https://metrics.torproject.org/rs.html#search/country:us%20flag:exit
    # For example:
    # "$688604204AF0C0473DFFA8CD2E186D1EEAEE6916"
    # "$B8FA90A8B7DA9B90A09AA04CD2E81E263AA8DA4C"
    # "$BD610AAEAE179EC259B022A178A75C70042407FB"
    # "$9C7B1DB2C5520B21E181EB945A01E9ABA42654A2"
    # 2. Enter their fingerprints in the profile definitions, e.g.,
    # Profile 1 (gmail)
    # "$688604204AF0C0473DFFA8CD2E186D1EEAEE6916"
    # "$B8FA90A8B7DA9B90A09AA04CD2E81E263AA8DA4C"
    # Profile 2 (protonmail)
    # "$BD610AAEAE179EC259B022A178A75C70042407FB"
    # Profile 3 (facebook)
    # "$9C7B1DB2C5520B21E181EB945A01E9ABA42654A2"
    # 3. Run this script, which cleans stale sessions before starting
    # Tor and then provides a choice of pre-selected exit nodes
    # Note: Due to Firefox Tor browser complexities, allow Tor a bit of
    # time to establish new circuits and then make sure to manually
    # verify the exit relay and exit IP before logging in
    # ---------------------------------------------------------------------
    # v2p9 20261109 Added sys.platform support for macOS and Linux paths
    # v2p8 20261109 Reverted profile exit nodes back to original configurations
    # v2p7 20261108 Converted native batch/PowerShell implementation to Python
    # v2p6 20261108 Improved documentation in terms of technical accuracy
    # v2p5 20261108 Added new exit nodes and a profile configuration check
    # v2p4 20261108 Handled stale process cleanup cleanly in native batch
    # v2p3 20261108 Added automated cleanup of stale Tor/Firefox instances
    # v2p2 20261108 Added full bootstrap completion polling on cold start
    # v2p1 20261108 Fixed $tcp variable scope in try/finally block
    # v2p0 20261108 Added automated Tor Browser startup and port polling
    # v1p9 20261108 Added ControlPort error handling and response validation
    # v1p8 20261108 Cleaned up comments and clarified explanations
    # v1p7 20261108 Identify general-purpose ckts and compare exit fingerprints
    # v1p6 20261108 Display multi-line Tor circuit status via GETINFO
    # v1p5 20261108 Request new Tor circuits after profile selection
    # v1p4 20261108 Added multi-profile exit-node selection menu
    # v1p3 20261108 Set Profile 1 ExitNodes (two fingerprints) via SETCONF
    # v1p2 20261108 Added GETINFO status/bootstrap-phase
    # v1p1 20261108 Retrieve current ExitNodes configuration via GETCONF
    # v1p0 20261108 Tested Tor ControlPort via TCP cookie authentication
    # ---------------------------------------------------------------------
    # See also...
    # Forces a new working Tor exit node:
    # <https://github.com/gmolop/Tor-ExitNode-changer/>
    # <https://github.com/hevnsnt/IPChanger>
    # <https://gist.github.com/kirelagin/9667900>
    # Interacts with Tor using the Python stem library:
    # <https://pypi.org/project/stem/> <https://stem.torproject.org/>
    # <https://github.com/torproject/stem>
    # Command-line Tor interaction and Nyx monitor:
    # <https://nyx.torproject.org/> <https://github.com/torproject/nyx>
    # Configures Tor using a GUI (Windows only):
    # <https://github.com/abysshint/tor-control-panel/>
    # ---------------------------------------------------------------------
    # Summary:
    # 1. Present a multi-profile selection menu allowing the user to choose
    # between predefined exit-node configurations (or quit with Q).
    # 2. Terminate any stale or running instances of Firefox Tor Browser
    # to ensure a clean starting environment.
    # 3. Launch the Firefox Tor Browser executable automatically if it is
    # not currently running on the system.
    # 4. Poll local TCP port 9151 and monitor for the existence of Tor's
    # control authentication cookie file.
    # 5. Open a local TCP socket connection to Tor's ControlPort
    # (127.0.0.1:9151) once it becomes available.
    # 6. Authenticate the control session securely using the binary bytes
    # read from Tor's local control_auth_cookie.
    # 7. Poll Tor's bootstrap status via GETINFO until the bootstrap-phase
    # reports 100% completion.
    # 8. Apply the user's selected profile fingerprints to Tor's configuration
    # using the SETCONF ExitNodes command.
    # 9. Issue a SIGNAL NEWNYM command to force Tor to discard old circuits
    # and build new ones using the designated exit nodes.
    # 10. Verify that the active ExitNodes configuration matches the expected
    # profile fingerprints.
    # 11. Query active circuits (GETINFO circuit-status), parse their exit node
    # fingerprints and compare them against the profile whitelist.
    # 12. Output clear verification results to the user console and pause
    # before exiting, leaving the configured browser ready for secure use.
    # ---------------------------------------------------------------------
    import os
    import socket
    import subprocess
    import sys
    import time
    from pathlib import Path

    # --- Configuration & Cross-Platform Paths ---
    if sys.platform == "win32":
    COOKIE_PATH = Path(
    r"C:\app\browser\tor\Tor Browser\Browser\TorBrowser\Data\Tor\control_auth_cookie"
    )
    TOR_EXE = Path(r"C:\app\browser\tor\Tor Browser\Browser\firefox.exe")
    KILL_CMD = ["taskkill", "/f", "/im", "firefox.exe"]
    elif sys.platform == "darwin": # macOS
    TOR_EXE = Path.home() / "Applications" / "TorBrowser.app" / "Contents" / "MacOS" / "firefox"
    if not TOR_EXE.is_file():
    TOR_EXE = Path("/Applications/TorBrowser.app/Contents/MacOS/firefox")
    COOKIE_PATH = Path.home() / "Library" / "Application Support" / "TorBrowser-Data" / "Tor" / "control_auth_cookie"
    KILL_CMD = ["pkill", "-f", "torbrowser"]
    else: # Linux and other Unix-likes
    base_linux = Path.home() / ".local" / "share" / "torbrowser" / "tor" / "x86_64" / "tor-browser"
    TOR_EXE = base_linux / "Browser" / "firefox"
    COOKIE_PATH = base_linux / "Browser" / "TorBrowser" / "Data" / "Tor" / "control_auth_cookie"
    KILL_CMD = ["pkill", "-f", "tor-browser"]

    CONTROL_PORT = 9151

    # Define selectable profiles with your original exit node fingerprints
    PROFILES = {
    "1": {
    "name": "Profile 1",
    "exit_nodes": (
    "$688604204AF0C0473DFFA8CD2E186D1EEAEE6916,"
    "$B8FA90A8B7DA9B90A09AA04CD2E81E263AA8DA4C"
    ),
    },
    "2": {
    "name": "Profile 2",
    "exit_nodes": "$BD610AAEAE179EC259B022A178A75C70042407FB",
    },
    "3": {
    "name": "Profile 3",
    "exit_nodes": "$9C7B1DB2C5520B21E181EB945A01E9ABA42654A2",
    },
    }


    def main():
    # Step 1: Profile Selection Menu
    print("----------------------------------------")
    print(" Tor exit node selector ")
    print("----------------------------------------")
    print()
    print(" 1 for Profile 1")
    print(" 2 for Profile 2")
    print(" 3 for Profile 3")
    print(" Q to Quit")
    print()

    choice = input("Select profile [1,2,3] or Q to quit: ").strip().upper()
    if choice == "Q" or choice not in PROFILES:
    print("Exiting.")
    sys.exit(0)

    profile = PROFILES[choice]
    print(f"\nSetting {profile['name']}...")

    # Step 2: Clean up any stale or running Tor/Firefox instances
    print("Ensuring clean state by stopping any existing Tor instances...")
    try:
    subprocess.run(
    KILL_CMD,
    stdout=subprocess.DEVNULL,
    stderr=subprocess.DEVNULL,
    )
    except Exception:
    pass
    time.sleep(2)

    # Steps 3 & 4: Launch browser if needed and wait for ControlPort & cookie
    if not COOKIE_PATH.is_file():
    print("Tor Browser is not running. Starting Tor Browser automatically...")
    if not TOR_EXE.is_file():
    print(f"ERROR: Tor Browser executable not found at: {TOR_EXE}")
    sys.exit(1)
    subprocess.Popen([str(TOR_EXE)])
    print("Waiting for Tor Browser to initialize and open ControlPort (9151)...")

    start_time = time.time()
    ready = False
    while time.time() - start_time < 45:
    if COOKIE_PATH.is_file():
    try:
    test_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    test_sock.settimeout(2)
    test_sock.connect(("127.0.0.1", CONTROL_PORT))
    test_sock.close()
    ready = True
    break
    except (socket.error, OSError):
    pass
    time.sleep(2)

    if not ready:
    print(
    "ERROR: Timed out waiting for Tor Browser to start and open ControlPort"
    " 9151."
    )
    sys.exit(1)
    print("Tor Browser port is open.")

    # Step 6: Read authentication cookie bytes
    try:
    cookie_bytes = COOKIE_PATH.read_bytes()
    cookie_hex = cookie_bytes.hex().upper()
    except Exception as e:
    print(f"ERROR: Failed to read control authentication cookie: {e}")
    sys.exit(1)

    # Helper functions for Tor Control Protocol
    def read_tor_reply(sock_file):
    lines = []
    while True:
    line = sock_file.readline()
    if not line:
    raise RuntimeError("Tor closed the ControlPort connection unexpectedly.")
    decoded = line.decode("utf-8", errors="ignore").rstrip("\r\n")
    lines.append(decoded)
    if decoded.startswith("250+"):
    while True:
    data_line = sock_file.readline()
    if not data_line:
    raise RuntimeError(
    "Tor closed the connection during a data response."
    )
    d_decoded = data_line.decode("utf-8", errors="ignore").rstrip(
    "\r\n"
    )
    lines.append(d_decoded)
    if d_decoded == ".":
    break
    continue
    if len(decoded) >= 4 and decoded[3] == "-":
    continue
    break
    return lines

    def send_command(sock_file, command):
    sock_file.write((command + "\r\n").encode("utf-8"))
    sock_file.flush()
    reply = read_tor_reply(sock_file)
    if not reply or not reply[0].startswith("250"):
    raise RuntimeError(f"Tor rejected command: {command} -- {' '.join(reply)}")
    return reply

    # Step 5: Connect to ControlPort
    stream = None
    s = None
    try:
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(15)
    s.connect(("127.0.0.1", CONTROL_PORT))
    stream = s.makefile("rwb")

    # Authenticate session
    auth_reply = send_command(stream, f"AUTHENTICATE {cookie_hex}")
    print(f"Authentication: {auth_reply[0]}")

    # Step 7: Wait for Tor bootstrap completion (100%)
    print("Waiting for Tor bootstrap to complete...")
    bootstrap_complete = False
    b_start = time.time()
    while time.time() - b_start < 60:
    try:
    bootstrap_reply = send_command(stream, "GETINFO status/bootstrap-phase")
    for line in bootstrap_reply:
    if "PROGRESS=100" in line:
    bootstrap_complete = True
    break
    if bootstrap_complete:
    break
    except Exception:
    pass
    time.sleep(2)

    if not bootstrap_complete:
    raise RuntimeError("Timed out waiting for Tor to finish bootstrapping.")
    print("Tor bootstrap complete (100%).")

    # Step 8: Apply selected profile ExitNodes via SETCONF
    config_reply = send_command(stream, "GETCONF ExitNodes")
    print(f"Exit configuration: {' '.join(config_reply)}")

    setconf_reply = send_command(
    stream, f"SETCONF ExitNodes={profile['exit_nodes']}"
    )
    print(f"SETCONF response: {setconf_reply[-1]}")

    # Step 9: Signal NEWNYM to clear circuits and build new ones
    newnym_reply = send_command(stream, "SIGNAL NEWNYM")
    print(f"NEWNYM response: {newnym_reply[-1]}")

    time.sleep(3)

    # Step 10: Verify new ExitNodes configuration matches expected
    config_reply = send_command(stream, "GETCONF ExitNodes")
    print(f"New exit configuration: {' '.join(config_reply)}")

    actual_line = None
    for item in config_reply:
    if item.startswith("250 ExitNodes="):
    actual_line = item
    break

    if not actual_line:
    raise RuntimeError("Could not verify the new ExitNodes configuration.")

    actual_text = actual_line.replace("250 ExitNodes=", "")
    actual_nodes = [
    fp.strip().lstrip("$").upper() for fp in actual_text.split(",") if fp
    ]
    expected_nodes = [
    fp.strip().lstrip("$").upper()
    for fp in profile["exit_nodes"].split(",")
    if fp
    ]

    if set(actual_nodes) != set(expected_nodes):
    raise RuntimeError("ExitNodes verification failed: fingerprint mismatch.")
    print("ExitNodes verification: Match")

    allowed = {fp: True for fp in expected_nodes}

    # Step 11: Inspect circuit-status and compare exit fingerprints
    circuit_reply = send_command(stream, "GETINFO circuit-status")
    print("\nGeneral-purpose circuits")
    print("-------------------------")

    found = False
    for line in circuit_reply:
    if "BUILT" not in line or "PURPOSE=GENERAL" not in line:
    continue
    fields = line.split()
    if len(fields) < 3:
    continue

    circuit_id = fields[0]
    hops = fields[2].split(",")
    last_hop = hops[-1].split("~")[0].lstrip("$").upper()
    found = True

    print(f"\nCircuit: {circuit_id}")
    print(f"Exit fingerprint: {last_hop}")
    if last_hop in allowed:
    print("Profile comparison: Match")
    else:
    print("Profile comparison: Not in profile")

    if not found:
    print("No built general-purpose circuits found.")

    print("\nCircuit inspection complete.")
    print("Tor control session completed successfully.")

    except Exception as e:
    print(f"\nError: {e}", file=sys.stderr)
    sys.exit(1)
    finally:
    if stream:
    try:
    stream.close()
    except Exception:
    pass
    if s:
    try:
    s.close()
    except Exception:
    pass

    # Step 12: Output final success message and pause before exit
    print("\ntorset completed successfully.")
    input("Press Enter to continue . . . ")


    if __name__ == "__main__":
    main()
    # ---------------------------------------------------------------------
    # end of torset.py
    # ---------------------------------------------------------------------
    --
    On Usenet, a good suggestion can make everyone's solution a little better.
    --- Synchronet 3.22a-Linux NewsLink 1.2
  • From Lawrence =?iso-8859-13?q?D=FFOliveiro?=@ldo@nz.invalid to comp.lang.python,alt.comp.os.windows-11,comp.sys.mac.system on Mon Nov 9 22:49:40 2026
    From Newsgroup: comp.sys.mac.system

    On Mon, 9 Nov 2026 10:27:21 -0400, Maria Sophia wrote:

    try:

    ...

    except Exception as e:
    print(f"\nError: {e}", file=sys.stderr)
    sys.exit(1)
    finally:
    if stream:
    try:
    stream.close()
    except Exception:
    pass
    if s:
    try:
    s.close()
    except Exception:
    pass

    Get rid of that enclosing try-block.
    --- Synchronet 3.22a-Linux NewsLink 1.2
  • From Maria Sophia@mariasophia@comprehension.com to comp.lang.python,alt.comp.os.windows-11,comp.sys.mac.system on Mon Nov 9 23:49:33 2026
    From Newsgroup: comp.sys.mac.system

    Lawrence DoOliveiro wrote:
    Get rid of that enclosing try-block.

    Hi Lawrence,

    Ah. Perfect! Thanks for pointing out that flaw.
    You're the first person to add value on the Python side!

    Good catch! You're right.
    Dropping that outer try/except/finally block cleans things up tidily.

    Since we're already utilizing Python context managers (with statements)
    for both the socket and the makefile stream, the underlying socket and
    file handle are already closed both safely and automatically when
    exiting the block, regardless of whether an exception happens.

    Having an explicit finally block closing s separately was redundant.
    I goofed. Mea culpa.

    Removing the extra wrapper makes the script both more idiomatic & concise.
    Much appreciated, as the goal is two fold:
    a. Edify everyone
    b. Improve the tools so everyone can use them

    I love when someone who knows what they're doing points out a flaw
    in my thinking as my whole mind, body and soul is about collaboration!

    Thanks!
    Here's the update.

    Let us know if it works on the Linux/macOS side of the house 'cuz
    I don't have those platforms, so it's written w/o benefit of testing.

    #!/usr/bin/env python3
    # ---------------------------------------------------------------------
    # torset.py
    # Manually set known-good Tor exit nodes for specific web-login profiles
    # ---------------------------------------------------------------------
    # Usage notes:
    # 1. Obtain a set of desired known-to-be-working US Tor exit relays:
    # https://metrics.torproject.org/rs.html#search/country:us%20flag:exit
    # For example:
    # "$688604204AF0C0473DFFA8CD2E186D1EEAEE6916"
    # "$B8FA90A8B7DA9B90A09AA04CD2E81E263AA8DA4C"
    # "$BD610AAEAE179EC259B022A178A75C70042407FB"
    # "$9C7B1DB2C5520B21E181EB945A01E9ABA42654A2"
    # 2. Enter their fingerprints in the profile definitions, e.g.,
    # Profile 1 (gmail)
    # "$688604204AF0C0473DFFA8CD2E186D1EEAEE6916"
    # "$B8FA90A8B7DA9B90A09AA04CD2E81E263AA8DA4C"
    # Profile 2 (protonmail)
    # "$BD610AAEAE179EC259B022A178A75C70042407FB"
    # Profile 3 (facebook)
    # "$9C7B1DB2C5520B21E181EB945A01E9ABA42654A2"
    # 3. Run this script, which cleans stale sessions before starting
    # Tor and then provides a choice of pre-selected exit nodes
    # Note: Due to Firefox Tor browser complexities, allow Tor a bit of
    # time to establish new circuits and then make sure to manually
    # verify the exit relay and exit IP before logging in
    # ---------------------------------------------------------------------
    # v3p0 20261109 Replaced socket/stream cleanup with Python context managers
    # v2p9 20261109 Added sys.platform support for macOS and Linux paths
    # v2p8 20261109 Reverted profile exit nodes back to original configurations
    # v2p7 20261108 Converted native batch/PowerShell implementation to Python
    # v2p6 20261108 Improved documentation in terms of technical accuracy
    # v2p5 20261108 Added new exit nodes and a profile configuration check
    # v2p4 20261108 Handled stale process cleanup cleanly in native batch
    # v2p3 20261108 Added automated cleanup of stale Tor/Firefox instances
    # v2p2 20261108 Added full bootstrap completion polling on cold start
    # v2p1 20261108 Fixed $tcp variable scope in try/finally block
    # v2p0 20261108 Added automated Tor Browser startup and port polling
    # v1p9 20261108 Added ControlPort error handling and response validation
    # v1p8 20261108 Cleaned up comments and clarified explanations
    # v1p7 20261108 Identify general-purpose ckts and compare exit fingerprints
    # v1p6 20261108 Display multi-line Tor circuit status via GETINFO
    # v1p5 20261108 Request new Tor circuits after profile selection
    # v1p4 20261108 Added multi-profile exit-node selection menu
    # v1p3 20261108 Set Profile 1 ExitNodes (two fingerprints) via SETCONF
    # v1p2 20261108 Added GETINFO status/bootstrap-phase
    # v1p1 20261108 Retrieve current ExitNodes configuration via GETCONF
    # v1p0 20261108 Tested Tor ControlPort via TCP cookie authentication
    # ---------------------------------------------------------------------
    # See also...
    # Forces a new working Tor exit node:
    # <https://github.com/gmolop/Tor-ExitNode-changer/>
    # <https://github.com/hevnsnt/IPChanger>
    # <https://gist.github.com/kirelagin/9667900>
    # Interacts with Tor using the Python stem library:
    # <https://pypi.org/project/stem/> <https://stem.torproject.org/>
    # <https://github.com/torproject/stem>
    # Command-line Tor interaction and Nyx monitor:
    # <https://nyx.torproject.org/> <https://github.com/torproject/nyx>
    # Configures Tor using a GUI (Windows only):
    # <https://github.com/abysshint/tor-control-panel/>
    # ---------------------------------------------------------------------
    # Summary:
    # 1. Present a multi-profile selection menu allowing the user to choose
    # between predefined exit-node configurations (or quit with Q).
    # 2. Terminate any stale or running instances of Firefox Tor Browser
    # to ensure a clean starting environment.
    # 3. Launch the Firefox Tor Browser executable automatically if it is
    # not currently running on the system.
    # 4. Poll local TCP port 9151 and monitor for the existence of Tor's
    # control authentication cookie file.
    # 5. Open a local TCP socket connection to Tor's ControlPort
    # (127.0.0.1:9151) once it becomes available.
    # 6. Authenticate the control session securely using the binary bytes
    # read from Tor's local control_auth_cookie.
    # 7. Poll Tor's bootstrap status via GETINFO until the bootstrap-phase
    # reports 100% completion.
    # 8. Apply the user's selected profile fingerprints to Tor's configuration
    # using the SETCONF ExitNodes command.
    # 9. Issue a SIGNAL NEWNYM command to force Tor to discard old circuits
    # and build new ones using the designated exit nodes.
    # 10. Verify that the active ExitNodes configuration matches the expected
    # profile fingerprints.
    # 11. Query active circuits (GETINFO circuit-status), parse their exit node
    # fingerprints and compare them against the profile whitelist.
    # 12. Output clear verification results to the user console and pause
    # before exiting, leaving the configured browser ready for secure use.
    # ---------------------------------------------------------------------
    import os
    import socket
    import subprocess
    import sys
    import time
    from pathlib import Path

    # --- Configuration & Cross-Platform Paths ---
    if sys.platform == "win32":
    COOKIE_PATH = Path(
    r"C:\app\browser\tor\Tor Browser\Browser\TorBrowser\Data\Tor\control_auth_cookie"
    )
    TOR_EXE = Path(r"C:\app\browser\tor\Tor Browser\Browser\firefox.exe")
    KILL_CMD = ["taskkill", "/f", "/im", "firefox.exe"]
    elif sys.platform == "darwin": # macOS
    TOR_EXE = Path.home() / "Applications" / "TorBrowser.app" / "Contents" / "MacOS" / "firefox"
    if not TOR_EXE.is_file():
    TOR_EXE = Path("/Applications/TorBrowser.app/Contents/MacOS/firefox")
    COOKIE_PATH = Path.home() / "Library" / "Application Support" / "TorBrowser-Data" / "Tor" / "control_auth_cookie"
    KILL_CMD = ["pkill", "-f", "torbrowser"]
    else: # Linux and other Unix-likes
    base_linux = Path.home() / ".local" / "share" / "torbrowser" / "tor" / "x86_64" / "tor-browser"
    TOR_EXE = base_linux / "Browser" / "firefox"
    COOKIE_PATH = base_linux / "Browser" / "TorBrowser" / "Data" / "Tor" / "control_auth_cookie"
    KILL_CMD = ["pkill", "-f", "tor-browser"]

    CONTROL_PORT = 9151

    # Define selectable profiles with your original exit node fingerprints
    PROFILES = {
    "1": {
    "name": "Profile 1",
    "exit_nodes": (
    "$688604204AF0C0473DFFA8CD2E186D1EEAEE6916,"
    "$B8FA90A8B7DA9B90A09AA04CD2E81E263AA8DA4C"
    ),
    },
    "2": {
    "name": "Profile 2",
    "exit_nodes": "$BD610AAEAE179EC259B022A178A75C70042407FB",
    },
    "3": {
    "name": "Profile 3",
    "exit_nodes": "$9C7B1DB2C5520B21E181EB945A01E9ABA42654A2",
    },
    }


    def main():
    # Step 1: Profile Selection Menu
    print("----------------------------------------")
    print(" Tor exit node selector ")
    print("----------------------------------------")
    print()
    print(" 1 for Profile 1")
    print(" 2 for Profile 2")
    print(" 3 for Profile 3")
    print(" Q to Quit")
    print()

    choice = input("Select profile [1,2,3] or Q to quit: ").strip().upper()
    if choice == "Q" or choice not in PROFILES:
    print("Exiting.")
    sys.exit(0)

    profile = PROFILES[choice]
    print(f"\nSetting {profile['name']}...")

    # Step 2: Clean up any stale or running Tor/Firefox instances
    print("Ensuring clean state by stopping any existing Tor instances...")
    try:
    subprocess.run(
    KILL_CMD,
    stdout=subprocess.DEVNULL,
    stderr=subprocess.DEVNULL,
    )
    except Exception:
    pass
    time.sleep(2)

    # Steps 3 & 4: Launch browser if needed and wait for ControlPort & cookie
    if not COOKIE_PATH.is_file():
    print("Tor Browser is not running. Starting Tor Browser automatically...")
    if not TOR_EXE.is_file():
    print(f"ERROR: Tor Browser executable not found at: {TOR_EXE}")
    sys.exit(1)
    subprocess.Popen([str(TOR_EXE)])
    print("Waiting for Tor Browser to initialize and open ControlPort (9151)...")

    start_time = time.time()
    ready = False
    while time.time() - start_time < 45:
    if COOKIE_PATH.is_file():
    try:
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as test_sock:
    test_sock.settimeout(2)
    test_sock.connect(("127.0.0.1", CONTROL_PORT))
    ready = True
    break
    except (socket.error, OSError):
    pass
    time.sleep(2)

    if not ready:
    print(
    "ERROR: Timed out waiting for Tor Browser to start and open ControlPort"
    " 9151."
    )
    sys.exit(1)
    print("Tor Browser port is open.")

    # Step 6: Read authentication cookie bytes
    try:
    cookie_bytes = COOKIE_PATH.read_bytes()
    cookie_hex = cookie_bytes.hex().upper()
    except Exception as e:
    print(f"ERROR: Failed to read control authentication cookie: {e}")
    sys.exit(1)

    # Helper functions for Tor Control Protocol
    def read_tor_reply(sock_file):
    lines = []
    while True:
    line = sock_file.readline()
    if not line:
    raise RuntimeError("Tor closed the ControlPort connection unexpectedly.")
    decoded = line.decode("utf-8", errors="ignore").rstrip("\r\n")
    lines.append(decoded)
    if decoded.startswith("250+"):
    while True:
    data_line = sock_file.readline()
    if not data_line:
    raise RuntimeError(
    "Tor closed the connection during a data response."
    )
    d_decoded = data_line.decode("utf-8", errors="ignore").rstrip(
    "\r\n"
    )
    lines.append(d_decoded)
    if d_decoded == ".":
    break
    continue
    if len(decoded) >= 4 and decoded[3] == "-":
    continue
    break
    return lines

    def send_command(sock_file, command):
    sock_file.write((command + "\r\n").encode("utf-8"))
    sock_file.flush()
    reply = read_tor_reply(sock_file)
    if not reply or not reply[0].startswith("250"):
    raise RuntimeError(f"Tor rejected command: {command} -- {' '.join(reply)}")
    return reply

    # Step 5: Connect to ControlPort using context managers (incorporating Lawrence's feedback)
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.settimeout(15)
    s.connect(("127.0.0.1", CONTROL_PORT))
    with s.makefile("rwb") as stream:

    # Authenticate session
    auth_reply = send_command(stream, f"AUTHENTICATE {cookie_hex}")
    print(f"Authentication: {auth_reply[0]}")

    # Step 7: Wait for Tor bootstrap completion (100%)
    print("Waiting for Tor bootstrap to complete...")
    bootstrap_complete = False
    b_start = time.time()
    while time.time() - b_start < 60:
    try:
    bootstrap_reply = send_command(stream, "GETINFO status/bootstrap-phase")
    for line in bootstrap_reply:
    if "PROGRESS=100" in line:
    bootstrap_complete = True
    break
    if bootstrap_complete:
    break
    except Exception:
    pass
    time.sleep(2)

    if not bootstrap_complete:
    raise RuntimeError("Timed out waiting for Tor to finish bootstrapping.")
    print("Tor bootstrap complete (100%).")

    # Step 8: Apply selected profile ExitNodes via SETCONF
    config_reply = send_command(stream, "GETCONF ExitNodes")
    print(f"Exit configuration: {' '.join(config_reply)}")

    setconf_reply = send_command(
    stream, f"SETCONF ExitNodes={profile['exit_nodes']}"
    )
    print(f"SETCONF response: {setconf_reply[-1]}")

    # Step 9: Signal NEWNYM to clear circuits and build new ones
    newnym_reply = send_command(stream, "SIGNAL NEWNYM")
    print(f"NEWNYM response: {newnym_reply[-1]}")

    time.sleep(3)

    # Step 10: Verify new ExitNodes configuration matches expected
    config_reply = send_command(stream, "GETCONF ExitNodes")
    print(f"New exit configuration: {' '.join(config_reply)}")

    actual_line = None
    for item in config_reply:
    if item.startswith("250 ExitNodes="):
    actual_line = item
    break

    if not actual_line:
    raise RuntimeError("Could not verify the new ExitNodes configuration.")

    actual_text = actual_line.replace("250 ExitNodes=", "")
    actual_nodes = [
    fp.strip().lstrip("$").upper() for fp in actual_text.split(",") if fp
    ]
    expected_nodes = [
    fp.strip().lstrip("$").upper()
    for fp in profile["exit_nodes"].split(",")
    if fp
    ]

    if set(actual_nodes) != set(expected_nodes):
    raise RuntimeError("ExitNodes verification failed: fingerprint mismatch.")
    print("ExitNodes verification: Match")

    allowed = {fp: True for fp in expected_nodes}

    # Step 11: Inspect circuit-status and compare exit fingerprints
    circuit_reply = send_command(stream, "GETINFO circuit-status")
    print("\nGeneral-purpose circuits")
    print("-------------------------")

    found = False
    for line in circuit_reply:
    if "BUILT" not in line or "PURPOSE=GENERAL" not in line:
    continue
    fields = line.split()
    if len(fields) < 3:
    continue

    circuit_id = fields[0]
    hops = fields[2].split(",")
    last_hop = hops[-1].split("~")[0].lstrip("$").upper()
    found = True

    print(f"\nCircuit: {circuit_id}")
    print(f"Exit fingerprint: {last_hop}")
    if last_hop in allowed:
    print("Profile comparison: Match")
    else:
    print("Profile comparison: Not in profile")

    if not found:
    print("No built general-purpose circuits found.")

    print("\nCircuit inspection complete.")
    print("Tor control session completed successfully.")

    # Step 12: Output final success message and pause before exit
    print("\ntorset completed successfully.")
    input("Press Enter to continue . . . ")


    if __name__ == "__main__":
    main()
    # ---------------------------------------------------------------------
    # end of torset.py
    # ---------------------------------------------------------------------
    --
    Every Usenet post should strive to add palpable additional value
    so that we can all delight in dissemination of useful knowledge.
    --- Synchronet 3.22a-Linux NewsLink 1.2
  • From Maria Sophia@mariasophia@comprehension.com to comp.lang.python,alt.comp.os.windows-11,comp.sys.mac.system on Tue Nov 10 16:16:35 2026
    From Newsgroup: comp.sys.mac.system

    If others want to try it out, here's the latest torset python script.
    To give people more options, I added five different sets of choices.

    Since we don't want everyone using the same exit nodes, I removed the
    actual exit nodes, replacing with dummy nodes, to avoid that happening.

    Exit-node fingerprints should be personally selected, which is easy for
    your country of choice using this site to find known good exit nodes.
    <https://metrics.torproject.org> then select "Relay Search" at bottom

    #!/usr/bin/env python3
    # ---------------------------------------------------------------------
    # python torset.py
    # Manually set static known Tor exit nodes for stable web-login accounts
    # ---------------------------------------------------------------------
    # Usage notes:
    # 1. Obtain a set of desired known-to-be-working US Tor exit relays:
    # https://metrics.torproject.org/rs.html#search/country:us%20flag:exit
    # 2. Enter exit-node fingerprints in the profile definitions, e.g.,
    # Profile 1 (gmail)
    # "$0XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    # Profile 2 (protonmail)
    # "$1XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,"
    # "$2XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    # Profile 3 (facebook)
    # "$3XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,"
    # "$4XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    # "$5XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,"
    # Profile 4 (youtube)
    # "$6XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,"
    # "$7XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,"
    # "$8XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,"
    # "$9XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    # Profile 5 (twitter)
    # "$10XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXL:w
    # 3. Run this script, which cleans stale sessions before starting
    # Tor and then provides a choice of pre-selected exit nodes
    # ---------------------------------------------------------------------
    # v3p1 20261109 Added examples for profiles with from 1 to 5 exit nodes
    # v3p0 20261109 Replaced socket/stream cleanup with Python context managers
    # v2p9 20261109 Added sys.platform support for macOS and Linux paths
    # v2p8 20261109 Reverted profile exit nodes back to original configurations
    # v2p7 20261108 Converted native batch/PowerShell implementation to Python
    # v2p6 20261108 Improved documentation in terms of technical accuracy
    # v2p5 20261108 Added new exit nodes and a profile configuration check
    # v2p4 20261108 Handled stale process cleanup cleanly in native batch
    # v2p3 20261108 Added automated cleanup of stale Tor/Firefox instances
    # v2p2 20261108 Added full bootstrap completion polling on cold start
    # v2p1 20261108 Fixed $tcp variable scope in try/finally block
    # v2p0 20261108 Added automated Tor Browser startup and port polling
    # v1p9 20261108 Added ControlPort error handling and response validation
    # v1p8 20261108 Cleaned up comments and clarified explanations
    # v1p7 20261108 Identify general-purpose ckts and compare exit fingerprints
    # v1p6 20261108 Display multi-line Tor circuit status via GETINFO
    # v1p5 20261108 Request new Tor circuits after profile selection
    # v1p4 20261108 Added multi-profile exit-node selection menu
    # v1p3 20261108 Set Profile 1 ExitNodes (two fingerprints) via SETCONF
    # v1p2 20261108 Added GETINFO status/bootstrap-phase
    # v1p1 20261108 Retrieve current ExitNodes configuration via GETCONF
    # v1p0 20261108 Tested Tor ControlPort via TCP cookie authentication
    # ---------------------------------------------------------------------
    # See also... Forces a new working Tor exit node:
    # <https://github.com/gmolop/Tor-ExitNode-changer/>
    # <https://github.com/hevnsnt/IPChanger>
    # <https://gist.github.com/kirelagin/9667900>
    # Interacts with Tor using the Python stem library:
    # <https://pypi.org/project/stem/> <https://stem.torproject.org/>
    # <https://github.com/torproject/stem>
    # Command-line Tor interaction and Nyx monitor:
    # <https://nyx.torproject.org/> <https://github.com/torproject/nyx>
    # Configures Tor using a GUI (Windows only):
    # <https://github.com/abysshint/tor-control-panel/>
    # ---------------------------------------------------------------------
    # Summary:
    # 1. Present a multi-profile selection menu allowing the user to choose
    # between predefined exit-node configurations (or quit with Q).
    # 2. Terminate any stale or running instances of Firefox Tor Browser
    # to ensure a clean starting environment.
    # 3. Launch the Firefox Tor Browser executable automatically if it is
    # not currently running on the system.
    # 4. Poll local TCP port 9151 and monitor for the existence of Tor's
    # control authentication cookie file.
    # 5. Open a local TCP socket connection to Tor's ControlPort
    # (127.0.0.1:9151) once it becomes available.
    # 6. Authenticate the control session securely using the binary bytes
    # read from Tor's local control_auth_cookie.
    # 7. Poll Tor's bootstrap status via GETINFO until the bootstrap-phase
    # reports 100% completion.
    # 8. Apply the user's selected profile fingerprints to Tor's configuration
    # using the SETCONF ExitNodes command.
    # 9. Issue a SIGNAL NEWNYM command to force Tor to discard old circuits
    # and build new ones using the designated exit nodes.
    # 10. Verify that the active ExitNodes configuration matches the expected
    # profile fingerprints.
    # 11. Query active circuits (GETINFO circuit-status), parse their exit node
    # fingerprints and compare them against the profile whitelist.
    # 12. Output clear verification results to the user console and pause
    # before exiting, leaving the configured browser ready for secure use.
    # ---------------------------------------------------------------------
    import os
    import socket
    import subprocess
    import sys
    import time
    from pathlib import Path

    # --- Begin Configuration & Cross-Platform Paths ---
    if sys.platform == "win32":
    COOKIE_PATH = Path(
    r"C:\app\browser\tor\Tor Browser\Browser\TorBrowser\Data\Tor\control_auth_cookie"
    )
    TOR_EXE = Path(r"C:\app\browser\tor\Tor Browser\Browser\firefox.exe")
    KILL_CMD = ["taskkill", "/f", "/im", "firefox.exe"]
    elif sys.platform == "darwin": # macOS
    TOR_EXE = Path.home() / "Applications" / "TorBrowser.app" / "Contents" / "MacOS" / "firefox"
    if not TOR_EXE.is_file():
    TOR_EXE = Path("/Applications/TorBrowser.app/Contents/MacOS/firefox")
    COOKIE_PATH = Path.home() / "Library" / "Application Support" / "TorBrowser-Data" / "Tor" / "control_auth_cookie"
    KILL_CMD = ["pkill", "-f", "torbrowser"]
    else: # Linux and other Unix-likes
    base_linux = Path.home() / ".local" / "share" / "torbrowser" / "tor" / "x86_64" / "tor-browser"
    TOR_EXE = base_linux / "Browser" / "firefox"
    COOKIE_PATH = base_linux / "Browser" / "TorBrowser" / "Data" / "Tor" / "control_auth_cookie"
    KILL_CMD = ["pkill", "-f", "tor-browser"]

    CONTROL_PORT = 9151
    # --- End Configuration & Cross-Platform Paths ---

    # Begin profile dictionary
    PROFILES = {
    "1": {
    "name": "Profile 1 (gmail)",
    "exit_nodes": (
    "$0XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    ),
    },
    "2": {
    "name": "Profile 2 (protonmail)",
    "exit_nodes": (
    "$1XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,"
    "$2XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    ),
    },
    "3": {
    "name": "Profile 3 (facebook)",
    "exit_nodes": (
    "$3XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,"
    "$4XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,"
    "$5XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    ),
    },
    "4": {
    "name": "Profile 4 (youtube)",
    "exit_nodes": (
    "$6XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,"
    "$7XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,"
    "$8XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX,"
    "$9XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    ),
    },
    "5": {
    "name": "Profile 5 (twitter)",
    "exit_nodes": (
    "$10XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    ),
    },
    }
    # End profile dictionary


    def main():
    # Step 1: Profile Selection Menu
    print(" Tor exit node selector ")
    print(" 1 for Profile 1 (gmail)")
    print(" 2 for Profile 2 (protonmail)")
    print(" 3 for Profile 3 (facebook)")
    print(" 4 for Profile 4 (youtube)")
    print(" 5 for Profile 5 (twitter)")
    print(" Q to Quit")
    print()

    choice = input("Select profile [1,2,3,4,5] or Q to quit: ").strip().upper()

    if choice == "Q" or choice not in PROFILES:
    print("Exiting.")
    sys.exit(0)

    profile = PROFILES[choice]
    print(f"\nSetting {profile['name']}...")

    # Step 2: Clean up any stale or running Tor/Firefox instances
    print("Ensuring clean state by stopping any existing Tor instances...")
    try:
    subprocess.run(
    KILL_CMD,
    stdout=subprocess.DEVNULL,
    stderr=subprocess.DEVNULL,
    )
    except Exception:
    pass
    time.sleep(2)

    # Steps 3 & 4: Launch browser if needed and wait for ControlPort & cookie
    if not COOKIE_PATH.is_file():
    print("Tor Browser is not running. Starting Tor Browser automatically...")
    if not TOR_EXE.is_file():
    print(f"ERROR: Tor Browser executable not found at: {TOR_EXE}")
    sys.exit(1)
    subprocess.Popen([str(TOR_EXE)])
    print("Waiting for Tor Browser to initialize and open ControlPort (9151)...")

    start_time = time.time()
    ready = False
    while time.time() - start_time < 45:
    if COOKIE_PATH.is_file():
    try:
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as test_sock:
    test_sock.settimeout(2)
    test_sock.connect(("127.0.0.1", CONTROL_PORT))
    ready = True
    break
    except (socket.error, OSError):
    pass
    time.sleep(2)

    if not ready:
    print(
    "ERROR: Timed out waiting for Tor Browser to start and open ControlPort"
    " 9151."
    )
    sys.exit(1)
    print("Tor Browser port is open.")

    # Step 6: Read authentication cookie bytes
    try:
    cookie_bytes = COOKIE_PATH.read_bytes()
    cookie_hex = cookie_bytes.hex().upper()
    except Exception as e:
    print(f"ERROR: Failed to read control authentication cookie: {e}")
    sys.exit(1)

    # Helper functions for Tor Control Protocol
    def read_tor_reply(sock_file):
    lines = []
    while True:
    line = sock_file.readline()
    if not line:
    raise RuntimeError("Tor closed the ControlPort connection unexpectedly.")
    decoded = line.decode("utf-8", errors="ignore").rstrip("\r\n")
    lines.append(decoded)
    if decoded.startswith("250+"):
    while True:
    data_line = sock_file.readline()
    if not data_line:
    raise RuntimeError(
    "Tor closed the connection during a data response."
    )
    d_decoded = data_line.decode("utf-8", errors="ignore").rstrip(
    "\r\n"
    )
    lines.append(d_decoded)
    if d_decoded == ".":
    break
    continue
    if len(decoded) >= 4 and decoded[3] == "-":
    continue
    break
    return lines

    def send_command(sock_file, command):
    sock_file.write((command + "\r\n").encode("utf-8"))
    sock_file.flush()
    reply = read_tor_reply(sock_file)
    if not reply or not reply[0].startswith("250"):
    raise RuntimeError(f"Tor rejected command: {command} -- {' '.join(reply)}")
    return reply

    # Step 5: Connect to ControlPort using context managers
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.settimeout(15)
    s.connect(("127.0.0.1", CONTROL_PORT))
    with s.makefile("rwb") as stream:

    # Authenticate session
    auth_reply = send_command(stream, f"AUTHENTICATE {cookie_hex}")
    print(f"Authentication: {auth_reply[0]}")

    # Step 7: Wait for Tor bootstrap completion (100%)
    print("Waiting for Tor bootstrap to complete...")
    bootstrap_complete = False
    b_start = time.time()
    while time.time() - b_start < 60:
    try:
    bootstrap_reply = send_command(stream, "GETINFO status/bootstrap-phase")
    for line in bootstrap_reply:
    if "PROGRESS=100" in line:
    bootstrap_complete = True
    break
    if bootstrap_complete:
    break
    except Exception:
    pass
    time.sleep(2)

    if not bootstrap_complete:
    raise RuntimeError("Timed out waiting for Tor to finish bootstrapping.")
    print("Tor bootstrap complete (100%).")

    # Step 8: Apply selected profile ExitNodes via SETCONF
    config_reply = send_command(stream, "GETCONF ExitNodes")
    print(f"Exit configuration: {' '.join(config_reply)}")

    setconf_reply = send_command(
    stream, f"SETCONF ExitNodes={profile['exit_nodes']}"
    )
    print(f"SETCONF response: {setconf_reply[-1]}")

    # Step 9: Signal NEWNYM to clear circuits and build new ones
    newnym_reply = send_command(stream, "SIGNAL NEWNYM")
    print(f"NEWNYM response: {newnym_reply[-1]}")

    time.sleep(3)

    # Step 10: Verify new ExitNodes configuration matches expected
    config_reply = send_command(stream, "GETCONF ExitNodes")
    print(f"New exit configuration: {' '.join(config_reply)}")

    actual_line = None
    for item in config_reply:
    if item.startswith("250 ExitNodes="):
    actual_line = item
    break

    if not actual_line:
    raise RuntimeError("Could not verify the new ExitNodes configuration.")

    actual_text = actual_line.replace("250 ExitNodes=", "")
    actual_nodes = [
    fp.strip().lstrip("$").upper() for fp in actual_text.split(",") if fp
    ]
    expected_nodes = [
    fp.strip().lstrip("$").upper()
    for fp in profile["exit_nodes"].split(",")
    if fp
    ]

    if set(actual_nodes) != set(expected_nodes):
    raise RuntimeError("ExitNodes verification failed: fingerprint mismatch.")
    print("ExitNodes verification: Match")

    allowed = {fp: True for fp in expected_nodes}

    # Step 11: Inspect circuit-status and compare exit fingerprints
    circuit_reply = send_command(stream, "GETINFO circuit-status")
    print("\nGeneral-purpose circuits")
    print("-------------------------")

    found = False
    for line in circuit_reply:
    if "BUILT" not in line or "PURPOSE=GENERAL" not in line:
    continue
    fields = line.split()
    if len(fields) < 3:
    continue

    circuit_id = fields[0]
    hops = fields[2].split(",")
    last_hop = hops[-1].split("~")[0].lstrip("$").upper()
    found = True

    print(f"\nCircuit: {circuit_id}")
    print(f"Exit fingerprint: {last_hop}")
    if last_hop in allowed:
    print("Profile comparison: Match")
    else:
    print("Profile comparison: Not in profile")

    if not found:
    print("No built general-purpose circuits found.")

    print("\nCircuit inspection complete.")
    print("Tor control session completed successfully.")

    # Step 12: Output final success message and pause before exit
    print("\ntorset completed successfully.")
    input("Press Enter to continue . . . ")


    if __name__ == "__main__":
    main()
    # ---------------------------------------------------------------------
    # end of torset.py
    # ---------------------------------------------------------------------
    --
    Usenet is where well-educated intelligent friendly people daily gather to discuss topics of interest and to help learn from each other every day.
    --- Synchronet 3.22a-Linux NewsLink 1.2
  • From Keith Thompson@Keith.S.Thompson+u@gmail.com to comp.lang.python,alt.comp.os.windows-11,comp.sys.mac.system on Tue Nov 10 15:35:18 2026
    From Newsgroup: comp.sys.mac.system

    Maria Sophia <mariasophia@comprehension.com> writes:
    If others want to try it out, here's the latest torset python script.
    To give people more options, I added five different sets of choices.

    Since we don't want everyone using the same exit nodes, I removed the
    actual exit nodes, replacing with dummy nodes, to avoid that happening.

    Exit-node fingerprints should be personally selected, which is easy for
    your country of choice using this site to find known good exit nodes.
    <https://metrics.torproject.org> then select "Relay Search" at bottom

    #!/usr/bin/env python3
    [382 lines deleted]

    Usenet is a very bad way to distribute source code. I can't just
    download a source file; I have to save the article and manually
    extract it. There's a risk that some software along the way will
    fold long lines or mess up tabs and spaces, which are of course
    semantically significant in Python. If you post a new version,
    there's no good way to see what's changed.

    If you want to share your source code, I urge you to set up a
    repository that you can update with new versions. GitHub is the
    most popular site, but there are alternatives. You can always post
    links here.
    --
    Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com
    void Void(void) { Void(); } /* The recursive call of the void */
    --- Synchronet 3.22a-Linux NewsLink 1.2
  • From Blaine@cactus_DAC@yahoo.com to comp.lang.python,alt.comp.os.windows-11,comp.sys.mac.system on Tue Nov 10 16:50:43 2026
    From Newsgroup: comp.sys.mac.system

    Keith Thompson wrote:
    Maria Sophia <mariasophia@comprehension.com> writes:
    If others want to try it out, here's the latest torset python script.
    To give people more options, I added five different sets of choices.

    Since we don't want everyone using the same exit nodes, I removed the
    actual exit nodes, replacing with dummy nodes, to avoid that happening.

    Exit-node fingerprints should be personally selected, which is easy for
    your country of choice using this site to find known good exit nodes.
    <https://metrics.torproject.org> then select "Relay Search" at bottom

    #!/usr/bin/env python3
    [382 lines deleted]

    Usenet is a very bad way to distribute source code. I can't just
    download a source file; I have to save the article and manually
    extract it. There's a risk that some software along the way will
    fold long lines or mess up tabs and spaces, which are of course
    semantically significant in Python. If you post a new version,
    there's no good way to see what's changed.

    If you want to share your source code, I urge you to set up a
    repository that you can update with new versions. GitHub is the
    most popular site, but there are alternatives. You can always post
    links here.

    What about usenet attachments? I know they don't work for binaries, but doesn't it allow text attachments?
    --
    Hits like a Phillips head into my brain
    It's gonna be too dark to sleep again
    Cutting my teeth on bars and rusty chains
    I'm gonna break my rusty cage And run
    --- Synchronet 3.22a-Linux NewsLink 1.2