#!/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. 在制MO未取到FP

    原因:今天在制MO未取进去原因为业务人员维护验货客户尾缀时维护ZZ导致,需更新为C开头即可 SELECT * FROM IN_SFCHEADER WHERE MO_ID in('00110051832 ...

  2. Ssm框架常见报错

    错误1: The origin server did not find a current representation for the target resource or is not willi ...

  3. CTC Loss原理

    https://blog.csdn.net/left_think/article/details/76370453 1. 背景介绍  在传统的语音识别的模型中,我们对语音模型进行训练之前,往往都要将文 ...

  4. 23-python用BeautifulSoup用抓取a标签内所有数据

    1.获取子标签: thr_msgs = soup.find_all('div',class_=re.compile('msg'))   for i in thr_msgs:     print(i) ...

  5. springMVC框架的作用

    springMVC:是一个表现层框架 作用:就是从请求中接收传入的参数 将处理后的结果数据返回给页面展示

  6. 五款免费的UML建模工具

    1.免费UML建模工具推荐:JUDE–community 2.免费UML建模工具推荐:UMLet 3.免费UML建模工具推荐:ArgoUML 4.免费UML建模工具推荐:BOUml 5.免费UML建模 ...

  7. linux下PHP7安装memcache

    1.memcache服务器的安装 .分别把memcached和libevent下载回来,放到 /tmp 目录下: # cd /tmp # wget http://www.danga.com/memca ...

  8. 安卓开发解决android.os.NetworkOnMainThreadException异常方法(主线程不能直接调用webservice)

    安卓开发解决android.os.NetworkOnMainThreadException异常方法 2013-01-07 14:01:04|  分类: 技术 |  标签:安卓  技术  java  | ...

  9. CodeForces - 468A ——(思维题)

    Little X used to play a card game called "24 Game", but recently he has found it too easy. ...

  10. handsontable-developer guide-cell type

    单元格类型:这里有很多没见过的用法,得好好总结一下 //预定义的类型Text Numeric Checkbox Date Select Dropdown Autocomplete Password H ...