programing

Python으로 머신의 외부 IP 주소 가져 오기

projobs 2021. 1. 17. 10:23
반응형

Python으로 머신의 외부 IP 주소 가져 오기


머신의 현재 외부 IP를 얻는 더 나은 방법을 찾고 있습니다. # ... 아래는 작동하지만 정보를 수집하기 위해 외부 사이트에 의존하지 않습니다 ... Mac OS에 번들로 제공되는 표준 Python 2.5.1 라이브러리를 사용하도록 제한됩니다. X 10.5.x

import os
import urllib2

def check_in():

    fqn = os.uname()[1]
    ext_ip = urllib2.urlopen('http://whatismyip.org').read()
    print ("Asset: %s " % fqn, "Checking in from IP#: %s " % ext_ip)

외부 IP를 얻는 라우터 뒤에있는 경우에는 다른 방법이 없으시 겠지만 외부 서비스를 사용할 수밖에 없습니다. 라우터 자체에 쿼리 인터페이스가있는 경우 사용할 수 있지만 솔루션은 환경에 따라 매우 다르며 신뢰할 수 없습니다.


http://ipify.org를 좋아했습니다 . API 사용을위한 Python 코드도 제공합니다.

# This example requires the requests library be installed.  You can learn more
# about the Requests library here: http://docs.python-requests.org/en/latest/

from requests import get

ip = get('https://api.ipify.org').text
print 'My public IP address is:', ip

표준 라이브러리 만 사용하는 Python3

앞서 언급했듯이 라우터의 외부 IP 주소를 찾기 위해 https://ident.me 와 같은 외부 서비스를 사용할 수 있습니다 .

다음은 표준 라이브러리python3 만 사용하여으로 수행되는 방법입니다 .

import urllib.request

external_ip = urllib.request.urlopen('https://ident.me').read().decode('utf8')

print(external_ip)

이 정보에 대해 라우터를 쿼리 하려면 UPnP 프로토콜사용해야합니다 . 가장 중요한 것은이 질문에 대한 다른 모든 답변이 제안하는 것처럼 보이는 외부 서비스에 의존하지 않는다는 것입니다.

이를 수행 할 수있는 miniupnp라는 Python 라이브러리가 있습니다 . 예를 들어 miniupnpc / testupnpigd.py를 참조하십시오 .

pip install miniupnpc

그들의 예를 바탕으로 다음과 같이 할 수 있어야합니다.

import miniupnpc

u = miniupnpc.UPnP()
u.discoverdelay = 200
u.discover()
u.selectigd()
print('external ip address: {}'.format(u.externalipaddress()))

외부 소스가 너무 불안정하다고 생각하면 몇 가지 다른 서비스를 풀링 할 수 있습니다. 대부분의 ip 조회 페이지의 경우 html을 스크랩해야하지만 일부는 귀하와 같은 스크립트를위한 린 페이지를 생성했습니다. 따라서 사이트의 히트를 줄일 수 있습니다.


제 생각에 가장 간단한 해결책은

    f = requests.request('GET', 'http://myip.dnsomatic.com')
    ip = f.text

그게 다야.


이 질문에 대한 다른 대부분의 답변을 여기에서 시도해 보았고 사용 된 대부분의 서비스가 하나를 제외하고는 작동하지 않음을 발견했습니다.

다음은 트릭을 수행하고 최소한의 정보 만 다운로드해야하는 스크립트입니다.

#!/usr/bin/env python

import urllib
import re

def get_external_ip():
    site = urllib.urlopen("http://checkip.dyndns.org/").read()
    grab = re.findall('([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)', site)
    address = grab[0]
    return address

if __name__ == '__main__':
  print( get_external_ip() )

import requests
import re


def getMyExtIp():
    try:
        res = requests.get("http://whatismyip.org")
        myIp = re.compile('(\d{1,3}\.){3}\d{1,3}').search(res.text).group()
        if myIp != "":
            return myIp
    except:
        pass
    return "n/a"

외부 웹 사이트를 확인하는 Python에 의존하지 않는 몇 가지 다른 방법이 있지만 OS는 가능합니다. 여기서 가장 중요한 문제는 Python을 사용하지 않더라도 명령 줄을 사용하는 경우 단순히 외부 (WAN) IP를 알려줄 수있는 "내장"명령이 없다는 것입니다. "ip addr show"및 "ifconfig -a"와 같은 명령은 네트워크 내 서버의 IP 주소를 보여줍니다. 라우터 만 실제로 외부 IP를 보유합니다. 그러나 명령 줄에서 외부 IP 주소 (WAN IP)를 찾는 방법이 있습니다.

이러한 예는 다음과 같습니다.

http://ipecho.net/plain ; echo
curl ipinfo.io/ip
dig +short myip.opendns.com @resolver1.opendns.com
dig TXT +short o-o.myaddr.l.google.com @ns1.google.com

따라서 파이썬 코드는 다음과 같습니다.

import os
ip = os.popen('wget -qO- http://ipecho.net/plain ; echo').readlines(-1)[0].strip()
print ip

또는

import os
iN, out, err = os.popen3('curl ipinfo.io/ip')
iN.close() ; err.close()
ip = out.read().strip()
print ip

또는

import os
ip = os.popen('dig +short myip.opendns.com @resolver1.opendns.com').readlines(-1)[0].strip()
print ip

또는 위의 다른 예를 os.popen, os.popen2, os.popen3 또는 os.system과 같은 명령에 연결하십시오.


컴퓨터가 방화벽이라면 솔루션은 매우 현명한 솔루션입니다. 대안은 방화벽 유형에 따라 달라지는 방화벽을 쿼리 할 수있는 것입니다 (가능한 경우).


내가 생각할 수있는 가장 간단한 (비 파이썬) 작업 솔루션은

wget -q -O- icanhazip.com

http://hostip.info 의 JSON API를 사용하는 매우 짧은 Python3 솔루션을 추가하고 싶습니다 .

from urllib.request import urlopen
import json
url = 'http://api.hostip.info/get_json.php'
info = json.loads(urlopen(url).read().decode('utf-8'))
print(info['ip'])

물론 오류 검사, 시간 초과 조건 및 편의성을 추가 할 수 있습니다.

#!/usr/bin/env python3
from urllib.request import urlopen
from urllib.error import URLError
import json

try:
    url = 'http://api.hostip.info/get_json.php'
    info = json.loads(urlopen(url, timeout = 15).read().decode('utf-8'))
    print(info['ip'])
except URLError as e:
    print(e.reason, end=' ') # e.g. 'timed out'
    print('(are you connected to the internet?)')
except KeyboardInterrupt:
    pass

In [1]: import stun

stun.get_ip_info()
('Restric NAT', 'xx.xx.xx.xx', 55320)

작업 파이썬 2.7 0.6 및 2.7.13

import urllib2  
req = urllib2.Request('http://icanhazip.com', data=None)  
response = urllib2.urlopen(req, timeout=5)  
print(response.read())

외부 서비스 (IP 웹 사이트 등)를 사용하지 않으려면 UPnP 프로토콜을 사용할 수 있습니다 .

이를 위해 간단한 UPnP 클라이언트 라이브러리 ( https://github.com/flyte/upnpclient )를 사용합니다.

설치 :

pip 설치 upnpclient

간단한 코드 :

import upnpclient

devices = upnpclient.discover()

if(len(devices) > 0):
    externalIP = devices[0].WANIPConn1.GetExternalIPAddress()
    print(externalIP)
else:
    print('No Connected network interface detected')

전체 코드 (github readme에 언급 된 추가 정보 얻기)

In [1]: import upnpclient

In [2]: devices = upnpclient.discover()

In [3]: devices
Out[3]: 
[<Device 'OpenWRT router'>,
 <Device 'Harmony Hub'>,
 <Device 'walternate: root'>]

In [4]: d = devices[0]

In [5]: d.WANIPConn1.GetStatusInfo()
Out[5]: 
{'NewConnectionStatus': 'Connected',
 'NewLastConnectionError': 'ERROR_NONE',
 'NewUptime': 14851479}

In [6]: d.WANIPConn1.GetNATRSIPStatus()
Out[6]: {'NewNATEnabled': True, 'NewRSIPAvailable': False}

In [7]: d.WANIPConn1.GetExternalIPAddress()
Out[7]: {'NewExternalIPAddress': '123.123.123.123'}

요청 모듈 사용 :

import requests

myip = requests.get('https://www.wikipedia.org').headers['X-Client-IP']

print("\n[+] Public IP: "+myip)

Python3에서 실행하는 것처럼 간단합니다.

import os

externalIP  = os.popen('curl -s ifconfig.me').readline()
print(externalIP)

이 Amazon AWS 엔드 포인트를 선호합니다.

import requests
ip = requests.get('https://checkip.amazonaws.com').text.strip()

ipWebCode = urllib.request.urlopen("http://ip.nefsc.noaa.gov").read().decode("utf8")
ipWebCode=ipWebCode.split("color=red> ")
ipWebCode = ipWebCode[1]
ipWebCode = ipWebCode.split("</font>")
externalIp = ipWebCode[0]

이것은 다른 프로그램을 위해 작성한 짧은 스 니펫입니다. 요령은 html을 분석하는 것이 고통스럽지 않도록 충분히 간단한 웹 사이트를 찾는 것이 었습니다.


다른 대체 스크립트가 있습니다.

def track_ip():
   """
   Returns Dict with the following keys:
   - ip
   - latlong
   - country
   - city
   - user-agent
   """

   conn = httplib.HTTPConnection("www.trackip.net")
   conn.request("GET", "/ip?json")
   resp = conn.getresponse()
   print resp.status, resp.reason

   if resp.status == 200:
       ip = json.loads(resp.read())
   else:
       print 'Connection Error: %s' % resp.reason

   conn.close()
   return ip

편집 : httplib 및 json을 가져 오는 것을 잊지 마십시오


일반화 된 응용 프로그램이 아니라 직접 작성하는 경우 라우터 설정 페이지에서 주소를 찾은 다음 해당 페이지의 html에서 긁어 낼 수 있습니다. 이것은 내 SMC 라우터에서 잘 작동했습니다. 하나의 읽기와 하나의 간단한 RE 검색을 찾았습니다.

My particular interest in doing this was to let me know my home IP address when I was away from home, so I could get back in via VNC. A few more lines of Python stores the address in Dropbox for outside access, and even emails me if it sees a change. I've scheduled it to happen on boot and once an hour thereafter.


Use this script :

import urllib, json

data = json.loads(urllib.urlopen("http://ip.jsontest.com/").read())
print data["ip"]

Without json :

import urllib, re

data = re.search('"([0-9.]*)"', urllib.urlopen("http://ip.jsontest.com/").read()).group(1)
print data

Linux only solution.

On Linux Systems, you can use Python to execute a command on the shell. I think it might help someone.

Something like this, (assuming 'dig' is working on the os)

import os
command = '''dig TXT +short o-o.myaddr.l.google.com @ns1.google.com | awk -F'"' '{ print $2}'''
ip = os.system(command)

ReferenceURL : https://stackoverflow.com/questions/2311510/getting-a-machines-external-ip-address-with-python

반응형