python(boto3) 脚本实现AWS实例的自起停
为AWS宁夏区开张送上迟到地祝福,上半年项目开发中用到了AWS云服务器,按时计费,为节省经费计划在上班期间开启,下班之后关闭。通过查看boto3文档,最终实现了这一小脚本。半年前的脚本,不知道在现在会不会过时,权当做个记录,如果能帮到网友自然更好
前置工作
- 目的
实现定时远程控制AWS中EC2和RDS实例的自启停
- 运行必要环境
python 3.6
boto 3
(通过aws命令行也可以进行远程控制,为了适应性,还是决定用python开发脚本,安装方法请通过网络检索。)
- 参考文档
https://pypi.org/project/boto3/
- 访问信息
以管理员的身份登录AWS,生成远程访问的必要信息,access_id,secret_access_key,region
实现
- 思路
EC2, 在boto3的文档中现成的EC2示范代码,照葫芦画瓢即可
RDS,没有直接示范代码,参考session的示范代码,也捣鼓成功了
- 文件结构
根据boto3的推荐,分成python程序文件和配置文件
配置文件如下,不再重复贴
1
2
3
4
5
6 1[config]
2aws_access_key_id = ABCDEFG
3aws_secret_access_key = 123456789/*-+
4region = cn-northwest-1
5
6
- python代码
EC2 实例控制代码,可以自动获取所有已存在的实例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68 1#!/usr/bin/env python
2# coding = utf-8
3
4import sys
5import boto3
6from boto3.session import Session
7import configparser
8
9DEBUG = False
10
11def get_config_info(configFile):
12 cf = configparser.ConfigParser()
13 cf.read(configFile)
14
15 return cf['config']['aws_access_key_id'], \
16 cf['config']['aws_secret_access_key'], \
17 cf['config']['region']
18
19
20def get_instances_info(resource, id_list, state):
21
22 instances = resource.instances.filter(
23 Filters=[{'Name': 'instance-state-name', 'Values': [state]}])
24
25 if any(instances):
26 for instance in instances:
27 id_list.append(instance.id)
28 print(instance.id, instance.instance_type, instance.state)
29 else :
30 print('instances none in ' + state)
31
32 return
33
34
35def main():
36
37 cmd = ['START', 'STOP', 'CHECK']
38 status = ['stopped', 'running']
39
40 ids = []
41 info = get_config_info(str(sys.argv[1]))
42
43 session = boto3.session.Session(aws_access_key_id = info[0],
44 aws_secret_access_key = info[1],
45 region_name = info[2])
46
47 ec2 = session.resource('ec2')
48
49 action = sys.argv[2].upper()
50
51 if cmd[2] == action :
52 for sta in status:
53 get_instances_info(ec2, ids, sta)
54
55 elif cmd[0] == action :
56 get_instances_info(ec2, ids, status[0])
57 ec2.instances.filter(InstanceIds = ids).start()
58
59 elif cmd[1] == action :
60 get_instances_info(ec2, ids, status[1])
61 ec2.instances.filter(InstanceIds = ids).stop()
62
63
64if __name__ == '__main__':
65 main()
66
67
68
RDS,当时不能自动获取RDS上的所有实例,需要用从配置文件中读取要操作的实例名称,不免为一大遗憾
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73 1# !/usr/bin/env python
2# coding = utf-8
3
4import sys
5import boto3
6from boto3.session import Session
7from botocore.exceptions import ClientError
8import configparser
9
10def get_config_info(configFile):
11 cf = configparser.ConfigParser()
12 cf.read(configFile)
13
14 return cf['config']['aws_access_key_id'], \
15 cf['config']['aws_secret_access_key'], \
16 cf['config']['region']
17
18
19def get_rds_instances(instancesFile):
20 instances = []
21 with open(instancesFile, 'r') as f:
22 for line in f.readlines():
23 print(line)
24 instances.append(line.strip())
25 f.close()
26
27 if any(instances):
28 return instances
29 else:
30 print('instances file is empty.')
31
32
33def main():
34 cmd = ['START', 'STOP', 'CHECK']
35
36 info = get_config_info(str(sys.argv[1]))
37
38 session = boto3.session.Session(aws_access_key_id = info[0],
39 aws_secret_access_key = info[1],
40 region_name = info[2])
41
42 rds_client = session.client('rds')
43
44 instances = get_rds_instances(str(sys.argv[2]))
45
46 action = sys.argv[3].upper()
47
48 if cmd[2] == action:
49 for instance in instances:
50 response = rds_client.\
51 describe_db_instances(DBInstanceIdentifier = instance)
52 print(instance, response)
53
54 elif cmd[0] == action:
55 for instance in instances:
56 response = rds_client.\
57 start_db_instance(DBInstanceIdentifier = instance)
58 print(instance, response)
59
60 elif cmd[1] == action:
61 for instance in instances:
62 response = rds_client.\
63 stop_db_instance(DBInstanceIdentifier = instance)
64 print(instance, response)
65
66 return
67
68
69if __name__ == '__main__':
70 main()
71
72
73
rds_instances
1
2
3
4 1testRds1
2testRds2
3
4
- 加入到系统任务中,设置为周一到周五早上9点执行启动命令,下午5点执行关闭命令,目标达成
踩过的坑
- 找不到实例、 拒绝访问、没有访问权限
确认一下本地PC的时区,AWS是按照时区进行分片,当请求发起后,通过发起请求PC的时区进行判断该查找哪一片区的实例,国内的PC不乱改时区,都能访问北京或宁夏的AWS上的实例,在确认了访问信息无误之后如仍不能访问,可以把PC时区调整为东八区试试。
PS: 洒家非python程序员 ,现学现用,不足之处甚多,欢迎心平气和地指正。
- 不想手动copy的网友请自取 https://download.csdn.net/download/u010009744/10836288