1.安装和使用
系统:Ubuntu14
首先安装两个python包:
pip install boto3
pip install awscli
然后设置凭证文件,输入,aws configure:
设置后,在~/.aws/目录下会多出两个配置文件,里面记录了刚刚输入的验证数据:
之后就可以使用boto3这个python包来编写自己的脚本了。
2.部分常用属性和方法
# encoding=utf8
import boto3
def main():
ec2 = boto3.resource('ec2') # 使用EC2服务
instance = ec2.Instance('你的实例id') # 获取一个EC2实例(一台机器)
state = instance.state # 获取实例的当前状态,返回是一个字典
'''
state说明:
0 : pending
16 : running
32 : shutting-down
48 : terminated
64 : stopping
80 : stopped
'''
# 返回实例的一个或多个网络接口信息
attrs = instance.network_interfaces_attribute
# 返回实例的公有ip,每次重启后该ip会改变
publicIp = instance.public_ip_address
# 返回实例的私有ip,每次重启后该ip不会改变
privateIp = instance.private_ip_address
# 停止一个实例,返回一个字典对象
stop_dic = instance.stop()
# 等待一个实例完成停止操作
instance.wait_until_stopped()
# 启用一个实例,返回一个字典对象
start_dic = instance.start()
# 等待一个实例到它正常运行
instance.wait_until_running()
# 也可以选出正在运行的所有实例
instances = ec2.instances.filter(
Filters=[{'Name': 'instance-state-name', 'Values': ['running']}]
)
for instance in instances:
print instance.id
# 更多关于instance的属性和方法可以参考:
# http://boto3.readthedocs.io/en/latest/reference/services/ec2.html#instance
# ec2相关文档可以参考:
# http://boto3.readthedocs.io/en/latest/reference/services/ec2.html
if __name__ == '__main__':
main()