-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython-operation.py
More file actions
435 lines (324 loc) · 12 KB
/
python-operation.py
File metadata and controls
435 lines (324 loc) · 12 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
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
#!/usr/bin/env python
# conding: utf-8
#
# vb command
#
import os
import sys
# import pdb
# import argparse
import subprocess
def parse_opts():
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument(
'-c',
'--check',
type=str,
help='WIP: check VM List.',
)
return parser.parse_args()
# VBoxManage コマンドの有無を確認する関数
def chk_vb_command():
"""
ローカルにVirtualBoxのCLIがインストールしてあるか確認する
"""
paths = ["/usr/bin/", "/usr/local/bin/"]
for path in paths:
vb_cmd = path + 'VBoxManage'
if os.path.isfile(vb_cmd) is True:
# print('OK')
# print(vb_cmd)
break # After this, vb_cmd exists in reality.
else:
print('Maybe, You do not install Virtualbox ( We could not find ' + vb_cmd + ' )')
else:
print('You do not install Virtualbox. Bye!')
sys.exit(0)
# print(vb_cmd)
return vb_cmd
# 実在するVMの表示名を取得する(vms_name_all_list)
def exe_vm_all(vc_path):
"""
ローカルマシンに存在するVMのリストを作成
"""
vms_name_all_list = []
try:
res = subprocess.run([vc_path, "list", "vms"],
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
# 標準出力としてターミナルに出力する
# sys.stdout.buffer.write(res.stdout)
# 一行ずつ取り出して、処理したい
for line in res.stdout.splitlines():
# すべての表示
# print(line)
# " で区切って配列形式
# print(line.split('"'))
# " で区切って配列形式の2個目 = VM name
vms_name_all = line.split('"')[1]
# print(vms_name_all)
# 配列に追加する
vms_name_all_list.append(vms_name_all)
except subprocess.CalledProcessError:
print('外部プログラムの実行に失敗しました [' + vc_path + ']', file=sys.stderr)
# 配列をソートする
vms_name_all_list = sorted(vms_name_all_list)
# 配列の確認
# print(vms_name_all_list)
return vms_name_all_list
# 現在起動しているVMの表示名を取得する(vms_name_running_list)
def exe_vm_running(vc_path):
"""
現在、ローカルマシン上で起動状態のVMのリストを作成
"""
vms_name_running_list = []
try:
res = subprocess.run([vc_path, "list", "runningvms"],
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
# 標準出力としてターミナルに出力する
# sys.stdout.buffer.write(res.stdout)
# 一行ずつ取り出して、処理したい
for line in res.stdout.splitlines():
# すべての表示
# print(line)
# " で区切って配列形式
# print(line.split('"'))
# " で区切って配列形式の2個目 = VM name
vms_name_running = line.split('"')[1]
# print(vms_name_all)
# 配列に追加する
vms_name_running_list.append(vms_name_running)
except subprocess.CalledProcessError:
print('外部プログラムの実行に失敗しました [' + vc_path + ']', file=sys.stderr)
# 配列をソートする
vms_name_running_list = sorted(vms_name_running_list)
# 配列の確認
# print(vms_name_running_list)
return vms_name_running_list
# 配列の比較
def chk_list_diff(vname_all, vname_rng):
"""
(存在するVM) - (起動中VM) をすることで、これか起動出来るVMのリストを作成
"""
# 集合(set)にして差分を確認
vname_dif = set(vname_all) - set(vname_rng)
# 差分のsetをsetのまま表示する
# print(vname_dif)
# setを配列(list)に直す
vname_dif = list(vname_dif)
# print(vname_dif)
# 出来た配列をソートする
vname_dif = sorted(vname_dif)
# print(vname_dif)
return vname_dif
# VirtualBoxのリスト表示
def print_list(vc_path, vname_all, vname_rng, vname_dif):
print('\n\n### Virtual Box List ###')
print('\n---------------------------')
print(' [ ALL VM ] |')
print('---------------------------')
if vname_all == []:
print('*** ' + 'not Making VMs' + ' ***')
else:
for index in range(len(vname_all)):
print(' ' + vname_all[index])
# print('\n\n## Virtual Box List ##\n')
print('\n---------------------------')
print(' [ Running VM ] |')
print('---------------------------')
if vname_rng == []:
print('*** ' + 'not Running VMs' + ' ***')
else:
for index in range(len(vname_rng)):
print(' ' + vname_rng[index])
# print('\n\n## Virtual Box List ##\n')
print('\n---------------------------')
print(' [ DIFFERENCE VM ] |')
print('---------------------------')
if vname_dif == []:
print('*** ' + 'not Diff VMs' + ' ***')
else:
for index in range(len(vname_dif)):
print(' ' + vname_dif[index])
print('\n\n### choose NUMBER of operation VM behave ###\n')
print(' 1 : start')
print(' 2 : stop')
print(' 3 : search')
print(' 9 : exit')
# ユーザの入力
ans = input_num()
# print(ans)
print('your input: ', ans)
if ans == 1:
fnc_start(vname_all, vname_rng, vname_dif, vc_path)
elif ans == 2:
fnc_stop(vname_all, vname_rng, vname_dif, vc_path)
elif ans == 3:
fnc_search(vname_all, vname_rng, vname_dif)
elif ans == 9:
print('OK! See You!!')
sys.exit(0)
else:
# print('Error. Invalid input vale: {}'.format(ans))
print('入力された値が選択出来る数値でありません: {}'.format(ans))
sys.exit(1)
# inputによる入力と数値チェック
def input_num():
"""
数字チェック
"""
i = input('>> ')
chk_num = i.isdecimal()
if chk_num is True and not i == '0':
# print('OK')
input_number = int(i)
pass
else:
print('your input: ', i)
print('入力された値が自然数でありません: {}'.format(i))
sys.exit(1)
return input_number
# startの関数
def fnc_start(vname_all, vname_rng, vname_dif, vc_path):
"""
VMの起動関数
"""
print('\n---------------------------')
print(' [ DIFFERENCE VM ] |')
print('---------------------------')
if vname_dif == []:
print('*** ' + 'not Diff VMs' + ' ***')
else:
for index in range(len(vname_dif)):
print(' ' + str(index + 1) + ' : ' + vname_dif[index])
# ユーザの入力
start_ans = input_num()
print('your input: ', start_ans)
# 修正
start_ans = start_ans - 1
if start_ans > len(vname_dif) - 1:
print('入力した数値が大きすぎます')
else:
# 入力された数値に対応するvnameを代入
start_vname = vname_dif[start_ans]
# print('len(hairetu): ', len(vame_dif))
# print('start_vname', start_vname)
# vnameを元にVirtualBoxをヘッドレスモードで起動する
print('Start Virtualbox is ' + str(start_vname))
try:
res = subprocess.run([vc_path, "startvm", start_vname, "-type", "vrdp"],
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
# 標準出力としてターミナルに出力する
# sys.stdout.buffer.write(res.stdout)
except subprocess.CalledProcessError:
print('外部プログラムの実行に失敗しました [' + vc_path + ']', file=sys.stderr)
# stopの関数
def fnc_stop(vname_all, vname_rng, vname_dif, vc_path):
"""
VMの停止関数
"""
print('\n---------------------------')
print(' [ Running VM ] |')
print('---------------------------')
if vname_rng == []:
print('*** ' + 'not Running VMs' + ' ***')
else:
for index in range(len(vname_rng)):
print(' ' + str(index + 1) + ' : ' + vname_rng[index])
# ユーザの入力
stop_ans = input_num()
print('your input: ', stop_ans)
# 修正
stop_ans = stop_ans - 1
if stop_ans > len(vname_rng) - 1:
print('入力した数値が大きすぎます')
else:
# 入力された数値に対応するvnameを代入
stop_vname = vname_rng[stop_ans]
print('Do you really want to stop {} ? >>> [Yes = 1 | No == 9]'.format(stop_vname))
# 質問に対するユーザの入力と数値チェック
stop_ans_confirmation = input_num()
print('your input: ', stop_ans_confirmation)
if stop_ans_confirmation == 1:
# vnameを元にVirtualBoxを停止させる
print('Stop Virtualbox is ' + str(stop_vname))
try:
res = subprocess.run([vc_path, "controlvm", stop_vname, "poweroff"],
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True)
except subprocess.CalledProcessError:
print('外部プログラムの実行に失敗しました [' + vc_path + ']', file=sys.stderr)
sys.exit(0)
elif stop_ans_confirmation == 9:
print('OK. Bye !!')
sys.exit(0)
else:
print('入力された値が選択出来る数値でありません: {}'.format(stop_ans_confirmation))
sys.exit(0)
# searchの関数
def fnc_search(vname_all, vname_rng, vname_dif):
"""
VMの探索関数
"""
print('\n---------------------------')
print(' [ ALL VM ] |')
print('---------------------------')
if vname_all == []:
print('*** ' + 'not VMs' + ' ***')
else:
for index in range(len(vname_all)):
print(' ' + str(index + 1) + ' : ' + vname_all[index])
# ユーザの入力
search_ans = input_num()
print('your input: ', search_ans)
# 修正
search_ans = search_ans - 1
if search_ans > len(vname_all) - 1:
print('入力した数値が大きすぎます')
else:
# 入力された数値に対応するvnameを代入
search_vname = vname_all[search_ans]
print(search_vname)
vag_files = []
# 環境変数から$HOMEを入れる
HOME_PATH = os.environ["HOME"]
print(HOME_PATH)
# os.walkによる 'Vagrantfile' の検索
for root, dirs, files in os.walk(HOME_PATH):
for filename in files:
if filename == 'Vagrantfile' and root.find('.vagrant.d') is -1:
vag_files.append(os.path.join(root, filename))
else:
pass
if vag_files == []:
print('あなたが探しているVagrantfileは存在しません.')
sys.exit(0)
srh_word = search_vname
for files in vag_files:
with open(files, encoding='utf-8') as f:
# print(files)
for row in f:
# print(row)
if not row.find(srh_word) is -1:
print('This file name is ', files)
# main
def main():
vc_path = chk_vb_command()
vname_all = exe_vm_all(vc_path)
vname_rng = exe_vm_running(vc_path)
vname_dif = chk_list_diff(vname_all, vname_rng)
# メイン処理
print_list(vc_path, vname_all, vname_rng, vname_dif)
if __name__ == '__main__':
main()