-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvm_tool.py
155 lines (135 loc) · 5.23 KB
/
vm_tool.py
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
#!/usr/bin/env python
# VMware vSphere Python SDK
# Copyright (c) 2008-2015 VMware, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Python program for listing the vms on an ESX / vCenter host
"""
from __future__ import print_function
import argparse
import atexit
import getpass
import traceback
import sys
from pyVim.connect import SmartConnect, Disconnect
from database import DataBase
from logger import Logger
from vmhostfolder import VmHostFolder
from vmutils import VmUtils
def get_args():
"""
Supports the command-line arguments listed below.
"""
parser = argparse.ArgumentParser(
description='Process args for retrieving all the Virtual Machines')
parser.add_argument('-s', '--host', required=True, action='store',
help='Remote host to connect to')
parser.add_argument('-o', '--port', type=int, default=443, action='store',
help='Port to connect on')
parser.add_argument('-u', '--user', required=True, action='store',
help='User name to use when connecting to host')
parser.add_argument('-p', '--password', required=False, action='store',
help='Password to use when connecting to host')
parser.add_argument('-v', '--view', choices=['vms', 'hosts'],
help="Preferred view: VMs and Templates/Hosts and Clusters", required=True)
parser.add_argument('--action',
choices=['list', 'poweron', 'poweroff', 'reboot', 'info', 'folder', 'listfolders', 'byfolder'])
parser.add_argument('-n', '--vmname', type=str, help="")
parser.add_argument('-f', '--fname', help="Folder Name", type=str)
parser.add_argument('--dump2db', action='store_true')
args = parser.parse_args()
return args
def do_vm_action(logger, args, vm_folders, si, db=None):
"""
:param logger
:type logger: logging
:param args:
:param vm_folders:
:type vm_folders: VmHostFolder[]
:param si:
:param db:
:type db: DataBase
:return:
"""
if args.action == "list":
VmUtils.list_all_vms(si)
elif args.action == "info":
if not args.vmname:
raise RuntimeError("VM name not specified")
VmUtils.print_vm_info(args, si)
elif args.action == "reboot":
VmUtils.reboot_vm(args, si)
elif args.action == "poweroff" or args.action == "poweron":
VmUtils.poweron_vm(args, si)
elif args.action == "folder":
VmUtils.print_vm_folder(args, si)
elif args.action == "listfolders":
VmUtils.print_all_folders(args, si)
elif args.action == "byfolder":
if not args.fname:
raise RuntimeError("VM folder not specified")
VmUtils.print_vms_by_folder(args, si)
if args.dump2db:
if db is None:
raise RuntimeError("DB isn't initialised")
logger.info("Scanning VM folders. Can take some time....")
folders = VmUtils.get_all_folders(si)
logger.debug("Found folders: {0}".format(folders))
for folder in folders:
vm_folders.append(VmHostFolder(folder, si))
logger.debug("Added folders objects: {0}".format(len(vm_folders)))
logger.info("Dumping to DB...")
for folder in vm_folders:
folder.insert(db)
logger.debug("Folder {0} inserted to DB".format(folder.name))
for cmp_resource in folder.compute_resources:
cmp_resource.insert(db)
logger.debug("Computer Resource {0} inserted to DB".format(cmp_resource.name))
for vm in cmp_resource.virtual_machines:
vm.insert(db)
logger.debug("VM {0} inserted to DB".format(vm.name))
logger.info("Done dumping to DB")
def main():
"""
"""
data_base = None
vm_folders = []
args = get_args()
logger = Logger().logger
logger.debug("Logger Initialized %s" % logger)
if args.dump2db:
data_base = DataBase(logger)
logger.info("SQLite DB initialized %s" % data_base)
if args.password:
password = args.password
else:
password = getpass.getpass(prompt='Enter password for host %s and '
'user %s: ' % (args.host, args.user))
si = SmartConnect(host=args.host,
user=args.user,
pwd=password)
if not si:
logger.error("Could not connect to the specified host using specified "
"username and password")
return -1
atexit.register(Disconnect, si)
do_vm_action(logger, args, vm_folders, si, data_base)
return 0
# Start program
if __name__ == "__main__":
try:
main()
except Exception as e:
traceback.print_exc()
sys.exit(1)