How to get public ip of current ec2 instance in python?

How to get public IP address of current EC2 instance in python?

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

If you are already using boto, you can also use the function boto.utils.get_instance_metadata. This makes a call to the metadata server, collects all the metadata and returns it as a Python dictionary. It also handles repetitions.

+3
source

Public IP Elastic IP- EC2 (: EIP- EC2, IP- ).

Django, IP- ALLOWED_HOSTS .py script.

  • 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)
    

.

+2
import requests
ip = requests.get("http://169.254.169.254/latest/meta-data/public-ipv4").content
+1
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 
0
source

All Articles