[英]How can I install pyautogui on a Debian environnement on a Python2.7?
[英]How can I get the public IP using python2.7?
如何使用 python2.7 獲取公共 IP? 不是私有IP。
目前有幾種選擇:
以下是您可以利用上述每種方法的確切方法。
from urllib2 import urlopen
my_ip = urlopen('http://ip.42.pl/raw').read()
這是我找到的第一個選項。 腳本很方便,這里不需要JSON解析。
from json import load
from urllib2 import urlopen
my_ip = load(urlopen('https://ipv4.jsonip.com'))['ip']
看起來這個域的唯一目的是以 JSON 格式返回 IP 地址。
from json import load
from urllib2 import urlopen
my_ip = load(urlopen('http://httpbin.org/ip'))['origin']
httpbin.org 是我經常推薦給初級開發人員用於測試他們的腳本/應用程序的服務。
from json import load
from urllib2 import urlopen
my_ip = load(urlopen('https://api.ipify.org/?format=json'))['ip']
這項服務的強大源於缺乏限制(沒有速率限制)、基礎設施(放置在 Heroku 上,考慮到高可用性)和靈活性(適用於 IPv4 和 IPv6)。
編輯:將httpbin.org添加到可用選項列表中。
我喜歡http://ip.42.pl/raw的 requests 包
import requests
requests.get('http://ip.42.pl/raw').text
帶有請求模塊
import requests
public_IP = requests.get("https://www.wikipedia.org").headers["X-Client-IP"]
print public_IP
嘗試這個:
import ipgetter
import requests
IP = ipgetter.myip()
url = 'http://freegeoip.net/json/'+IP
r = requests.get(url)
js = r.json()
print 'IP Adress: ' + js['ip']
print 'Country Code: ' + js['country_code']
print 'Country Name: ' + js['country_name']
print 'Region Code: ' + js['region_code']
print 'Region Name: ' + js['region_name']
print 'City Name: ' + js['city']
print 'Zip code: ' + js['zip_code']
print 'Time Zone: ' + js['time_zone']
print 'Latitude: ' + str(js['latitude'])
print 'Longitude: ' + str(js['longitude'])
你可以這樣做:
import requests
print requests.get("http://ipecho.net/plain?").text
產生:
XX.XX.XXX.XXX
在 python 2.7 中,它只是兩行代碼。
>>> import requests
>>print requests.get("http://ipconfig.in/ip").text
Getip是一個小模塊,它從隨機服務器返回公共IP地址。
安裝:
〜$ pip install getip2
使用:
>> import getip
>> ip = getip.get()
>>
>> ip
'66.249.76.109'
這是一種不必撥打互聯網電話的方法:
如果這不起作用,請告訴我,然后我可以更新答案(它適用於我的約 10 台服務器)
from subprocess import check_output
out = check_output("/sbin/ifconfig | awk '/inet / { print $2 }' | sed 's/addr://'", shell=True)
[x for x in out.decode().split() if not x == "127.0.0.1" and
not (x.startswith("172") and x.endswith("0.1"))]
["x.x.x.x.x"]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.