Skip to content

Instantly share code, notes, and snippets.

@mengskysama
Last active August 13, 2023 17:30
Show Gist options
  • Save mengskysama/812735eafa87c85c31c06e28ab231f28 to your computer and use it in GitHub Desktop.
Save mengskysama/812735eafa87c85c31c06e28ab231f28 to your computer and use it in GitHub Desktop.
import subprocess
import re
import os
import sys
import time
import logging
from logging.handlers import RotatingFileHandler
logger = logging.getLogger('main')
logger.setLevel(logging.DEBUG)
handler = RotatingFileHandler("/tmp/dial_cn2.log",
maxBytes=5*1024*1024,
backupCount=1)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
ppp_if = 'pppoe-wan'
def get_wan_ip():
out = ''
try:
out = subprocess.check_output(["ifconfig", ppp_if]).decode('utf-8')
except:
pass
r = re.search(r'inet addr:(\d+\.\d+\.\d+\.\d+)', out)
if not r:
return ''
return r.group(1)
def wan_is_cn2():
ip = get_wan_ip()
if not ip:
return False
if ip.startswith('58.32.3') or ip.startswith('58.32.1') or ip.startswith('58.32.2'):
return True
return False
def redial():
os.system('ifdown wan && ifup wan')
max_wait = 30
while max_wait > 0:
max_wait -= 1
if get_wan_ip():
return
time.sleep(1)
logger.info('redial failed get ip timeout')
def dial_cn2(max_retry: int):
ip = get_wan_ip()
logger.info('wan ip is %s', ip)
if wan_is_cn2():
return
while max_retry > 0:
max_retry -= 1
logger.info('start dial ...')
redial()
ip = get_wan_ip()
if ip:
logger.info('wan ip is %s', ip)
if wan_is_cn2():
exit(0)
if __name__ == '__main__':
max_retry = 30
if len(sys.argv) == 2:
max_retry = int(sys.argv[1])
dial_cn2(max_retry)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment