forked from liangxiao1/mini_utils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaws_rest_api.py
More file actions
298 lines (277 loc) · 10.5 KB
/
aws_rest_api.py
File metadata and controls
298 lines (277 loc) · 10.5 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
#!/usr/bin/env python
'''
github : https://github.com/liangxiao1/mini_utils
This tool is setup a quick flask server with restapi provided.
It is a lightweight solution if you do not want to share awscli tokens with other for tempary access.
Others can reboot/start/stop/terminate/ssh login to aws instances without knowing tokens.
It does not allow to create new instance for resource controlling purpose.
Please ask account owner start a instance and send instance id to you.
'''
from flask import Flask, send_file, render_template_string
from flask_restful import Resource, Api, reqparse
import boto3
from botocore.exceptions import ClientError
import time
import tempfile
import os
import base64
parser = reqparse.RequestParser()
parser.add_argument('instanceid', type=str, help='instance id')
parser.add_argument('region', type=str, help='region, default us-west-2')
app = Flask(__name__)
api = Api(app)
TASKS = {
'status': 'status of an instance',
'stop': 'stop an instance',
'stop-hibernate': 'hibernate an instance',
'start': 'start an instance',
'reboot': 'stop and start an instance',
'terminate': 'destroy an instance',
'console': 'get console log from an instance',
'consoledownload': 'download console log from an instance',
'consolescreenshot ': 'download console screenshot from an instance',
}
class TasksList(Resource):
def get(self):
return TASKS
class Status(Resource):
def get(self):
# Default to 200 OK
args = parser.parse_args(strict=True)
instanceid = args['instanceid']
if instanceid == None:
return {'Error': "which instanceid do you get?"}
region = args['region']
if region == None:
region = 'us-west-2'
try:
ec2 = boto3.resource('ec2', region_name=region)
instance = ec2.Instance(instanceid)
instance.reload()
instance.state
except ClientError as err:
return {instanceid: '%s' % err}
return {'instanceid': instanceid,
'state': instance.state,
'IP':instance.public_ip_address}
class Start(Resource):
def get(self):
# Default to 200 OK
args = parser.parse_args(strict=True)
instanceid = args['instanceid']
if instanceid == None:
return {'Error': "which instanceid do you get?"}
region = args['region']
if region == None:
region = 'us-west-2'
try:
ec2 = boto3.resource('ec2', region_name=region)
instance = ec2.Instance(instanceid)
instance.reload()
instance.start()
instance.wait_until_running()
instance.reload()
instance.state
except ClientError as err:
return {instanceid: '%s' % err}
return {'instanceid': instanceid,
'state': instance.state,
'IP':instance.public_ip_address}
class Stop(Resource):
def get(self):
# Default to 200 OK
args = parser.parse_args(strict=True)
instanceid = args['instanceid']
if instanceid == None:
return {'Error': "which instanceid do you get?"}
region = args['region']
if region == None:
region = 'us-west-2'
try:
ec2 = boto3.resource('ec2', region_name=region)
instance = ec2.Instance(instanceid)
instance.reload()
instance.stop()
instance.wait_until_stopped()
instance.reload()
instance.state
except ClientError as err:
return {instanceid: '%s' % err}
return {'instanceid': instanceid,
'state': instance.state,
'IP':instance.public_ip_address}
class StopHibernate(Resource):
def get(self):
# Default to 200 OK
args = parser.parse_args(strict=True)
instanceid = args['instanceid']
if instanceid == None:
return {'Error': "which instanceid do you get?"}
region = args['region']
if region == None:
region = 'us-west-2'
try:
ec2 = boto3.resource('ec2', region_name=region)
instance = ec2.Instance(instanceid)
instance.reload()
instance.stop(Hibernate=True)
instance.wait_until_stopped()
instance.reload()
instance.state
except ClientError as err:
return {instanceid: '%s' % err}
return {'instanceid': instanceid,
'state': instance.state,
'IP':instance.public_ip_address}
class Reboot(Resource):
def get(self):
# Default to 200 OK
args = parser.parse_args(strict=True)
instanceid = args['instanceid']
if instanceid == None:
return {'Error': "which instanceid do you get?"}
region = args['region']
if region == None:
region = 'us-west-2'
try:
ec2 = boto3.resource('ec2', region_name=region)
instance = ec2.Instance(instanceid)
instance.reload()
instance.stop()
instance.wait_until_stopped()
instance.start()
instance.wait_until_running()
instance.reload()
instance.state
except ClientError as err:
return {instanceid: '%s' % err}
return {'instanceid': instanceid,
'state': instance.state,
'IP':instance.public_ip_address}
class Terminate(Resource):
def get(self):
# Default to 200 OK
args = parser.parse_args(strict=True)
instanceid = args['instanceid']
if instanceid == None:
return {'Error': "which instanceid do you get?"}
region = args['region']
if region == None:
region = 'us-west-2'
try:
ec2 = boto3.resource('ec2', region_name=region)
instance = ec2.Instance(instanceid)
instance.reload()
instance.terminate()
instance.wait_until_terminated()
instance.reload()
instance.state
except ClientError as err:
return {instanceid: '%s' % err}
return {'instanceid': instanceid,
'state': instance.state}
class Console(Resource):
def get(self):
# Default to 200 OK
args = parser.parse_args(strict=True)
instanceid = args['instanceid']
if instanceid == None:
return {'Error': "which instanceid do you get?"}
region = args['region']
if region == None:
region = 'us-west-2'
try:
ec2 = boto3.resource('ec2', region_name=region)
instance = ec2.Instance(instanceid)
instance.reload()
for i in range(10):
try:
console = instance.console_output(Latest=True)
except Exception as err:
console = instance.console_output()
try:
console['Output']
break
except Exception as err:
console['Output']="Please try later as delay in console output"
time.sleep(2)
continue
instance.reload()
instance.state
except ClientError as err:
return {instanceid: '%s' % err}
return {'instanceid': instanceid,'state':instance.state,
'download':'/ops/consoledownload?instanceid=%s' % instanceid,'console':console['Output']}
class ConsoleDownload(Resource):
def get(self):
# Default to 200 OK
args = parser.parse_args(strict=True)
instanceid = args['instanceid']
if instanceid == None:
return {'Error': "which instanceid do you get?"}
region = args['region']
if region == None:
region = 'us-west-2'
try:
ec2 = boto3.resource('ec2', region_name=region)
instance = ec2.Instance(instanceid)
instance.reload()
for i in range(10):
try:
console = instance.console_output(Latest=True)
except Exception as err:
console = instance.console_output()
try:
console['Output']
break
except Exception as err:
console['Output']="Please try later as delay in console output"
time.sleep(2)
continue
instance.reload()
instance.state
except ClientError as err:
return {instanceid: '%s' % err}
if not os.path.exists('logs'):
os.mkdir('logs')
fh, tmp_log_file = tempfile.mkstemp(suffix='_console.log', dir='logs', text=False)
with open(tmp_log_file, 'w') as fh:
print(console['Output'], file=fh)
return send_file(tmp_log_file, as_attachment=True, cache_timeout=0)
class ConsoleScreeshot(Resource):
def get(self):
# If the system fall to grub cli, there is no console log, this will help
args = parser.parse_args(strict=True)
instanceid = args['instanceid']
if instanceid == None:
return {'Error': "which instanceid do you get?"}
region = args['region']
if region == None:
region = 'us-west-2'
try:
client = boto3.client('ec2', region_name=region)
console_dict = client.get_console_screenshot(InstanceId=instanceid, WakeUp=True)
except Exception as err:
return {"ERROR":str(err)}
if not os.path.exists('logs'):
os.mkdir('logs')
fh, tmp_log_file = tempfile.mkstemp(suffix='_console.jpg', dir='logs', text=False)
with open(tmp_log_file, 'wb') as fh:
fh.write(base64.b64decode(console_dict['ImageData']))
return send_file(tmp_log_file, as_attachment=True, cache_timeout=0)
class SSHKEY(Resource):
def get(self):
path = "data/guest_s1.pem"
return send_file(path, as_attachment=True)
api.add_resource(TasksList, '/ops','/')
api.add_resource(Status, '/ops/status')
api.add_resource(Stop, '/ops/stop')
api.add_resource(StopHibernate, '/ops/stop-hibernate')
api.add_resource(Start, '/ops/start')
api.add_resource(Reboot, '/ops/reboot')
api.add_resource(Terminate, '/ops/terminate')
api.add_resource(Console, '/ops/console')
api.add_resource(ConsoleDownload, '/ops/consoledownload')
api.add_resource(ConsoleScreeshot, '/ops/consolescreenshot')
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5901, debug=True)