#!/usr/bin/env python
#-*- coding:utf-8 -*-
# Description : get ecs from aliyun
# Author : quke
# Date : 2017-05-16 import json
import math
import time
import random
import datetime
import sqlite3
from aliyunsdkcore import client
from aliyunsdkecs.request.v20140526 import DescribeInstancesRequest def coroutine(func):
def start(*args, **kwargs):
g = func(*args, **kwargs)
g.next()
return g
return start @coroutine
def get_aliyun_ecs(key, secret, zone):
'''
aliyun显示每页最大显示数量PageSize 100条
https://help.aliyun.com/document_detail/35112.html
'''
Client = client.AcsClient(key, secret, zone) request = DescribeInstancesRequest.DescribeInstancesRequest()
request.set_accept_format('json')
request.set_PageSize(100)
response = None while True:
pageNumber = (yield response)
print pageNumber
request = DescribeInstancesRequest.DescribeInstancesRequest()
request.set_accept_format('json')
request.set_PageSize(100)
request.set_PageNumber(pageNumber)
response = json.loads(Client.do_action_with_exception(request)) def format_data(jsonData):
instances = jsonData.get('Instances').get('Instance')
result = [] for line in instances:
data = (
line.get('ZoneId'),
line.get('InstanceId'),
line.get('HostName'),
line.get('InnerIpAddress').get('IpAddress')[0] if line.get('InnerIpAddress').get('IpAddress') else 'null',
line.get('PublicIpAddress').get('IpAddress')[0] if line.get('PublicIpAddress').get('IpAddress') else 'null',
u'%d核|%dG' %(line.get('Cpu'),int(line.get('Memory'))/1024),
datetime.datetime.strptime(line.get('CreationTime'), '%Y-%m-%dT%H:%MZ').strftime('%Y-%m-%d %H:%M:%S'),
datetime.datetime.strptime(line.get('ExpiredTime'), '%Y-%m-%dT%H:%MZ').strftime('%Y-%m-%d %H:%M:%S'),
)
result.append(data) return result def insertDB(data):
conn = sqlite3.connect('/Users/quke/db.sqlite3')
cursor = conn.cursor() for line in data:
cursor.execute('insert into cmdb_aliyunecs("region","instanceId","hostname","inner_ip","outer_ip","hardware","creationTime","expiredTime") values(?,?,?,?,?,?,?,?)', line)
conn.commit() if __name__ == '__main__':
# region https://help.aliyun.com/document_detail/28908.html
regions = ('cn-beijing', 'cn-hangzhou', 'cn-hongkong', 'us-east-1')
for region in regions:
print region
aliyun_ecs=get_aliyun_ecs('key','secret', region)
jsonData = aliyun_ecs.send(1)
formated_data = format_data(jsonData)
insertDB(formated_data) totalCount = jsonData.get('TotalCount')
totalPage = int(math.ceil(totalCount/float(100))) + 1 for pageNumber in range(2, totalPage):
time.sleep(random.random())
jsonData = aliyun_ecs.send(pageNumber)
formated_data = format_data(jsonData)
insertDB(formated_data)

  

python获取aliyun ECS实例的更多相关文章

  1. 【类不类二】Python的类变量与实例变量

    在研究类的时候,难免会有很多疑问,C论坛和博客园高手如云(不知道是不是也美女如云), 搜到了这篇博文,是介绍Python的类变量和实例变量的 ! 刚好在下对self.***这种形式的实例变 量不是很理 ...

  2. shell,python获取当前路径(脚本的当前路径) (aso项目记录)

    一.shell获取脚本当前路径 cur_dir=$(cd "$(dirname "$0")"; pwd)  #获取当前脚本的绝对路径,参数$0是当前脚本对象 等 ...

  3. python获取日期加减之后的日期

    python语言中的datetime模块可以利用其中的方法获取不同的日期,比如获取当前日期.明天.昨天.上个月.下个月和明年.下面利用几个实例说明这些日期的获取方法,操作如下:     第一步,利用d ...

  4. 【转】基于Python的接口测试框架实例

    下面小编就为大家带来一篇基于Python的接口测试框架实例.小编觉得挺不错的,现在就分享给大家,也给大家做个参考.一起跟随小编过来看看吧   背景 最近公司在做消息推送,那么自然就会产生很多接口,测试 ...

  5. 阿里云自定义镜像可以免费保存,ECS实例到期后自定义镜像手动快照不会被删除

    阿里云自定义镜像可以免费保存,ECS实例到期后自定义镜像手动快照不会被删除 4. ECS 实例释放后,自定义镜像是否还存在? 存在. 5. ECS 实例释放后,快照是否还存在? 保留手动快照,清除自动 ...

  6. redis安装 phpredis Jedis 扩展的实现及注意事项,php,java,python相关插件安装实例代码和文档推荐

    redis安装 phpredis Jedis 扩展的实现及注意事项,php,java,python相关插件安装实例代码和文档推荐 1.Redis 官方网站下载: http://redis.io/dow ...

  7. 基于Python的接口测试框架实例

    文章来源:http://www.jb51.net/article/96481.htm 下面小编就为大家带来一篇基于Python的接口测试框架实例.小编觉得挺不错的,现在就分享给大家,也给大家做个参考. ...

  8. Python的装饰器实例用法小结

    这篇文章主要介绍了Python装饰器用法,结合实例形式总结分析了Python常用装饰器的概念.功能.使用方法及相关注意事项 一.装饰器是什么 python的装饰器本质上是一个Python函数,它可以让 ...

  9. Python获取百度浏览记录

    Python模拟百度登录实例详解 http://www.jb51.net/article/78406.htm Python实战计划学习作业2-1 http://blog.csdn.net/python ...

随机推荐

  1. 小学生福利V2.0.1

    211606320刘佳&211506332熊哲琛 一.预估与实际 PSP2.1 Personal Software Process Stages 预估耗时(分钟) 实际耗时(分钟) Plann ...

  2. Shiro框架的简单应用

    一.概念 Shiro是一个安全框架,可以进行角色.权限管理. Shiro主要功能如下:Authentication(认证):用户身份识别,通常被称为用户“登录”Authorization(授权):访问 ...

  3. php function 按引用返回一个值

    按引用返回一个值,而不是按值返回,这样就无需为变量建立一个重复的副本 function &array_find_value($needle, &$haystack) { foreach ...

  4. How to use mouse to moving windows of not have title bar?

    How to use mouse to moving windows of not have title bar? #include "widget.h" #include < ...

  5. C++ 文件类型分析

    .APS:存放二进制资源的中间文件,VC把当前资源文件转换成二进制格式,并存放在APS文件中,以加快资源装载速度.资源辅助文件. .BMP:位图资源文件. .BSC:浏览信息文件,由浏览信息维护工具( ...

  6. [z]hadoop生态系统

    http://developer.51cto.com/art/201311/415639_all.htm

  7. netbeans下调试php程序-xdebug

    环境说明: pc系统:ubuntu 16.04 php版本:5.6.23 apache:Apache/2.4.18 (Ubuntu) 第一步:修改xdebug.ini 打开文件/etc/php/5.6 ...

  8. CRC32加密算法原理

    [转]:https://blog.csdn.net/android_mnbvcxz/article/details/78902737

  9. cmake get_filename_component

    get_filename_component Get a specific component of a full filename. get_filename_component(<VAR&g ...

  10. JSON.parse()和JSON.stringify()的使用

    parse用于从一个字符串中解析出json对象,如 var str = '{"name":"huangxiaojian","age":&qu ...