python脚本获取本机(主机)(公网)IP地址

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_29757283/article/details/80106364

===== 更新:

原文代码是在LINUX下的python3解释器中一行一行测试的。

更新代码整理成一个 getWANIP.py 的脚本文件。并放到了 github上,几行命令就可以直接使用和测试。

$ 
$ wget https://raw.githubusercontent.com/RDpWTeHM/RaspberryPi/master/RaspberryPi-script/RPiManaged/getWANIP/getWANIP.py
$ chmod +x getWANIP.py
$ 
$ ## 运行脚本,获得到 WAN IP 并直接打印到标准输出
$ ./getWANIP.py 
get HTML text OK!
153.35.***.***
$

如果运行 `$ ./getWANIP.py` 提示 import 相关错误, 

需要先安装相关库:

$
$ sudo pip3 install requests
$ sudo pip3 install beautifulsoup4
$

==== 原文:

Note: 一般主机是接在路由器后面, 所以分配到的是私网的IP 地址,路由器的WAN端是公网IP地址。

         如果运营商使用NAT进一步分配的话,那么路由的WAN段一般是10.0.0.0/4 网段的私网IP 地址,

        但是不论如何, 能上网自然主机的出口是会有一个公网IP的。通过搜索引擎输入IP查询到的正是这个IP地址。

这里以百度搜索引擎为例,通过Python 脚本,获取主机上网的公网 IP

获取 HTML 代码:
		 kv = { 'wd':'IP' }
		
		r = requests.get("http://www.baidu.com/s", params=kv )
		
		r.status_code
		
		len ( r.text )
		
		r.encoding = r.apparent_encoding   # 字符串长的时候, 这会占用一定时间
		                                   # (处理器性能弱的时候)
		
		
		htmlData = r.text
		
		
		
		
		
		 
	Ø 假设已经获取到了 网页的 html 代码
		保持在 htmlData 变量名中
		
		-- 提取body:
		bodyData = htmlData[htmlData.find("<body"):htmlData.find("</body")]
		
		bodyData = '<html><head></head>' + bodyData + '</body></html>'
		
		# print bodyData
		
		
		BodySoup = BeautifulSoup( bodyData, "html.parser" )
		
		
		-- 提取主要段落:
		
		result = BodySoup.find_all( 'div', attrs='result-op c-container' )
		
		# type(result)
		
		result = list(result)  # turn set to list type
		
		RequestsResult = result[0]
		
		Str = "%s" % RequestsResult.span
		
		# print (Str)
		# <span class="c-gap-right">本机IP: 1x2.1x3.1x5.2xx</span>
		
		# 注意,Str 必须是正确的值才好进入下一步的字符串处理。这边是在解释器模式下的测试+代码记录在CSDN上,所以实际情况有一定的可能性不会那么刚好在第一个span标签就是上面所示的字符串。
		
	Ø  提取 IP 值:
		ipSoup = BeautifulSoup ( Str, "html.parser" )
		
		ipStrKV = ipSoup.span.string
		
		# print ipStrKV
		# 本机IP: 1x2.1x3.1x5.2xx
		# >>> ipStrKV
		# '本机IP:\xa01x2.1x3.1x5.2xx'
		# >>>
		#
		
		### ipKV = **ipStrKV**
		### ipStr = ipKV.get("本机IP")
		
		
		( ipKey, ipValue) = ipStrKV.split(":") 
		
		# >>> 
		# >>> ipKey
		# '本机IP'
		# >>> ipValue
		# '\xa01x2.1x3.1x5.2xx'
		# >>> 
		# >>> print ( ipValue )
		#  122.1x3.1x5.2xx
		# >>> 
		# >>> 
		# >>> ipValue[0]
		# '\xa0'
		# >>> 
		# >>> 
		
		def getIPstr( srcIP ) :
			dst = ''
			for i in range( len(srcIP) ):
				if srcIP[i].isdigit() or srcIP[i]=='.' :
					dst = dst + srcIP[i]
				else:
					pass
				# END if ... else ...
			# END for.
			return dst
		# END def.
		
		# >>> 
		# >>> ipStr = getIPstr(ipValue)
		# >>> ipStr
		# '122.1x3.195.2xx'
		# >>> 
		# >>> 
		

猜你喜欢

转载自blog.csdn.net/qq_29757283/article/details/80106364
今日推荐