Created
May 26, 2020 06:02
-
-
Save simonkuang/9895b60853e246cc76bbd5d0bb060580 to your computer and use it in GitHub Desktop.
获取本地 IP 并上报服务器。用于内网环境服务器重启后,IP 变化,无法远程的场景。上报服务器最好是固定 IP 并提供 http 服务。可用 pyinstaller 打包。
This file contains 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
# -*- coding: utf-8 -*- | |
import os | |
import socket | |
import time | |
import urllib | |
import urllib.parse | |
import urllib.request | |
from pprint import pprint as pp | |
def get_host_ip(): | |
""" | |
查询本机ip地址 | |
:return: ip | |
""" | |
ip = None | |
try: | |
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) | |
s.connect(('8.8.8.8', 80)) | |
ip = s.getsockname()[0] | |
finally: | |
s.close() | |
return ip | |
def report_ip(ip): | |
""" | |
上报 IP | |
""" | |
msg = urllib.parse.quote("This is the testing hosts ip from local network.") | |
url = "https://api.xxxx.com/report/ip?ip={}&msg={}".format(ip, msg) | |
#pp(url) | |
req = urllib.request.Request(url) | |
response = urllib.request.urlopen(req) | |
msg = response.read() | |
if msg == 'ok': | |
return True | |
else: | |
return False | |
def test_network(): | |
""" | |
测试网络是否连通 | |
""" | |
exit_code = os.system(u'ping www.baidu.com') | |
if exit_code: | |
return False | |
else: | |
return True | |
def mtime(): | |
""" | |
获取毫秒时间戳 | |
""" | |
return int(round(time.time() * 1000)) | |
def loop(): | |
linked = test_network() | |
if linked: # network linked | |
ip = get_host_ip() | |
if ip: | |
[report_ip(ip) for i in range(3)] # try to report 3 times | |
return True | |
else: | |
return False | |
else: | |
now = mtime() | |
if now - start_time > threhold: | |
return False | |
time.sleep(5) | |
loop() | |
return True | |
if __name__ == '__main__': | |
start_time = mtime() | |
threhold = 30 * 60 * 1000 # 30 min | |
loop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment