Python获取外网ip,并且保存到本地。
如下图:
由于刚学Python,代码写的很粗糙。各位大佬轻点踩。
import json
import os
try:
from urllib.request import urlopen
from urllib.request import Request
from urllib.error import URLError
from urllib.error import HTTPError
except ImportError:
from urllib2 import urlopen
from urllib2 import Request
from urllib2 import HTTPError
from urllib2 import URLError
ip_file = 'c://ip.txt';
ip = '';
public_ipv4 = '';
#创建文件的方法
def createFile(ip_file,msg):
file = open(ip_file, 'w')
file.write(msg)
file.close;
#判断文件是否存在
if os.path.isfile(ip_file):
print '文件存在'
else:
print '文件不存在';
createFile(ip_file, '127.0.0.1')
# 打开一个文件
fo = open(ip_file, "r+");
ip = fo.read();
print "读取的字符串是 : ", ip;
# 关闭打开的文件
fo.close();
#判断地址是否为空
if ip!="":
print 'ip地址不是空';
else:
print 'ip地址是空的';
#获取网络ip
try:
public_ipv4 = urlopen(Request('http://ipv4.icanhazip.com/')).read().rstrip().decode('utf-8');
print '获取网络上的ip:',public_ipv4;
#比较本地ip跟网络ip是否一致
if ip==public_ipv4:
print 'ip一致';
else:
print 'ip不一致';
#将网络上的ip写入到文件
# 打开文件
fo = open(ip_file, "w")
fo.write(public_ipv4)
# 关闭文件
fo.close()
except URLError as e:
print('* no public IPv4 address detected');
exit(0);