我有一个可在aws机器以及其他机器上运行的python脚本。该脚本的功能取决于它是否在AWS上。
是否可以通过编程方式发现它是否在AWS上运行? (也许使用boto吗?)
如果您想严格使用boto做到这一点,可以这样做:
import boto.utils
md = boto.utils.get_instance_metadata(timeout=.1, num_retries=0)
timeout
指定HTTP客户端在超时之前等待响应的时间。 num_retries
参数控制客户端在放弃并返回空字典之前重试请求的次数。
您可以轻松使用AWS开发工具包并检查实例ID。除此之外,您还可以检查aws ip范围-查看此链接https://forums.aws.amazon.com/ann.jspa?annID=1701
我找到了一种方法,使用:
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
我尝试了上面的某些操作,并且当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.