python脚本获取本机公网ip

时间:2023-03-09 16:19:53
python脚本获取本机公网ip

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

2.python脚本实现:

 #!/usr/bin/python
# -*- coding:utf8 -*-
# By 飞走不可 import urllib2 url = urllib2.urlopen("http://txt.go.sohu.com/ip/soip")
text = url.read()
key1 = 'user_ip'
key2 = ';'
s = text.find(key1)
e = text.find(key2,s)
IP = text[s:e]
print IP

3.群里大神给修改后:

 #!/usr/bin/python
# -*- coding:utf8 -*- import urllib2
import re url = urllib2.urlopen("http://txt.go.sohu.com/ip/soip")
text = url.read()
ip = re.findall(r'\d+.\d+.\d+.\d+',text) print ip[]

4.另外,shell方式:

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