如何在python中获取当前ec2实例的公共ip?
如何在python中获取当前EC2实例的公共ip地址?如果您已经在使用如何在python中获取当前ec2实例的公共ip?,python,amazon-web-services,amazon-ec2,boto,Python,Amazon Web Services,Amazon Ec2,Boto,如何在python中获取当前EC2实例的公共ip地址?如果您已经在使用boto,您还可以使用boto.utils.get\u instance\u metadata函数。这将调用元数据服务器,收集所有元数据并将其作为Python字典返回。它还处理重试。以下方法将返回EC2实例的公共IP或弹性IP地址(注意:如果EIP地址与EC2实例关联,则公共IP地址实际上已释放) import urllib.request urllib.request.urlopen("http://169.254.169.
boto
,您还可以使用boto.utils.get\u instance\u metadata
函数。这将调用元数据服务器,收集所有元数据并将其作为Python字典返回。它还处理重试。以下方法将返回EC2实例的公共IP或弹性IP地址(注意:如果EIP地址与EC2实例关联,则公共IP地址实际上已释放)
import urllib.request
urllib.request.urlopen("http://169.254.169.254/latest/meta-data/public-ipv4").read()
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
这对于Django项目特别有用,因为您可以在settings.py脚本中将IP地址附加到允许的_主机
- 安装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)
干杯。介绍了如何使用HTTP GET检索实例的IP地址。您的回答相当简单,也许您可以解释一下这是如何工作的。这是amazon ec2特有的还是什么?@CrazyCastaL看这里:
local-ipv4
元数据将包含实例的私有IP地址,该地址仅在AWS网络中有用。公共IP地址将作为public-ipv4
提供。
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)