OpenSecurity/bin/vmmanager.py
author mb
Wed, 29 Jan 2014 15:38:12 +0100
changeset 56 9180aaaf2551
parent 55 42238cd74afe
permissions -rw-r--r--
bugfix in vmmanager.py
     1 '''
     2 Created on Nov 19, 2013
     3 
     4 @author: BarthaM
     5 '''
     6 import os
     7 import os.path
     8 from subprocess import Popen, PIPE, call
     9 import subprocess
    10 import sys
    11 import re
    12 import _winreg
    13 from cygwin import Cygwin
    14 from environment import Environment
    15 import threading
    16 import time
    17 import string
    18 
    19 import shutil
    20 import stat
    21 import tempfile
    22 
    23 
    24 DEBUG = True
    25 class VMManagerException(Exception):
    26     def __init__(self, value):
    27         self.value = value
    28     def __str__(self):
    29         return repr(self.value)
    30 
    31 class USBFilter:
    32     vendorid = ""
    33     productid = ""
    34     revision = ""
    35     
    36     def __init__(self, vendorid, productid, revision):
    37         self.vendorid = vendorid.lower()
    38         self.productid = productid.lower()
    39         self.revision = revision.lower()
    40         return
    41     
    42     def __eq__(self, other):
    43         return self.vendorid == other.vendorid and self.productid == other.productid and self.revision == other.revision
    44     
    45     def __hash__(self):
    46         return hash(self.vendorid) ^ hash(self.productid) ^ hash(self.revision)
    47     
    48     def __repr__(self):
    49         return "VendorId = \'" + str(self.vendorid) + "\' ProductId = \'" + str(self.productid) + "\' Revision = \'" + str(self.revision) + "\'"
    50         
    51 
    52 class VMManager(object):
    53     vmRootName = "SecurityDVM"
    54     systemProperties = None
    55     cygwin_path = 'c:\\cygwin64\\bin\\'
    56     vboxManage = 'VBoxManage'
    57     startNotifications = list()
    58     
    59     _instance = None
    60     #def __new__(cls, *args, **kwargs):
    61     #    if not cls._instance:
    62     #        cls._instance = super(VMManager, cls).__new__(cls, *args, **kwargs)
    63     #    return cls._instance
    64     
    65     _instance = None
    66     #def __new__(cls, *args, **kwargs):
    67     #    if not cls._instance:
    68     #        cls._instance = super(VMManager, cls).__new__(cls, *args, **kwargs)
    69     #    return cls._instance
    70     
    71     def __init__(self):
    72         self.cygwin_path = os.path.join(Cygwin.root(), 'bin') + os.path.sep
    73         self.vboxManage = os.path.join(self.getVBoxManagePath(), 'VBoxManage')
    74         self.systemProperties = self.getSystemProperties()
    75         return
    76     
    77     @staticmethod
    78     def getInstance():
    79         if VMManager._instance == None:
    80             VMManager._instance = VMManager()
    81         return VMManager._instance
    82     
    83     def putStartNotification(self, ip):
    84         self.startNotifications.append(ip)
    85     
    86     def isSDVMStarted(self, ip):
    87         return self.startNotifications.contains(ip)
    88     
    89     def getVBoxManagePath(self):
    90         """get the path to the VirtualBox installation on this system"""
    91         p = None
    92         try:
    93             k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Oracle\VirtualBox')
    94             p = _winreg.QueryValueEx(k, 'InstallDir')[0]
    95             _winreg.CloseKey(k)
    96         except:
    97             pass
    98         return p
    99     
   100     # return hosty system properties
   101     def getSystemProperties(self):
   102         cmd = self.vboxManage + ' list systemproperties'
   103         result = self.hostExecute(cmd)
   104         if result[1]=='':
   105             return None
   106         props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result[1].strip().splitlines()))
   107         return props
   108     
   109     # return the folder containing the guest VMs     
   110     def getDefaultMachineFolder(self):
   111         machineFolder = self.systemProperties["Default machine folder"]
   112         return machineFolder
   113     
   114     #list the hostonly IFs exposed by the VBox host
   115     def getHostOnlyIFs(self):
   116         cmd = 'VBoxManage list hostonlyifs'
   117         result = self.hostExecute(cmd)[1]
   118         if result=='':
   119             return None
   120         props = dict((k.strip(),v.strip().strip('"')) for k,v in (line.split(':', 1) for line in result.strip().splitlines()))
   121         return props
   122         
   123     def listRSDS(self):
   124         cmd = 'VBoxManage list usbhost'
   125         results = self.hostExecute(cmd)[1]
   126         results = results.split('Host USB Devices:')[1].strip()
   127         
   128         items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
   129         rsds = dict()   
   130         for item in items:
   131             props = dict()
   132             for line in item.splitlines():
   133                 if line != "":         
   134                     k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
   135                     props[k] = v;
   136             
   137             if 'Product' in props.keys() and props['Product'] == 'Mass Storage':
   138                 usb_filter = USBFilter( re.search(r"\((?P<vid>[0-9A-Fa-f]+)\)", props['VendorId']).groupdict()['vid'], 
   139                                         re.search(r"\((?P<pid>[0-9A-Fa-f]+)\)", props['ProductId']).groupdict()['pid'],
   140                                         re.search(r"\((?P<rev>[0-9A-Fa-f]+)\)", props['Revision']).groupdict()['rev'] )
   141                 rsds[props['UUID']] = usb_filter;
   142                 if DEBUG:
   143                     print usb_filter
   144         return rsds
   145 
   146     # list all existing VMs registered with VBox
   147     def listVM(self):
   148         cmd = 'VBoxManage list vms'
   149         result = self.hostExecute(cmd)[1]
   150         vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
   151         return vms
   152     
   153     # list running VMs
   154     def listRunningVMS(self):
   155         cmd = 'VBoxManage list runningvms'
   156         result = self.hostExecute(cmd)[1]
   157         vms = list(k.strip().strip('"') for k,_ in (line.split(' ') for line in result.splitlines()))
   158         return vms
   159     
   160     # list existing SDVMs
   161     def listSDVM(self):
   162         vms = self.listVM()
   163         svdms = []
   164         for vm in vms:
   165             if vm.startswith(self.vmRootName) and vm != self.vmRootName:
   166                 svdms.append(vm)
   167         return svdms
   168     
   169     # generate valid (not already existing SDVM name). necessary for creating a new VM
   170     def generateSDVMName(self):
   171         vms = self.listVM()
   172         for i in range(0,999):
   173             if(not self.vmRootName+str(i) in vms):
   174                 return self.vmRootName+str(i)
   175         return ''
   176     
   177     # return the RSDs attached to all existing SDVMs
   178     def getAttachedRSDs(self):
   179         vms = self.listSDVM()
   180         attached_devices = dict()
   181         for vm in vms:
   182             rsd_filter = self.getUSBFilter(vm)
   183             if rsd_filter != None:
   184                 attached_devices[vm] = rsd_filter
   185         return attached_devices
   186     
   187     # configures hostonly networking and DHCP server. requires admin rights
   188     def configureHostNetworking(self):
   189         #cmd = 'vboxmanage list hostonlyifs'
   190         #self.hostExecute(cmd)
   191         #cmd = 'vboxmanage hostonlyif remove \"VirtualBox Host-Only Ethernet Adapter\"'
   192         #self.hostExecute(cmd)
   193         #cmd = 'vboxmanage hostonlyif create'
   194         #self.hostExecute(cmd)
   195         cmd = 'VBoxManage hostonlyif ipconfig \"VirtualBox Host-Only Ethernet Adapter\" --ip 192.168.56.1 --netmask 255.255.255.0'
   196         self.hostExecute(cmd)
   197         #cmd = 'vboxmanage dhcpserver add'
   198         #self.hostExecute(cmd)
   199         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'
   200         self.hostExecute(cmd)
   201     
   202     #create new virtual machine instance based on template vm named SecurityDVM (\SecurityDVM\SecurityDVM.vmdk)
   203     def createVM(self, vm_name):
   204         hostonly_if = self.getHostOnlyIFs()
   205         cmd = 'VBoxManage createvm --name ' + vm_name + ' --ostype Debian --register'
   206         self.hostExecute(cmd)
   207         cmd = 'VBoxManage modifyvm ' + vm_name + ' --memory 512 --vram 10 --cpus 1 --usb on --usbehci on --nic1 hostonly --hostonlyadapter1 \"' + hostonly_if['Name'] + '\" --nic2 nat' 
   208         self.hostExecute(cmd)
   209         cmd = 'VBoxManage storagectl ' + vm_name + ' --name SATA --add sata --portcount 2'
   210         self.hostExecute(cmd)
   211         return
   212     
   213     # attach storage image to controller
   214     def storageAttach(self, vm_name):
   215         if self.isStorageAttached(vm_name):
   216             self.storageDetach(vm_name)
   217         machineFolder = self.getDefaultMachineFolder()
   218         cmd = 'VBoxManage storageattach ' + vm_name + ' --storagectl SATA --port 0 --device 0 --type hdd --medium \"'+ machineFolder + '\SecurityDVM\SecurityDVM.vmdk\"'
   219         self.hostExecute(cmd)
   220         return
   221     
   222     # return true if storage is attached 
   223     def isStorageAttached(self, vm_name):
   224         info = self.getVMInfo(vm_name)
   225         return (info['SATA-0-0']!='none')
   226     
   227     # detach storage from controller
   228     def storageDetach(self, vm_name):
   229         if self.isStorageAttached(vm_name):
   230             cmd = 'VBoxManage storageattach ' + vm_name + ' --storagectl SATA --port 0 --device 0 --type hdd --medium none'
   231             self.hostExecute(cmd)
   232         return
   233     
   234     def changeStorageType(self, filename, type):
   235         cmd = 'VBoxManage modifyhd \"' + filename + '\" --type ' + type
   236         self.hostExecute(cmd)
   237         return
   238     
   239     # list storage snaphots for VM
   240     def updateTemplate(self):
   241         self.poweroffVM('SecurityDVM')
   242         self.waitShutdown('SecurityDVM')
   243         
   244         # check for updates
   245         self.genCertificateISO('SecurityDVM')
   246         self.attachCertificateISO('SecurityDVM')
   247         
   248         self.storageDetach('SecurityDVM')
   249         cmd = 'VBoxManage list hdds'
   250         results = self.hostExecute(cmd)[1]
   251         results = results.replace('Parent UUID', 'Parent')
   252         items = list( "UUID:"+result for result in results.split('UUID:') if result != '')
   253         
   254         snaps = dict()   
   255         for item in items:
   256             #print item
   257             props = dict()
   258             for line in item.splitlines():
   259                 if line != "":         
   260                     k,v = line[:line.index(':')].strip(), line[line.index(':')+1:].strip()
   261                     props[k] = v;
   262             snaps[props['UUID']] = props
   263         
   264         machineFolder = self.getDefaultMachineFolder()
   265         template_storage = machineFolder + '\SecurityDVM\SecurityDVM.vmdk'
   266         
   267         # find template uuid
   268         template_uuid = ''
   269         for hdd in snaps.values():
   270             if hdd['Location'] == template_storage:
   271                 template_uuid = hdd['UUID']
   272         print 'found parent uuid ' + template_uuid
   273         
   274         # remove snapshots 
   275         for hdd in snaps.values():
   276             if hdd['Parent'] == template_uuid:
   277                 #template_uuid = hdd['UUID']
   278                 print 'removing snapshot ' + hdd['UUID']
   279                 cmd = 'VBoxManage closemedium disk {' + hdd['UUID'] + '} --delete'
   280                 results = self.hostExecute(cmd)[1]
   281                 # parse result 0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%
   282         
   283         self.changeStorageType(template_storage,'normal')
   284         self.storageAttach('SecurityDVM')
   285         self.startVM('SecurityDVM')
   286         self.waitStartup('SecurityDVM')
   287         self.guestExecute('SecurityDVM', 'sudo apt-get -y update' )
   288         self.guestExecute('SecurityDVM', 'sudo apt-get -y upgrade' )
   289         self.stopVM('SecurityDVM')
   290         self.waitShutdown('SecurityDVM')
   291         self.storageDetach('SecurityDVM')
   292         self.changeStorageType(template_storage,'immutable')
   293         self.storageAttach('SecurityDVM')
   294         
   295     
   296     #remove VM from the system. should be used on VMs returned by listSDVMs    
   297     def removeVM(self, vm_name):
   298         print('removing ' + vm_name)
   299         cmd = 'VBoxManage unregistervm ' + vm_name + ' --delete'
   300         print self.hostExecute(cmd)
   301         machineFolder = self.getDefaultMachineFolder()
   302         cmd = self.cygwin_path + 'bash.exe --login -c \"rm -rf ' + machineFolder + '\\' + vm_name + '*\"'
   303         print self.hostExecute(cmd)
   304     
   305     # start VM
   306     def startVM(self, vm_name):
   307         print('starting ' +  vm_name)
   308         cmd = 'VBoxManage startvm ' + vm_name + ' --type headless' 
   309         result = self.hostExecute(cmd)
   310         while not string.find(str(result), 'successfully started',):
   311             print "Failed to start SDVM: ", vm_name, " retrying"
   312             time.sleep(1)
   313             result = self.hostExecute(cmd)
   314         return result[0]
   315     
   316     # return wether VM is running or not
   317     def isVMRunning(self, vm_name):
   318         return vm_name in self.listRunningVMS()    
   319     
   320     # stop VM
   321     def stopVM(self, vm_name):
   322         print('stopping ' + vm_name)
   323         cmd = 'sudo shutdown -h now'
   324         self.guestExecute('SecurityDVM', cmd)
   325             
   326     # poweroff VM
   327     def poweroffVM(self, vm_name):
   328         if not self.isVMRunning(vm_name):
   329             return
   330         print('powering off ' + vm_name)
   331         cmd = 'VBoxManage controlvm ' + vm_name + ' poweroff'
   332         self.hostExecute(cmd)
   333     
   334     # return the hostOnly IP for a running guest    
   335     def getHostOnlyIP(self, vm_name):
   336         print('gettting hostOnly IP address ' + vm_name)
   337         cmd = 'VBoxManage guestproperty get ' + vm_name + ' /VirtualBox/GuestInfo/Net/0/V4/IP'
   338         result = self.hostExecute(cmd)
   339         if result=='':
   340             return None
   341         result = result[1]
   342         if result.startswith('No value set!'):
   343             return None
   344         return result[result.index(':')+1:].strip()
   345     
   346     # attach removable storage device to VM by provision of filter
   347     def attachRSD(self, vm_name, rsd_filter):
   348         cmd = 'VBoxManage usbfilter add 0 --target ' + vm_name + ' --name OpenSecurityRSD --vendorid ' + rsd_filter.vendorid + ' --productid ' + rsd_filter.productid + ' --revision ' + rsd_filter.revision
   349         print self.hostExecute(cmd)
   350         
   351     
   352     # return the description set for an existing VM
   353     def getVMInfo(self, vm_name):
   354         cmd = 'VBoxManage showvminfo ' + vm_name + ' --machinereadable'
   355         results = self.hostExecute(cmd)[1]
   356         props = dict((k.strip().strip('"'),v.strip().strip('"')) for k,v in (line.split('=', 1) for line in results.splitlines()))
   357         return props
   358     
   359     # return the configured USB filter for an existing VM 
   360     def getUSBFilter(self, vm_name):
   361         props = self.getVMInfo(vm_name)
   362         keys = set(['USBFilterVendorId1', 'USBFilterProductId1', 'USBFilterRevision1'])
   363         keyset = set(props.keys())
   364         usb_filter = None
   365         if keyset.issuperset(keys):
   366             usb_filter = USBFilter(props['USBFilterVendorId1'], props['USBFilterProductId1'], props['USBFilterRevision1'])
   367         return usb_filter
   368     
   369     #generates ISO containing authorized_keys for use with guest VM
   370     def genCertificateISO(self, vm_name):
   371         machineFolder = self.getDefaultMachineFolder()
   372         machineFolder = self.cygwinPath(machineFolder)
   373         # remove .ssh folder if exists
   374         cmd = self.cygwin_path+'bash.exe --login -c \"rm -rf \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"\"'
   375         self.hostExecute(cmd)
   376         # remove .ssh folder if exists
   377         cmd = self.cygwin_path+'bash.exe --login -c \"rm -rf \\\"' + machineFolder + '/' + vm_name + '/dvm_key\\\"\"'
   378         self.hostExecute(cmd)
   379         # create .ssh folder in vm_name
   380         cmd = self.cygwin_path+'bash.exe --login -c \"mkdir -p \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"\"'
   381         self.hostExecute(cmd)
   382         # generate dvm_key pair in vm_name / .ssh     
   383         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" |',
   384         self.hostExecute(cmd)
   385         # move out private key
   386         cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key\\\" \\\"' + machineFolder + '/' + vm_name + '\\\"'
   387         self.hostExecute(cmd)
   388         # set permissions for private key
   389         cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '/' + vm_name + '/dvm_key\\\"\"'
   390         self.hostExecute(cmd)
   391         # rename public key to authorized_keys
   392         cmd = self.cygwin_path+'bash.exe --login -c \"mv \\\"' + machineFolder + '/' + vm_name + '/.ssh/dvm_key.pub\\\" \\\"' + machineFolder + '/' + vm_name + '/.ssh/authorized_keys\\\"'
   393         self.hostExecute(cmd)
   394         # set permissions for authorized_keys
   395         cmd = self.cygwin_path+'bash.exe --login -c \"chmod 500 \\\"' + machineFolder + '/' + vm_name + '/.ssh/authorized_keys\\\"\"'
   396         self.hostExecute(cmd)
   397         # generate iso image with .ssh/authorized keys
   398         cmd = self.cygwin_path+'bash.exe --login -c \"/usr/bin/genisoimage -J -R -o \\\"' + machineFolder + '/' + vm_name + '/'+ vm_name + '.iso\\\" \\\"' + machineFolder + '/' + vm_name + '/.ssh\\\"\"'
   399         self.hostExecute(cmd)
   400     
   401     # attaches generated ssh public cert to guest vm
   402     def attachCertificateISO(self, vm_name):
   403         machineFolder = self.getDefaultMachineFolder()
   404         cmd = 'vboxmanage storageattach ' + vm_name + ' --storagectl SATA --port 1 --device 0 --type dvddrive --mtype readonly --medium \"' + machineFolder + '\\' + vm_name + '\\'+ vm_name + '.iso\"'
   405         result = self.hostExecute(cmd)
   406         return result
   407     
   408     handleDeviceChangeLock = threading.Lock()
   409     
   410     # handles device change events
   411     def handleDeviceChange(self):
   412         if VMManager.handleDeviceChangeLock.acquire(True):
   413             #destroy unused vms
   414             new_ip = None
   415             attached_devices = self.getAttachedRSDs()
   416             connected_devices = self.listRSDS()
   417             for vm_name in attached_devices.keys():
   418                 if attached_devices[vm_name] not in connected_devices.values():
   419                     self.unmapNetworkDrive('h:')
   420                     self.stopVM(vm_name)
   421                     self.removeVM(vm_name)
   422             #create new vm for attached device if any
   423             attached_devices = self.getAttachedRSDs()
   424             for connected_device in connected_devices.values():
   425                 if (attached_devices and False) or (connected_device not in attached_devices.values()):
   426                     new_sdvm = self.generateSDVMName()
   427                     self.createVM(new_sdvm)
   428                     self.storageAttach(new_sdvm)
   429                     self.attachRSD(new_sdvm, connected_device)
   430                     self.startVM(new_sdvm)
   431                     # wait for machine to come up
   432                     while new_ip == None:
   433                         time.sleep(1)
   434                         new_ip = self.getHostOnlyIP(new_sdvm)
   435                     while new_ip not in self.startNotifications:
   436                         time.sleep(1)
   437                     if new_ip != None:
   438                         self.mapNetworkDrive('h:', '\\\\' + new_ip + '\\USB', None, None)
   439                     #TODO: cleanup notifications somwhere else (eg. machine shutdown)
   440                     self.startNotifications.remove(new_ip)
   441             VMManager.handleDeviceChangeLock.release()
   442             return new_ip
   443     
   444     # wait for machine to come up
   445     def waitStartup(self, vm_name): 
   446         new_ip = None
   447         while new_ip == None:
   448             time.sleep(1)
   449             new_ip = self.getHostOnlyIP(vm_name)
   450         while new_ip not in self.startNotifications:
   451             time.sleep(1)
   452         return new_ip
   453     
   454     # wait for machine to shutdown
   455     def waitShutdown(self, vm_name):
   456         while vm_name in self.listRunningVMS():
   457             time.sleep(1)
   458         return
   459         
   460     # handles browsing request    
   461     def handleBrowsingRequest(self):
   462         if VMManager.handleDeviceChangeLock.acquire(True):
   463             new_sdvm = self.generateSDVMName()
   464             self.createVM(new_sdvm)
   465             self.storageAttach(new_sdvm)
   466             self.genCertificateISO(new_sdvm)
   467             self.attachCertificateISO(new_sdvm)
   468             self.startVM(new_sdvm)
   469             new_ip = self.waitStartup(new_sdvm)
   470             if new_ip != None:
   471                 self.mapNetworkDrive('g:', '\\\\' + new_ip + '\\Download', None, None)
   472             #TODO: cleanup notifications somwhere else (eg. machine shutdown)
   473             self.startNotifications.remove(new_ip)
   474             VMManager.handleDeviceChangeLock.release()
   475         return new_sdvm
   476     
   477     def cygwinPath(self, path):
   478         # TODO: test if env ist cygwin
   479         cmd = self.cygwin_path + 'bash.exe --login -c \"cygpath -u \\\"' + path + '\\\"\"' 
   480         return self.hostExecute(cmd)[1].rstrip('\n')
   481     
   482     #executes command on host system
   483     def hostExecute(self, cmd, wait_return=True ):
   484         if DEBUG:
   485             print('trying to launch: ' + cmd)
   486         process = Popen(cmd, stdout=PIPE, stderr=PIPE) #shell = True
   487         if DEBUG:
   488             print('launched: ' + cmd)
   489         if not wait_return:
   490             return [0, 'working in background', '']
   491         result = process.wait()
   492         res_stdout = process.stdout.read();
   493         res_stderr = process.stderr.read();
   494         if DEBUG:
   495             if res_stdout != "":
   496                 print res_stdout
   497             if res_stderr != "":
   498                 print res_stderr
   499         if result !=0:
   500             raise VMManagerException(res_stderr)
   501         return result, res_stdout, res_stderr
   502     
   503     # executes command over ssh on guest vm
   504     def guestExecute(self, vm_name, prog, user_name='osecuser'):
   505         # get vm ip
   506         address = self.getHostOnlyIP(vm_name)
   507         machineFolder = self.getDefaultMachineFolder()
   508         machineFolder = self.cygwinPath(machineFolder)
   509         # run command //mintty.exe -e
   510         cmd = self.cygwin_path + 'bash.exe --login -c \"/usr/bin/ssh -v -i \\\"' + machineFolder + '/' + vm_name + '/dvm_key\\\"  ' + user_name + '@' + address + ' ' + prog + '\"'
   511         return self.hostExecute(cmd)
   512     
   513     # executes command over ssh on guest vm with X forwarding
   514     def guestExecuteX11(self, vm_name, prog, user_name='osecuser'):
   515         #TODO: verify if X server is running on user account 
   516         #TODO: set DISPLAY accordingly
   517         address = self.getHostOnlyIP(vm_name)
   518         machineFolder = self.getDefaultMachineFolder()
   519         # run command
   520         #--login
   521         #cmd = self.cygwin_path+'bash.exe --login -c \"DISPLAY=:0 ssh -v -Y -i \\\"' + machineFolder + '\\' + vm_name + '\\dvm_key\\\"  '  + user_name + '@' + address + ' ' + prog + '\"'
   522         cmd = self.cygwin_path+'mintty.exe -e /bin/env DISPLAY=:0 /usr/bin/ssh -o StrictHostKeyChecking=no -v -Y -i \"' + machineFolder + '\\' + vm_name + '\\dvm_key\"  '  + user_name + '@' + address + ' ' + prog + ''
   523         #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 + '\"'
   524         if DEBUG:
   525             print('trying to launch: ' + cmd)
   526         process = Popen(cmd)
   527         if DEBUG:
   528             print('launched: ' + cmd)
   529         return     
   530     
   531     #Small function to check the availability of network resource.
   532     def isAvailable(self, path):
   533         cmd = 'IF EXIST ' + path + ' echo YES'
   534         result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
   535         return string.find(str(result), 'YES',)
   536     
   537     #Small function to check if the mention location is a directory
   538     def isDirectory(self, path):
   539         cmd = 'dir ' + path + ' | FIND ".."'
   540         result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
   541         return string.find(str(result), 'DIR',)
   542 
   543     def mapNetworkDrive(self, drive, networkPath, user, password):
   544         self.unmapNetworkDrive(drive)
   545         #Check for drive availability
   546         if self.isAvailable(drive) > -1:
   547             print "Drive letter is already in use: ", drive
   548             return -1
   549         #Check for network resource availability
   550         while self.isAvailable(networkPath) == -1:
   551             time.sleep(1)
   552             print "Path not accessible: ", networkPath, " retrying"
   553             #return -1
   554     
   555         #Prepare 'NET USE' commands
   556         cmd = 'NET USE ' + drive + ' ' + networkPath
   557         if user != None:
   558             cmd = cmd + ' ' + password + ' /User' + user
   559     
   560         print "cmd = ", cmd
   561         #Execute 'NET USE' command with authentication
   562         result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
   563         print "Executed: ", cmd
   564         if string.find(str(result), 'successfully',) == -1:
   565             print cmd, " FAILED"
   566             return -1
   567         #Mapped with first try
   568         return 1
   569     
   570     def unmapNetworkDrive(self, drive):
   571         #Check if the drive is in use
   572         if self.isAvailable(drive) == -1:
   573             #Drive is not in use
   574             return -1
   575         #Prepare 'NET USE' command
   576         cmd = 'net use ' + drive + ' /DELETE'
   577         result = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True).communicate()
   578         if string.find(str(result), 'successfully',) == -1:
   579             return -1
   580         return 1
   581 
   582 
   583 if __name__ == '__main__':
   584     man = VMManager.getInstance()
   585     #man.removeVM('SecurityDVM0')
   586     #man.netUse('192.168.56.134', 'USB\\')
   587     #ip = '192.168.56.139'
   588     #man.mapNetworkDrive('h:', '\\\\' + ip + '\USB', None, None)
   589     #man.cygwin_path = 'c:\\cygwin64\\bin\\'
   590     #man.handleDeviceChange()
   591     #print man.listSDVM()
   592     #man.configureHostNetworking()
   593     #new_vm = man.generateSDVMName()
   594     #man.createVM(new_vm)
   595     #man.genCertificateISO(new_vm)
   596     #man.attachCertificateISO(new_vm)
   597     
   598     #man.attachCertificateISO(vm_name)
   599     #man.guestExecute(vm_name, "ls")
   600     #man.sshGuestX11Execute('SecurityDVM1', '/usr/bin/iceweasel')
   601     #time.sleep(60)
   602     #print man.cygwinPath("C:\Users\BarthaM\VirtualBox VMs\SecurityDVM\.ssh\*")
   603     #man.genCertificateISO('SecurityDVM')
   604     #man.attachCertificateISO('SecurityDVM')
   605     #man.isStorageAttached('SecurityDVM')
   606     #man.guestExecute('SecurityDVM', 'sudo apt-get -y update')
   607     #man.guestExecute('SecurityDVM', 'sudo apt-get -y upgrade' )
   608     
   609     #man.stopVM('SecurityDVM')
   610     #man.storageDetach('SecurityDVM')
   611     #man.changeStorageType('C:\Users\BarthaM\VirtualBox VMs\SecurityDVM\SecurityDVM.vmdk','immutable')
   612     #man.storageAttach('SecurityDVM')
   613     
   614     
   615     #cmd = "c:\\cygwin64\\bin\\bash.exe --login -c \"/bin/ls\""
   616     #man.execute(cmd)
   617