查找当前机器是否在python中的aws上

问题描述 投票:1回答:4

我有一个可在aws机器以及其他机器上运行的python脚本。该脚本的功能取决于它是否在AWS上。

是否可以通过编程方式发现它是否在AWS上运行? (也许使用boto吗?)

python amazon-web-services boto
4个回答
2
投票

如果您想严格使用boto做到这一点,可以这样做:

import boto.utils
md = boto.utils.get_instance_metadata(timeout=.1, num_retries=0)

timeout指定HTTP客户端在超时之前等待响应的时间。 num_retries参数控制客户端在放弃并返回空字典之前重试请求的次数。


1
投票

您可以轻松使用AWS开发工具包并检查实例ID。除此之外,您还可以检查aws ip范围-查看此链接https://forums.aws.amazon.com/ann.jspa?annID=1701


0
投票

我找到了一种方法,使用:

try:
    instance_id_resp = requests.get('http://169.254.169.254/latest/meta-data/instance-id')
    is_on_aws = True
except requests.exceptions.ConnectionError as e:
    is_on_awas = False

0
投票

我尝试了上面的某些操作,并且当not在Amazon上运行时,我无法访问169.254.169.254。也许与我在美国境外有关。

无论如何,这是一段对我有用的代码:

def running_on_amazon():
  import urllib2
  import socket

  # I'm using curlmyip.com, but there are other websites that provide the same service 
  ip_finder_addr = "http://curlmyip.com" 
  f = urllib2.urlopen(ip_finder_addr)
  my_ip = f.read(100).strip()
  host_addr = socket.gethostbyaddr(my_ip)

  my_public_name = host_addr[0]
  amazon = (my_public_name.find("aws") >=0 )
  return amazon # returns a boolean value. 
© www.soinside.com 2019 - 2024. All rights reserved.