python脚本获取本机公网ip

1.获取公网IP地址方式,访问:http://txt.go.sohu.com/ip/soip

2.python脚本实现:

 1 #!/usr/bin/python
 2 # -*- coding:utf8 -*-
 3 # By 飞走不可
 4 
 5 import urllib2
 6 
 7 url = urllib2.urlopen("http://txt.go.sohu.com/ip/soip")
 8 text = url.read()
 9 key1 = 'user_ip'
10 key2 = ';'
11 s = text.find(key1)
12 e = text.find(key2,s)
13 IP = text[s:e]
14 print IP

3.群里大神给修改后:

 1 #!/usr/bin/python
 2 # -*- coding:utf8 -*-
 3 
 4 import urllib2
 5 import re
 6 
 7 url = urllib2.urlopen("http://txt.go.sohu.com/ip/soip")
 8 text = url.read()
 9 ip = re.findall(r'\d+.\d+.\d+.\d+',text)
10 
11 print ip[0]

4.另外,shell方式:

 1 echo $(curl -s http://txt.go.sohu.com/ip/soip)| grep -P -o -i "(\d+\.\d+.\d+.\d+)" 

 

在学习python中,感觉找不到头绪,好可怜。。。。

放上大神的blog:http://kinggoo.com/ob-ip.htm

转载于:https://www.cnblogs.com/hanyifeng/p/4918301.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值