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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM