OpenSecurity/bin/vmmanager.py
author mb
Thu, 09 Jan 2014 10:44:42 +0100
changeset 46 f659d8fb57a8
parent 43 7c2e34bcdf3d
child 52 1238895dc6b6
child 54 59f1d824a070
permissions -rw-r--r--
latest changes from december 2013
mb@7
     1
'''
mb@7
     2
Created on Nov 19, 2013
mb@7
     3
mb@7
     4
@author: BarthaM
mb@7
     5
'''
mb@7
     6
import os
mb@7
     7
import os.path
mb@7
     8
from subprocess import Popen, PIPE, call
mb@7
     9
import subprocess
mb@7
    10
import sys
mb@7
    11
import re
om@19
    12
import _winreg
om@18
    13
from cygwin import Cygwin
mb@36
    14
import threading
mb@40
    15
import time
mb@40
    16
import string
mb@7
    17
om@19
    18
om@42
    19
DEBUG = True
mb@46
    20
class VMManagerException(Exception):
mb@46
    21
    def __init__(self, value):
mb@46
    22
        self.value = value
mb@46
    23
    def __str__(self):
mb@46
    24
        return repr(self.value)
mb@7
    25
mb@7
    26
class USBFilter:
mb@7
    27
    vendorid = ""
mb@7
    28
    productid = ""
mb@7
    29
    revision = ""
mb@7
    30
    
mb@7
    31
    def __init__(self, vendorid, productid, revision):
mb@7
    32
        self.vendorid = vendorid.lower()
mb@7
    33
        self.productid = productid.lower()
mb@7
    34
        self.revision = revision.lower()
mb@7
    35
        return
mb@7
    36
    
mb@7
    37
    def __eq__(self, other):
mb@7
    38
        return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
mb@7
    39
    
mb@7
    40
    def __hash__(self):
mb@7
    41
        return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
mb@7
    42
    
mb@7
    43
    def __repr__(self):
mb@7
    44
        return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
mb@7
    45
        
mb@7
    46
mb@7
    47
class VMManager(object):
mb@7
    48
    vmRootName = "SecurityDVM"
mb@7
    49
    systemProperties = None
mb@7
    50
    cygwin_path = 'c:\\cygwin64\\bin\\'
om@19
    51
    vboxManage = 'VBoxManage'
mb@34
    52
    startNotifications = list()
mb@34
    53
    
mb@34
    54
    _instance = None
mb@34
    55
    #def __new__(cls, *args, **kwargs):
mb@34
    56
    #    if not cls._instance:
mb@34
    57
    #        cls._instance = super(VMManager, cls).__new__(cls, *args, **kwargs)
mb@34
    58
    #    return cls._instance
mb@7
    59
    
mb@33
    60
    _instance = None
mb@33
    61
    #def __new__(cls, *args, **kwargs):
mb@33
    62
    #    if not cls._instance:
mb@33
    63
    #        cls._instance = super(VMManager, cls).__new__(cls, *args, **kwargs)
mb@33
    64
    #    return cls._instance
mb@33
    65
    
mb@7
    66
    def __init__(self):
om@31
    67
        self.cygwin_path = os.path.join(Cygwin.root(), 'bin') + os.path.sep
om@22
    68
        self.vboxManage = os.path.join(self.getVBoxManagePath(), 'VBoxManage')
mb@7
    69
        self.systemProperties = self.getSystemProperties()
mb@7
    70
        return
mb@33
    71
    
mb@33
    72
    @staticmethod
mb@33
    73
    def getInstance():
mb@33
    74
        if VMManager._instance == None:
mb@33
    75
            VMManager._instance = VMManager()
mb@33
    76
        return VMManager._instance
mb@34
    77
    
mb@34
    78
    def putStartNotification(self, ip):
mb@34
    79
        self.startNotifications.append(ip)
mb@34
    80
    
mb@34
    81
    def isSDVMStarted(self, ip):
mb@34
    82
        return self.startNotifications.contains(ip)
mb@33
    83
             
mb@46
    84
    def execute(self, cmd, wait_return=True ):
mb@7
    85
        if DEBUG:
mb@7
    86
            print('trying to launch: ' + cmd)
mb@40
    87
        process = Popen(cmd, stdout=PIPE, stderr=PIPE) #shell = True
mb@7
    88
        if DEBUG:
mb@7
    89
            print('launched: ' + cmd)
mb@46
    90
        if not wait_return:
mb@46
    91
            return [0, 'working in background', '']
mb@7
    92
        result = process.wait()
mb@7
    93
        res_stdout = process.stdout.read();
mb@7
    94
        res_stderr = process.stderr.read();
mb@7
    95
        if DEBUG:
mb@7
    96
            if res_stdout != "":
mb@7
    97
                print res_stdout
mb@7
    98
            if res_stderr != "":
mb@7
    99
                print res_stderr
mb@46
   100
        if result !=0:
mb@46
   101
            raise VMManagerException(res_stderr)
mb@7
   102
        return result, res_stdout, res_stderr
mb@7
   103
    
om@19
   104
    def getVBoxManagePath(self):
om@19
   105
        """get the path to the VirtualBox installation on this system"""
om@19
   106
        p = None
om@19
   107
        try:
om@19
   108
            k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Oracle\VirtualBox')
om@19
   109
            p = _winreg.QueryValueEx(k, 'InstallDir')[0]
om@19
   110
            _winreg.CloseKey(k)
om@19
   111
        except:
om@19
   112
            pass
om@19
   113
        return p
om@19
   114
    
BarthaM@8
   115
    # return hosty system properties
mb@7
   116
    def getSystemProperties(self):
om@22
   117
        cmd = self.vboxManage + ' list systemproperties'
mb@7
   118
        result = self.execute(cmd)
mb@7
   119
        if result[1]=='':
mb@7
   120
            return None
mb@7
   121
        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
mb@7
   122
        return props
BarthaM@8
   123
    
BarthaM@8
   124
    # return the folder containing the guest VMs     
mb@7
   125
    def getDefaultMachineFolder(self):
mb@7
   126
        return self.systemProperties["Default machine folder"]
mb@7
   127
    
BarthaM@8
   128
    #list the hostonly IFs exposed by the VBox host
mb@7
   129
    def getHostOnlyIFs(self):
mb@11
   130
        cmd = 'VBoxManage list hostonlyifs'
mb@11
   131
        result = self.execute(cmd)[1]
mb@7
   132
        if result=='':
mb@7
   133
            return None
mb@7
   134
        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
mb@7
   135
        return props
mb@7
   136
        
mb@7
   137
    def listRSDS(self):
mb@7
   138
        cmd = 'VBoxManage list usbhost'
mb@12
   139
        results = self.execute(cmd)[1]
mb@7
   140
        results = results.split('Host USB Devices:')[1].strip()
mb@7
   141
        
mb@7
   142
        items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
mb@7
   143
        rsds = dict()   
mb@7
   144
        for item in items:
mb@7
   145
            props = dict()
mb@7
   146
            for line in item.splitlines():
mb@7
   147
                if line != "":         
mb@7
   148
                    k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
mb@7
   149
                    props[k] = v;
mb@7
   150
            
mb@7
   151
            if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
mb@7
   152
                usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'], 
mb@7
   153
                                        re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
mb@7
   154
                                        re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
mb@7
   155
                rsds[props['UUID']] = usb_filter;
mb@7
   156
                if DEBUG:
mb@33
   157
                    print usb_filter
mb@7
   158
        return rsds
mb@7
   159
BarthaM@8
   160
    # list all existing VMs registered with VBox
mb@7
   161
    def listVM(self):
mb@7
   162
        cmd = 'VBoxManage list vms'
mb@11
   163
        result = self.execute(cmd)[1]
mb@7
   164
        vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
mb@7
   165
        return vms
mb@7
   166
    
BarthaM@8
   167
    # list existing SDVMs
mb@7
   168
    def listSDVM(self):
mb@7
   169
        vms = self.listVM()
mb@7
   170
        svdms = []
mb@7
   171
        for vm in vms:
mb@7
   172
            if vm.startswith(self.vmRootName) and vm != self.vmRootName:
mb@7
   173
                svdms.append(vm)
mb@7
   174
        return svdms
mb@7
   175
    
BarthaM@8
   176
    # generate valid (not already existing SDVM name). necessary for creating a new VM
mb@7
   177
    def generateSDVMName(self):
mb@7
   178
        vms = self.listVM()
mb@7
   179
        for i in range(0,999):
mb@7
   180
            if(not self.vmRootName+str(i) in vms):
mb@7
   181
                return self.vmRootName+str(i)
mb@7
   182
        return ''
mb@7
   183
    
BarthaM@8
   184
    # return the RSDs attached to all existing SDVMs
BarthaM@8
   185
    def getAttachedRSDs(self):
BarthaM@8
   186
        vms = self.listSDVM()
BarthaM@8
   187
        attached_devices = dict()
BarthaM@8
   188
        for vm in vms:
BarthaM@8
   189
            rsd_filter = self.getUSBFilter(vm)
mb@12
   190
            if rsd_filter != None:
BarthaM@8
   191
                attached_devices[vm] = rsd_filter
BarthaM@8
   192
        return attached_devices
BarthaM@8
   193
    
BarthaM@8
   194
    # configures hostonly networking and DHCP server. requires admin rights
BarthaM@8
   195
    def configureHostNetworking(self):
BarthaM@8
   196
        #cmd = 'vboxmanage list hostonlyifs'
BarthaM@8
   197
        #self.execute(cmd)
BarthaM@8
   198
        #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
BarthaM@8
   199
        #self.execute(cmd)
BarthaM@8
   200
        #cmd = 'vboxmanage hostonlyif create'
BarthaM@8
   201
        #self.execute(cmd)
mb@33
   202
        cmd = 'VBoxManage hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'
BarthaM@8
   203
        self.execute(cmd)
BarthaM@8
   204
        #cmd = 'vboxmanage dhcpserver add'
BarthaM@8
   205
        #self.execute(cmd)
mb@33
   206
        cmd = 'VBoxManage dhcpserver modify --ifname \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.100 --netmask 255.255.255.0 --lowerip 192.168.56.101 --upperip 192.168.56.200'
BarthaM@8
   207
        self.execute(cmd)
BarthaM@8
   208
    
mb@11
   209
    #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
BarthaM@8
   210
    def createVM(self, vm_name):
BarthaM@8
   211
        hostonly_if = self.getHostOnlyIFs()
BarthaM@8
   212
        machineFolder = self.getDefaultMachineFolder()
mb@11
   213
        cmd = 'VBoxManage createvm --name ' + vm_name + ' --ostype Debian --register'
BarthaM@8
   214
        self.execute(cmd)
mb@11
   215
        cmd = 'VBoxManage modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat' 
BarthaM@8
   216
        self.execute(cmd)
mb@11
   217
        cmd = 'VBoxManage storagectl ' + vm_name + ' --name contr1 --add sata --portcount 2'
BarthaM@8
   218
        self.execute(cmd)
mb@46
   219
        cmd = 'VBoxManage storageattach ' + vm_name + ' --storagectl contr1 --port 0 --device 0 --type hdd --medium \"'+ machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"' #--mtype immutable
BarthaM@8
   220
        self.execute(cmd)
BarthaM@8
   221
        return
BarthaM@8
   222
    
BarthaM@8
   223
    #remove VM from the system. should be used on VMs returned by listSDVMs    
BarthaM@8
   224
    def removeVM(self, vm_name):
BarthaM@8
   225
        print('removing ' + vm_name)
mb@36
   226
        cmd = 'VBoxManage unregistervm ' + vm_name + ' --delete'
BarthaM@8
   227
        print self.execute(cmd)
BarthaM@8
   228
        machineFolder = self.getDefaultMachineFolder()
mb@36
   229
        cmd = self.cygwin_path + 'bash.exe --login -c \"rm -rf ' + machineFolder + '\\' + vm_name + '*\"'
BarthaM@8
   230
        print self.execute(cmd)
BarthaM@8
   231
    
BarthaM@8
   232
    # start VM
BarthaM@8
   233
    def startVM(self, vm_name):
BarthaM@8
   234
        print('starting ' +  vm_name)
mb@40
   235
        cmd = 'VBoxManage startvm ' + vm_name + ' --type headless' 
mb@46
   236
        result = self.execute(cmd)
mb@46
   237
        while not string.find(str(result), 'successfully started',):
mb@46
   238
            print "Failed to start SDVM: ", vm_name, " retrying"
mb@46
   239
            time.sleep(1)
mb@46
   240
            result = self.execute(cmd)
mb@46
   241
        return result[0]
BarthaM@8
   242
        
BarthaM@8
   243
    # stop VM    
BarthaM@8
   244
    def stopVM(self, vm_name):
BarthaM@8
   245
        print('stopping ' + vm_name)
BarthaM@8
   246
        cmd = 'VBoxManage controlvm ' + vm_name + ' poweroff'
mb@46
   247
        self.execute(cmd)
BarthaM@8
   248
    
BarthaM@8
   249
    # return the hostOnly IP for a running guest    
BarthaM@8
   250
    def getHostOnlyIP(self, vm_name):
BarthaM@8
   251
        print('gettting hostOnly IP address ' + vm_name)
BarthaM@8
   252
        cmd = 'VBoxManage guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'
BarthaM@8
   253
        result = self.execute(cmd)
BarthaM@8
   254
        if result=='':
BarthaM@8
   255
            return None
BarthaM@8
   256
        result = result[1]
mb@40
   257
        if result.startswith('No value set!'):
mb@40
   258
            return None
BarthaM@8
   259
        return result[result.index(':')+1:].strip()
BarthaM@8
   260
    
BarthaM@8
   261
    # attach removable storage device to VM by provision of filter
BarthaM@8
   262
    def attachRSD(self, vm_name, rsd_filter):
BarthaM@8
   263
        cmd = 'VBoxManage usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision
BarthaM@8
   264
        print self.execute(cmd)
BarthaM@8
   265
        
BarthaM@8
   266
    
BarthaM@8
   267
    # return the description set for an existing VM
mb@7
   268
    def getVMInfo(self, vm_name):
mb@7
   269
        cmd = 'VBoxManage showvminfo ' + vm_name + ' --machinereadable'
mb@12
   270
        results = self.execute(cmd)[1]
mb@7
   271
        props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
mb@7
   272
        return props
mb@7
   273
    
BarthaM@8
   274
    # return the configured USB filter for an existing VM 
mb@7
   275
    def getUSBFilter(self, vm_name):
mb@7
   276
        props = self.getVMInfo(vm_name)
mb@7
   277
        keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
mb@7
   278
        keyset = set(props.keys())
mb@7
   279
        usb_filter = None
mb@7
   280
        if keyset.issuperset(keys):
mb@7
   281
            usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
mb@7
   282
        return usb_filter
mb@7
   283
    
mb@7
   284
    #generates ISO containing authorized_keys for use with guest VM
mb@7
   285
    def genCertificateISO(self, vm_name):
mb@7
   286
        machineFolder = self.getDefaultMachineFolder()
mb@7
   287
        # create .ssh folder in vm_name
mb@7
   288
        cmd = self.cygwin_path+'bash.exe --login -c \"mkdir -p \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
mb@46
   289
        self.execute(cmd)
mb@7
   290
        # generate dvm_key pair in vm_name / .ssh     
mb@7
   291
        cmd = self.cygwin_path+'bash.exe --login -c \"ssh-keygen -q -t rsa -N \\"\\" -C \\\"' + vm_name + '\\\" -f \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\"\"'   #'echo -e "y\\n" |',
mb@46
   292
        self.execute(cmd)
mb@7
   293
        # set permissions for keys
mb@7
   294
        #TODO: test without chmod
mb@7
   295
        cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\*\\\"\"'
mb@46
   296
        self.execute(cmd)
mb@7
   297
        # move out private key
mb@7
   298
        cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key\\\" \\\"' + machineFolder + '\\' + vm_name + '\\\"'
mb@46
   299
        self.execute(cmd)
mb@7
   300
        # rename public key to authorized_keys
mb@7
   301
        cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\dvm_key.pub\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\authorized_keys\\\"'
mb@46
   302
        self.execute(cmd)
mb@7
   303
        # generate iso image with .ssh/authorized keys
mb@7
   304
        cmd = self.cygwin_path+'bash.exe --login -c \"/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\\\" \\\"' + machineFolder + '\\' + vm_name + '\\.ssh\\\"\"'
mb@46
   305
        self.execute(cmd)
mb@7
   306
    
mb@7
   307
    # attaches generated ssh public cert to guest vm
mb@7
   308
    def attachCertificateISO(self, vm_name):
mb@7
   309
        machineFolder = self.getDefaultMachineFolder()
mb@7
   310
        cmd = 'vboxmanage storageattach ' + vm_name + ' --storagectl contr1 --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'
mb@7
   311
        result = self.execute(cmd)
mb@7
   312
        return result
mb@7
   313
    
mb@36
   314
    handleDeviceChangeLock = threading.Lock()
mb@36
   315
    
mb@7
   316
    # handles device change events
mb@7
   317
    def handleDeviceChange(self):
mb@36
   318
        if VMManager.handleDeviceChangeLock.acquire(True):
mb@36
   319
            #destroy unused vms
mb@40
   320
            new_ip = None
mb@36
   321
            attached_devices = self.getAttachedRSDs()
mb@36
   322
            connected_devices = self.listRSDS()
mb@36
   323
            for vm_name in attached_devices.keys():
mb@36
   324
                if attached_devices[vm_name] not in connected_devices.values():
mb@40
   325
                    self.unmapNetworkDrive('h:')
mb@36
   326
                    self.stopVM(vm_name)
mb@36
   327
                    self.removeVM(vm_name)
mb@36
   328
            #create new vm for attached device if any
mb@36
   329
            attached_devices = self.getAttachedRSDs()
mb@36
   330
            for connected_device in connected_devices.values():
mb@36
   331
                if (attached_devices and False) or (connected_device not in attached_devices.values()):
mb@36
   332
                    new_sdvm = self.generateSDVMName()
mb@36
   333
                    self.createVM(new_sdvm)
mb@36
   334
                    self.attachRSD(new_sdvm, connected_device)
mb@46
   335
mb@46
   336
mb@36
   337
                    self.startVM(new_sdvm)
mb@46
   338
                    # wait for machine to come up
mb@40
   339
                    while new_ip == None:
mb@40
   340
                        time.sleep(1)
mb@40
   341
                        new_ip = self.getHostOnlyIP(new_sdvm)
mb@40
   342
                    while new_ip not in self.startNotifications:
mb@40
   343
                        time.sleep(1)
mb@46
   344
                    if new_ip != None:
mb@46
   345
                        self.mapNetworkDrive('h:', '\\\\' + new_ip + '\\USB', None, None)
mb@40
   346
                    #TODO: cleanup notifications somwhere else (eg. machine shutdown)
mb@40
   347
                    self.startNotifications.remove(new_ip)
mb@36
   348
            VMManager.handleDeviceChangeLock.release()
mb@40
   349
            return new_ip
mb@12
   350
    
mb@12
   351
    def handleBrowsingRequest(self):
mb@46
   352
        if VMManager.handleDeviceChangeLock.acquire(True):
mb@46
   353
            new_ip = None
mb@46
   354
            new_sdvm = self.generateSDVMName()
mb@46
   355
            self.createVM(new_sdvm)
mb@46
   356
            self.genCertificateISO(new_sdvm)
mb@46
   357
            self.attachCertificateISO(new_sdvm)
mb@46
   358
            self.startVM(new_sdvm)
mb@46
   359
            # wait for machine to come up
mb@46
   360
            while new_ip == None:
mb@46
   361
                time.sleep(1)
mb@46
   362
                new_ip = self.getHostOnlyIP(new_sdvm)
mb@46
   363
            while new_ip not in self.startNotifications:
mb@46
   364
                time.sleep(1)
mb@46
   365
            if new_ip != None:
mb@46
   366
                self.mapNetworkDrive('g:', '\\\\' + new_ip + '\\Download', None, None)
mb@46
   367
            #TODO: cleanup notifications somwhere else (eg. machine shutdown)
mb@46
   368
            self.startNotifications.remove(new_ip)
mb@46
   369
            VMManager.handleDeviceChangeLock.release()
om@31
   370
        return new_sdvm
mb@7
   371
    
mb@7
   372
    # executes command over ssh on guest vm
mb@46
   373
    def sshGuestExecute(self, vm_name, prog, user_name='osecuser'):
mb@7
   374
        # get vm ip
mb@7
   375
        address = self.getHostOnlyIP(vm_name)
mb@7
   376
        machineFolder = self.getDefaultMachineFolder()
mb@7
   377
        # run command
BarthaM@8
   378
        cmd = self.cygwin_path+'bash.exe --login -c \"ssh -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\"  ' + user_name + '@' + address + ' ' + prog + '\"'
mb@7
   379
        return self.execute(cmd)
mb@7
   380
    
mb@7
   381
    # executes command over ssh on guest vm with X forwarding
mb@46
   382
    def sshGuestX11Execute(self, vm_name, prog, user_name='osecuser'):
mb@7
   383
        #TODO: verify if X server is running on user account 
mb@7
   384
        #TODO: set DISPLAY accordingly
mb@7
   385
        address = self.getHostOnlyIP(vm_name)
mb@7
   386
        machineFolder = self.getDefaultMachineFolder()
mb@7
   387
        # run command
mb@46
   388
        #--login
mb@46
   389
        #cmd = self.cygwin_path+'bash.exe --login -c \"DISPLAY=:0 ssh -v -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\"  '  + user_name + '@' + address + ' ' + prog + '\"'
mb@46
   390
        cmd = self.cygwin_path+'mintty.exe -e /bin/env DISPLAY=:0 /usr/bin/ssh -v -Y -i \"' + machineFolder + '\\' + vm_name + '\\dvm_key\"  '  + user_name + '@' + address + ' ' + prog + ''
mb@46
   391
        #cmd = self.cygwin_path+'mintty.exe -e /bin/bash --login -c \"DISPLAY=:0 /usr/bin/ssh -v -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\"  '  + user_name + '@' + address + ' ' + prog + '\"'
mb@46
   392
        if DEBUG:
mb@46
   393
            print('trying to launch: ' + cmd)
mb@46
   394
        process = Popen(cmd)
mb@46
   395
        if DEBUG:
mb@46
   396
            print('launched: ' + cmd)
mb@46
   397
        return     
mb@7
   398
    
mb@40
   399
    #Small function to check the availability of network resource.
mb@40
   400
    def isAvailable(self, path):
mb@40
   401
        cmd = 'IF EXIST ' + path + ' echo YES'
mb@40
   402
        result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
mb@40
   403
        return string.find(str(result), 'YES',)
mb@40
   404
    
mb@40
   405
    #Small function to check if the mention location is a directory
mb@40
   406
    def isDirectory(self, path):
mb@40
   407
        cmd = 'dir ' + path + ' | FIND ".."'
mb@40
   408
        result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
mb@40
   409
        return string.find(str(result), 'DIR',)
mb@40
   410
mb@40
   411
    def mapNetworkDrive(self, drive, networkPath, user, password):
mb@40
   412
        self.unmapNetworkDrive('h:')
mb@40
   413
        #Check for drive availability
mb@40
   414
        if self.isAvailable(drive) > -1:
mb@40
   415
            print "Drive letter is already in use: ", drive
mb@40
   416
            return -1
mb@40
   417
        #Check for network resource availability
mb@40
   418
        while self.isAvailable(networkPath) == -1:
mb@40
   419
            time.sleep(1)
mb@40
   420
            print "Path not accessible: ", networkPath, " retrying"
mb@40
   421
            #return -1
mb@40
   422
    
mb@40
   423
        #Prepare 'NET USE' commands
mb@40
   424
        cmd = 'NET USE ' + drive + ' ' + networkPath
mb@40
   425
        if user != None:
mb@40
   426
            cmd = cmd + ' ' + password + ' /User' + user
mb@40
   427
    
mb@40
   428
        print "cmd = ", cmd
mb@40
   429
        #Execute 'NET USE' command with authentication
mb@40
   430
        result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
mb@40
   431
        print "Executed: ", cmd
mb@40
   432
        if string.find(str(result), 'successfully',) == -1:
mb@40
   433
            print cmd, " FAILED"
mb@40
   434
            return -1
mb@40
   435
        #Mapped with first try
mb@40
   436
        return 1
mb@40
   437
    
mb@40
   438
    def unmapNetworkDrive(self, drive):
mb@40
   439
        #Check if the drive is in use
mb@40
   440
        if self.isAvailable(drive) == -1:
mb@40
   441
            #Drive is not in use
mb@40
   442
            return -1
mb@40
   443
        #Prepare 'NET USE' command
mb@40
   444
        cmd = 'net use ' + drive + ' /DELETE'
mb@40
   445
        result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
mb@40
   446
        if string.find(str(result), 'successfully',) == -1:
mb@40
   447
            return -1
mb@40
   448
        return 1
mb@40
   449
mb@40
   450
if __name__ == '__main__':
mb@40
   451
    man = VMManager.getInstance()
mb@40
   452
    #man.removeVM('SecurityDVM0')
mb@40
   453
    #man.netUse('192.168.56.134', 'USB\\')
mb@46
   454
    #ip = '192.168.56.139'
mb@46
   455
    #man.mapNetworkDrive('h:', '\\\\' + ip + '\USB', None, None)
mb@33
   456
    #man.cygwin_path = 'c:\\cygwin64\\bin\\'
mb@7
   457
    #man.handleDeviceChange()
mb@7
   458
    #print man.listSDVM()
mb@11
   459
    #man.configureHostNetworking()
mb@33
   460
    #new_vm = man.generateSDVMName()
mb@33
   461
    #man.createVM(new_vm)
mb@33
   462
    #man.genCertificateISO(new_vm)
mb@33
   463
    #man.attachCertificateISO(new_vm)
mb@11
   464
    
mb@7
   465
    #man.attachCertificateISO(vm_name)
mb@7
   466
    #man.sshGuestExecute(vm_name, "ls")
mb@46
   467
    man.sshGuestX11Execute('SecurityDVM1', '/usr/bin/iceweasel')
mb@46
   468
    time.sleep(60)
mb@7
   469
    #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""
mb@7
   470
    #man.execute(cmd)
mb@33
   471