1.通过调用阿里SDK,将获取到的ECS信息存入数据库,如果不知道SDK怎么使用,查看:01.阿里云SDK调用,获取ESC主机详细信息
2.import aliSDK应用的是01.阿里云SDK调用,获取ESC主机详细信息脚本,放在同一路径下就可以直接使用。
1 # -*- coding:utf-8 -*- 2 3 ''' 4 获取阿里云ecs主机的基本情况,并入库 5 表结构:CREATE TABLE `f_ecs` ( 6 `f_id` int(11) NOT NULL, 7 `f_name` varchar(50) DEFAULT NULL, 8 `f_public_ip` varchar(50) DEFAULT NULL, 9 `f_ip` varchar(50) DEFAULT NULL, 10 `f_cpu` int(4) DEFAULT NULL, 11 `f_memory` int(8) DEFAULT NULL, 12 `f_time` datetime DEFAULT NULL, 13 PRIMARY KEY (`f_id`), 14 KEY `f_name` (`f_name`) 15 ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 16 ''' 17 18 import time 19 import pymysql 20 import aliSDK 21 conn = pymysql.connect(host='192.168.1.202',user='root', passwd='20131220', db='ali', charset='utf8') 22 cur = conn.cursor() 23 24 #查询 25 def Query(cur,sql): 26 cur.execute(sql); 27 return cur.fetchall(); 28 29 #插入 30 def Insert(cur,sql): 31 cur.execute(sql); 32 conn.commit() 33 return (cur); 34 35 #update 36 def Update(cur,sql): 37 cur.execute(sql); 38 conn.commit() 39 return (cur); 40 41 for i in aliSDK.get_sys_info(): 42 name = i['InstanceName'] #获取主机名 43 ip = i['PublicIpAddress']['IpAddress'] #获取公网ip 44 ip2 = i['InnerIpAddress']['IpAddress'] #内网ip 45 cpu = i['Cpu'] #cpu个数 46 mem = i['Memory'] #内存大小 47 hostname = Query(cur,r"SELECT f_name,f_public_ip,f_ip,f_cpu,f_memory from t_ecs where f_ip='%s';" %(ip2[0])) 48 if hostname: 49 if hostname[0][2] != ip2[0] or hostname[0][3] != cpu or hostname[0][4] != mem: 50 if ip: #因为公网ip可能没有,所以在有公网ip和无公网ip中,sql语句会略微不同 51 Update(cur,r"UPDATE t_ecs SET `f_public_ip`='%s', `f_ip`='%s', `f_cpu`='%s', `f_memory`='%s', `f_time`=now() WHERE f_name='%s';" %(ip[0], ip2[0], cpu, mem, name)) 52 else: 53 Update(cur,r"UPDATE t_ecs SET `f_ip`='%s', `f_cpu`='%s', `f_memory`='%s', `f_time`=now() WHERE f_name='%s';" %(ip2[0], cpu, mem, name)) 54 else: 55 if ip: 56 Insert(cur, r"INSERT INTO t_ecs (`f_name`, `f_public_ip`, `f_ip`, `f_cpu`, `f_memory`, `f_time`) VALUES ('%s', '%s', '%s', %s, %s, now());" %(name, ip[0], ip2[0], cpu, mem)) 57 else: 58 Insert(cur, r"INSERT INTO t_ecs (`f_name`, `f_ip`,`f_cpu`, `f_memory`, `f_time`) VALUES ('%s', '%s', %s, %s, now());" %(name , ip2[0], cpu, mem)) 59 cur.close() 60 conn.close()
3.当你账号下的ECS主机信息改变时,重复执行此脚本也能自动更新数据库的信息。
4.此脚本没有删除的功能。
####后续学习中,跟Flask框架结合####