2014-08-31 189 views

回答

4
import urllib.request 
urllib.request.urlopen("http://169.254.169.254/latest/meta-data/public-ipv4").read() 
+1

你的答案相当简短,也许你可以解释它是如何工作的。这是亚马逊ec2具体还是什么? – CrazyCasta 2014-08-31 06:07:06

+0

@CrazyCastaL请看这里:http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-instance-addressing.html – 2014-08-31 06:07:36

+0

“local-ipv4”元数据将包含实例的私有IP地址这仅在AWS网络中有用。公共IP地址可以使用“public-ipv4”。 – garnaat 2014-08-31 12:55:32

3

如果您已经使用boto,你也可以使用boto.utils.get_instance_metadata功能。这会调用元数据服务器,收集所有元数据并将其作为Python字典返回。它也处理重试。

0
def console(cmd): 
    p = Popen(cmd,shell=True,stdout=PIPE) 
    out,err = p.communicate() 
    dir_list = out.split('\n') 
    return (dir_list) 
ip = console("http://169.254.169.254/latest/meta-data/public-ipv4") 
print ip 
1
import requests 
ip = requests.get("http://169.254.169.254/latest/meta-data/public-ipv4").content 
2

下面的方法将返回公共IP或您的EC2实例的弹性IP地址(注意:如果EIP地址与您的EC2实例相关联,那么公共IP地址实际上是释放)。

这对于Django项目特别有用,因为您可以在settings.py脚本中将IP地址附加到ALLOWED_HOSTS。

  • 安装PyCurl

    pip install pycurl 
    
  • Python 3中

    import pycurl 
    from io import BytesIO 
    
    # Determine Public IP address of EC2 instance 
    buffer = BytesIO() 
    c = pycurl.Curl() 
    c.setopt(c.URL, 'checkip.amazonaws.com') 
    c.setopt(c.WRITEDATA, buffer) 
    c.perform() 
    c.close() 
    body = buffer.getvalue() 
    # Body is a byte string, encoded. Decode it first. 
    print (body.decode('iso-8859-1').strip()) 
    
  • 的Python 2

    import pycurl 
    from StringIO import StringIO 
    
    buffer = StringIO() 
    c = pycurl.Curl() 
    c.setopt(c.URL, 'checkip.amazonaws.com') 
    c.setopt(c.WRITEDATA, buffer) 
    c.perform() 
    c.close() 
    
    body = buffer.getvalue() 
    # Body is a string in some encoding. 
    # In Python 2, we can print it without knowing what the encoding is. 
    print (body) 
    

欢呼。