python编写的ip检测工具
本帖最后由 顺其自然1231 于 2020-4-23 12:59 编辑由于使用的某个产品需要设定公网白名单才能访问(如某些api),故每次使用前需要查询自己的公网ip,比较麻烦,于是用python写了一个简单的工具用于快速查询当前设备下的公网ip和局域ip。成果如下:
http://p3.pstatp.com/large/pgc-image/fb30b768475b40d48b4cda94b4424f5c
http://p3.pstatp.com/large/pgc-image/d30b2db80a9a489cb16eb1805228613b
import requests
import re
import socket
import platform
import PySimpleGUI as sg
import pyperclip
import time
import os
import json
def get_public_ip():
"""
此函数用于获取当前设备下的公网ip
:return:公网ip地址
"""
public_ip1 = '0.0.0.0'
for ii in range(3):
try:
response = requests.get('http://myip.kkcha.com/', timeout=10)
html = response.text
p = re.compile('var sRemoteAddr = \'(.*?)\'')
result = p.search(html)
public_ip1 = result.group(1)
break
except Exception as err:
print(err)
time.sleep(5)
return public_ip1
def get_private_ip():
"""
此函数用于获取局域网Ip
:return:
"""
s = None
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('www.baidu.com', 0))
ip = s.getsockname()[0]
except Exception as err:
print(err)
ip = "x.x.x.x"
finally:
s.close()
return ip
def get_sys_info():
"""
此函数用于返回当前设备系统信息,并且返回相应的局域网ip
:return:sys_str,系统信息,ip_address,局域网ip地址
"""
ip_address = "0.0.0.0"
sys_str = platform.system()
if sys_str == "Windows":
ip_address = socket.gethostbyname(socket.gethostname())
elif sys_str == "Linux":
ip_address = get_private_ip()
elif sys_str == "Darwin":
ip_address = socket.gethostbyname(socket.gethostname())
else:
print("Other System @ some ip")
return sys_str, ip_address
def load_data(path1='./data/data.json'):
"""
用于加载公网ip列表
:param path1: 保存路径
:return:
"""
dir_name = os.path.dirname(path1)
if not os.path.exists(dir_name):# 如果文件夹不存在
os.mkdir(dir_name)# 创建文件夹
if not os.path.exists(path1):# 如果文件路径不存在
with open(path1, 'wt', encoding='utf-8') as f:
list1 = []
json.dump(obj=list1, fp=f)
return []
else:
with open(path1, 'rt', encoding='utf-8') as f:
list1 = json.load(f)
f.close()
return list1
def save_data(list1, path1='./data/data.json'):
"""
此函数用于储存数据到json中
:param list1: Ip数据
:param path1: json路径
:return:
"""
with open(path1, 'wt+', encoding='utf-8') as f:
json.dump(list1, f)
f.close()
if __name__ == "__main__":
system_info, local_ip = get_sys_info()# 获取系统信息和局域网ip
public_ip = get_public_ip() # 获取公网ip地址
# -- 开始构件GUI --#
# 设置自定义字体
my_font = 'Deja_Vu_Sans_Mono.ttf'
my_font_style1 = (my_font, 11, "normal")
layout = [
'当前系统:'), sg.Text(system_info)],
'局域网ip:'), sg.Text(local_ip), sg.Button('复制1')],
'公网ip:'), sg.Text(public_ip), sg.Button('复制2')],
'检测ip变动'), sg.Button('退出')]
]
windows = sg.Window('python网络查询工具', layout=layout, font=my_font_style1, size=(300, 140))
for i in range(5):
event, values = windows.read()
if event in (None, '退出'):
break
elif event == '复制1':
try:
pyperclip.copy(local_ip)
except Exception as err:
if system_info == 'Linux':
sg.popup('错误,你的系统可能缺少相应安装包',
'请输入以下指令安装相关依赖',
'sudo apt-get install xsel xclip', title='错误', font=my_font_style1)
else:
sg.popup(err)
elif event == '复制2':
try:
pyperclip.copy(public_ip)
except Exception as err:
if system_info == 'Linux':
sg.popup('错误,你的系统可能缺少相应安装包',
'请输入以下指令安装相关依赖',
'sudo apt-get install xsel xclip', title='错误',font=my_font_style1)
else:
sg.popup(err)
elif event == '检测ip变动':
list2 = load_data()# 加载ip列表
if len(list2) == 0:# 如果为空
sg.popup('当前Ip列表为空,请重新点击', title='提示', auto_close=True,
auto_close_duration=3, font=my_font_style1)
list2.append(public_ip)
save_data(list2)
elif public_ip in list2:# 如果Ip在集合中
sg.popup('ip未发生变动', auto_close=True, auto_close_duration=4, title='提示', font=my_font_style1)
sg.popup('历史Ip为', list2, auto_close=True,
auto_close_duration=4, title='提示',
font=my_font_style1)
elif public_ip not in list2:
sg.popup('ip发生变化', auto_close=True, auto_close_duration=3, title='提示', font=my_font_style1)
list2.append(public_ip)
save_data(list2)
windows.close()
成品下载地址:
https://github.com/Tlntin/ip_tools/releases
V1.02最新版蓝奏云地址:https://lanzouj.com/ibt9d0h
最新版增加了ip变动检测功能。
V1.02增加了进度条,增加了一条查询线路,增加重新检测按钮,增加了多线程快速抓取(也可能变慢),减少失败几率。
帮你把代码格式调了下,有些显示不清楚
import requests
import re
import socket
import platform
import PySimpleGUI as sg
import pyperclip
import time
import os
import json
def get_public_ip():
"""
此函数用于获取当前设备下的公网ip
:return:公网ip地址
"""
public_ip1 = '0.0.0.0'
for ii in range(3):
try:
response = requests.get('http://myip.kkcha.com/', timeout=10)
html = response.text
p = re.compile('var sRemoteAddr = \'(.*?)\'')
result = p.search(html)
public_ip1 = result.group(1)
break
except Exception as err:
print(err)
time.sleep(5)
return public_ip1
def get_private_ip():
"""
此函数用于获取局域网Ip
:return:
"""
s = None
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('www.baidu.com', 0))
ip = s.getsockname()
except Exception as err:
print(err)
ip = "x.x.x.x"
finally:
s.close()
return ip
def get_sys_info():
"""
此函数用于返回当前设备系统信息,并且返回相应的局域网ip
:return:sys_str,系统信息,ip_address,局域网ip地址
"""
ip_address = "0.0.0.0"
sys_str = platform.system()
if sys_str == "Windows":
ip_address = socket.gethostbyname(socket.gethostname())
elif sys_str == "Linux":
ip_address = get_private_ip()
elif sys_str == "Darwin":
ip_address = socket.gethostbyname(socket.gethostname())
else:
print("Other System @ some ip")
return sys_str, ip_address
def load_data(path1='./data/data.json'):
"""
用于加载公网ip列表
:param path1: 保存路径
:return:
"""
dir_name = os.path.dirname(path1)
if not os.path.exists(dir_name):# 如果文件夹不存在
os.mkdir(dir_name)# 创建文件夹
if not os.path.exists(path1):# 如果文件路径不存在
with open(path1, 'wt', encoding='utf-8') as f:
list1 = []
json.dump(obj=list1, fp=f)
return []
else:
with open(path1, 'rt', encoding='utf-8') as f:
list1 = json.load(f)
f.close()
return list1
def save_data(list1, path1='./data/data.json'):
"""
此函数用于储存数据到json中
:param list1: Ip数据
:param path1: json路径
:return:
"""
with open(path1, 'wt+', encoding='utf-8') as f:
json.dump(list1, f)
f.close()
if __name__ == "__main__":
system_info, local_ip = get_sys_info()# 获取系统信息和局域网ip
public_ip = get_public_ip() # 获取公网ip地址
# -- 开始构件GUI --#
# 设置自定义字体
my_font = 'Deja_Vu_Sans_Mono.ttf'
my_font_style1 = (my_font, 11, "normal")
layout = [
,
,
,
]
windows = sg.Window('python网络查询工具', layout=layout, font=my_font_style1, size=(300, 140))
for i in range(5):
event, values = windows.read()
if event in (None, '退出'):
break
elif event == '复制1':
try:
pyperclip.copy(local_ip)
except Exception as err:
if system_info == 'Linux':
sg.popup('错误,你的系统可能缺少相应安装包',
'请输入以下指令安装相关依赖',
'sudo apt-get install xsel xclip', title='错误', font=my_font_style1)
else:
sg.popup(err)
elif event == '复制2':
try:
pyperclip.copy(public_ip)
except Exception as err:
if system_info == 'Linux':
sg.popup('错误,你的系统可能缺少相应安装包',
'请输入以下指令安装相关依赖',
'sudo apt-get install xsel xclip', title='错误',font=my_font_style1)
else:
sg.popup(err)
elif event == '检测ip变动':
list2 = load_data()# 加载ip列表
if len(list2) == 0:# 如果为空
sg.popup('当前Ip列表为空,请重新点击', title='提示', auto_close=True,
auto_close_duration=3, font=my_font_style1)
list2.append(public_ip)
save_data(list2)
elif public_ip in list2:# 如果Ip在集合中
sg.popup('ip未发生变动', auto_close=True, auto_close_duration=4, title='提示', font=my_font_style1)
sg.popup('历史Ip为', list2, auto_close=True,
auto_close_duration=4, title='提示',
font=my_font_style1)
elif public_ip not in list2:
sg.popup('ip发生变化', auto_close=True, auto_close_duration=3, title='提示', font=my_font_style1)
list2.append(public_ip)
save_data(list2)
windows.close() 这个工具很实用,支持! 很有意思的程序 sg函数就可以写图形化了? 感谢分享,学习了 0xkevin 发表于 2020-4-19 23:24
sg函数就可以写图形化了?
pysimpleGUI,这个模块可以。比较轻巧。不太喜欢tinker.
感谢分享,有用 试了一下,好像可用,但我双外网(电信+联通),只测到电信,选择“线路1”或“线路2”结果无区别,请指导,谢谢 小工具用着还可以把 hfxiang 发表于 2020-4-23 14:32
试了一下,好像可用,但我双外网(电信+联通),只测到电信,选择“线路1”或“线路2”结果无区别,请指导 ...
双外网应该也只能有一个公网Ip吧。二选一。
类似插两个无线网卡,最后生效的也只有一个