Last active
July 7, 2023 18:42
-
-
Save b-simjoo/6a077c66ef6c056baa2220763b038959 to your computer and use it in GitHub Desktop.
Proxy agent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /usr/bin/python3 | |
# I wrote this script so that my personal computer running Ubuntu | |
# always has an active connection with the proxy server. | |
# | |
# Note that I am using my ssh config file, you can define a host there or | |
# you can type the whole command here | |
import notify2 | |
import requests | |
from subprocess import Popen, run, TimeoutExpired | |
from time import sleep | |
SSH_TIMEOUT = 8 | |
SSH_COMMAND = ["ssh", "proxy", "-o", f"ConnectTimeout={SSH_TIMEOUT}"] | |
PROXY = "socks5h://localhost:9090" | |
connection_log = True | |
ex_count = 0 | |
def connected(use_proxy=False) -> bool: | |
global ex_count, t_out | |
try: | |
if use_proxy: | |
res = requests.get( | |
"http://google.com", | |
timeout=(8, 7), | |
proxies=dict( | |
http=PROXY, | |
https=PROXY, | |
), | |
) | |
else: | |
res = requests.get("http://google.com", timeout=(7, 5)) | |
ex_count = 0 | |
return res.status_code == requests.codes.ok | |
except Exception as ex: | |
ex_count += 1 if ex_count < 5 else 0 | |
t_out = 1 | |
sleep(ex_count) | |
return False | |
def ping(host): | |
res = run(["ping", "-c", "3", "-W", "3", host]) | |
return res.returncode == 0 | |
if __name__ == "__main__": | |
notify2.init("proxy agent") | |
while True: | |
try: | |
while not ping("google.com"): | |
pass | |
proxy_proc = Popen(SSH_COMMAND) | |
try: | |
proxy_proc.wait(SSH_TIMEOUT) | |
except TimeoutExpired: | |
pass | |
else: | |
continue | |
if connected(use_proxy=True): | |
notify2.Notification("Proxy agent", "Proxy connected").show() | |
else: | |
if proxy_proc.poll() is None: | |
proxy_proc.kill() | |
continue | |
error = 0 | |
while error < 3: | |
error = 0 if connected(use_proxy=True) else error + 1 | |
notify2.Notification( | |
"Proxy agent", "Proxy connection failed, Retrying...", "error" | |
).show() | |
if proxy_proc.poll() is None: | |
proxy_proc.kill() | |
except Exception as ex: | |
notify2.Notification( | |
"Proxy agent", f"Unhandled Exception:\n{ex}", "error" | |
).show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment