-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathutils.py
181 lines (149 loc) · 5.49 KB
/
utils.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
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Name : utils.py
# Version : 0.1
# Author : Abdesslem Amri
# Date : 15-01-2014
# Owner : Abdesslem Amri
# License : GPLv2
# Description : This script is used to manage the virtual machine
# [NOTES] -----------------------------------------------------------
# 1) If you're running VirtualBox on Windows, you'll need win32com, which is
# included in the Python Extensions for Windows package
#--------------------------------------------------------------------
__author__ = 'ask3m'
#--------------------------------------------------------------------
import sys, os, time, glob, shutil
from optparse import OptionParser
import subprocess
# -----------------------------------------------------------------------
def pinfo(msg):
print "[INFO] ", msg
def perror(msg):
print "[ERROR] ", msg
# -----------------------------------------------------------------------
class VBoxAuto:
status="ON"
def __init__(self, machine):
self.machine = machine
self.ctx = {}
self.mach = None
self.session=None
def get_mach(self):
return self.ctx['global'].getArray(self.ctx['vb'], 'machines')
def check(self):
try:
from vboxapi import VirtualBoxManager
except ImportError:
perror('You need to install VirtualBox!')
return False
vbm = VirtualBoxManager(None, None)
self.ctx = {'global':vbm,
'const' :vbm.constants,
'vb' :vbm.vbox,
'mgr' :vbm.mgr}
# the machine name or id must be valid
for m in self.get_mach():
if m.name == self.machine or m.id == self.machine:
self.mach = m
break
if self.mach == None:
perror('Cannot find the machine: %s' % self.machine)
return False
pinfo('Using %s (uuid: %s)' % (self.mach.name, self.mach.id))
pinfo('Session state: %s' % self.get_const(
"SessionState", self.mach.sessionState))
pinfo('Machine state: %s' % self.get_const(
"MachineState", self.mach.state))
status=self.mach.state
return True
def get_const(self, enum, elem):
# this lookup fails on Python2.6 - if that happens
# then just return the element number
try:
all = self.ctx['const'].all_values(enum)
for e in all.keys():
if str(elem) == str(all[e]):
return e
except:
return '%d' % elem
def list(self):
try:
for m in self.get_mach():
print "%-12s %s (state:%s/%s)" %(m.name, m.id,
self.get_const("MachineState", m.state),
self.get_const("SessionState", m.sessionState))
except:
perror('No machines. Did you call check() first?')
def start(self, nsecwait=60):
vb = self.ctx['vb']
self.session = self.ctx['mgr'].getSessionObject(vb)
mach=vb.findMachine(self.machine)
p= mach.launchVMProcess(self.session,"gui","")
#headless
while not p.completed:
p.waitForCompletion(1000)
self.ctx['global'].waitForEvents(0)
if int(p.resultCode) == 0:
print "close"
else:
perror('Cannot start machine!')
pinfo('Waiting %d seconds to boot...' % nsecwait)
time.sleep(nsecwait)
def opensession(self):
session = self.ctx['global'].openMachineSession(self.mach.id)
mach = session.machine
return (session, mach)
def closesession(self, session):
self.ctx['global'].closeMachineSession(session)
time.sleep(5)
def stop(self):
(session, mach) = self.opensession()
pinfo('Powering down the system')
try:
session.console.powerDown()
time.sleep(5)
self.closesession(session)
except Exception, e:
pinfo(e)
def revert(self, snapname):
# Revert a VM to the specified snapshot
(session, mach) = self.opensession()
pinfo("Reverting to snapshot '%s'" % snapname)
try:
snap = mach.findSnapshot(snapname)
session.console.restoreSnapshot(snap)
time.sleep(5)
self.closesession(session)
except Exception, e:
pinfo(e)
def winexec(self, user, passwd, args):
print "okk"
#session = self.ctx['mgr'].getSessionObject()
#(session, mach) = self.opensession()
try:
argstr = ' '.join(args[1:])
except:
argstr = ''
pinfo("Executing '%s' with args '%s'" % (args[0], argstr))
pinfo("If this set fails, set up autologin for your user.")
env = []
ret = self.session.console.guest.executeProcess(
args[0],
0,
args,
env,
user, passwd, 0)
# on Windows, executeProcess returns an IProgress instance
if os.name == "nt":
pid = ret[3]
else:
pid = ret[1]
pinfo('Process ID: %d' % pid)
# -----------------------------------------------------------------------
def main(argv):
print 'Nothing to do. Import me!'
return 0
if __name__ == '__main__':
main(sys.argv)