OpenSecurity/bin/cygwin.py
changeset 87 d5b04809faca
parent 79 617009c32da0
child 90 bfd41c38d156
     1.1 --- a/OpenSecurity/bin/cygwin.py	Wed Feb 26 17:27:07 2014 +0100
     1.2 +++ b/OpenSecurity/bin/cygwin.py	Tue Mar 04 16:54:51 2014 +0100
     1.3 @@ -1,229 +1,229 @@
     1.4 -#!/bin/env python
     1.5 -# -*- coding: utf-8 -*-
     1.6 -
     1.7 -# ------------------------------------------------------------
     1.8 -# cygwin command
     1.9 -# 
    1.10 -# executes a cygwin command inside the opensecurity project
    1.11 -#
    1.12 -# Autor: Mihai Bartha, <mihai.bartha@ait.ac.at>
    1.13 -#        Oliver Maurhart, <oliver.maurhart@ait.ac.at>
    1.14 -#
    1.15 -# Copyright (C) 2013 AIT Austrian Institute of Technology
    1.16 -# AIT Austrian Institute of Technology GmbH
    1.17 -# Donau-City-Strasse 1 | 1220 Vienna | Austria
    1.18 -# http://www.ait.ac.at
    1.19 -#
    1.20 -# This program is free software; you can redistribute it and/or
    1.21 -# modify it under the terms of the GNU General Public License
    1.22 -# as published by the Free Software Foundation version 2.
    1.23 -# 
    1.24 -# This program is distributed in the hope that it will be useful,
    1.25 -# but WITHOUT ANY WARRANTY; without even the implied warranty of
    1.26 -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    1.27 -# GNU General Public License for more details.
    1.28 -# 
    1.29 -# You should have received a copy of the GNU General Public License
    1.30 -# along with this program; if not, write to the Free Software
    1.31 -# Foundation, Inc., 51 Franklin Street, Fifth Floor, 
    1.32 -# Boston, MA  02110-1301, USA.
    1.33 -# ------------------------------------------------------------
    1.34 -
    1.35 -
    1.36 -# ------------------------------------------------------------
    1.37 -# imports
    1.38 -
    1.39 -import os
    1.40 -import subprocess
    1.41 -import sys
    1.42 -import _winreg
    1.43 -from subprocess import Popen, PIPE, call, STARTUPINFO, _subprocess
    1.44 -import threading
    1.45 -# local
    1.46 -from environment import Environment
    1.47 -from opensecurity_util import logger, setupLogger, OpenSecurityException
    1.48 -
    1.49 -# ------------------------------------------------------------
    1.50 -# code
    1.51 -
    1.52 -def once(theClass):
    1.53 -    """get the path to our local cygwin installment"""
    1.54 -    home_drive = os.path.expandvars("%HOMEDRIVE%") + os.sep
    1.55 -    path_hint = [ 
    1.56 -        os.path.abspath(os.path.join(Environment('OpenSecurity').prefix_path, '..', 'cygwin')), 
    1.57 -        os.path.abspath(os.path.join(Environment('OpenSecurity').prefix_path, '..', 'cygwin64')), 
    1.58 -        os.path.abspath(os.path.join(home_drive, 'cygwin')),
    1.59 -        os.path.abspath(os.path.join(home_drive, 'cygwin64'))
    1.60 -    ]
    1.61 -    path_valid = [ p for p in path_hint if os.path.exists(p) ]
    1.62 -        
    1.63 -    theClass.cygwin_root = path_valid[0]
    1.64 -    theClass.cygwin_bin = os.path.join(theClass.cygwin_root, 'bin') + os.path.sep
    1.65 -    theClass.cygwin_bash = os.path.join(theClass.cygwin_bin, 'bash.exe')
    1.66 -    theClass.cygwin_ssh = os.path.join(theClass.cygwin_bin, 'ssh.exe')
    1.67 -    theClass.cygwin_x11 = os.path.join(theClass.cygwin_bin, 'XWin.exe')
    1.68 -    theClass.win_cmd = os.environ.get("COMSPEC", "cmd.exe") 
    1.69 -    
    1.70 -    """get the path to the VirtualBox installation on this system"""
    1.71 -    try:
    1.72 -        k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Oracle\VirtualBox')
    1.73 -        theClass.vbox_root = _winreg.QueryValueEx(k, 'InstallDir')[0]
    1.74 -        theClass.vbox_man = os.path.join(theClass.vbox_root, 'VBoxManage.exe')
    1.75 -        _winreg.CloseKey(k)
    1.76 -    except:
    1.77 -        pass
    1.78 -    return theClass
    1.79 -
    1.80 -@once
    1.81 -class Cygwin(object):
    1.82 -    cygwin_root = ''
    1.83 -    cygwin_bin = ''
    1.84 -    cygwin_bash = ''
    1.85 -    cygwin_ssh = ''
    1.86 -    cygwin_x11 = ''
    1.87 -    vbox_root = ''
    1.88 -    vbox_man = ''
    1.89 -    win_cmd = ''
    1.90 -    """Some nifty methods working with Cygwin"""
    1.91 -    
    1.92 -    def __call__(self, command, arguments, wait_return=True, window = False):
    1.93 -        """make an instance of this object act as a function"""
    1.94 -        return self.execute(command, arguments, wait_return, window)
    1.95 -
    1.96 -        
    1.97 -    @staticmethod
    1.98 -    def root():
    1.99 -        return Cygwin.cygwin_root
   1.100 -
   1.101 -    @staticmethod
   1.102 -    def bin():
   1.103 -        return Cygwin.cygwin_bin
   1.104 -    
   1.105 -    @staticmethod
   1.106 -    def bash():
   1.107 -        return Cygwin.cygwin_bash
   1.108 -    
   1.109 -    @staticmethod    
   1.110 -    def ssh():
   1.111 -        return Cygwin.cygwin_ssh
   1.112 -
   1.113 -    @staticmethod    
   1.114 -    def x11():
   1.115 -        return Cygwin.cygwin_x11
   1.116 -    
   1.117 -    @staticmethod
   1.118 -    def vboxman():
   1.119 -        return Cygwin.vbox_man
   1.120 -    
   1.121 -    @staticmethod
   1.122 -    def cmd():
   1.123 -        return Cygwin.win_cmd
   1.124 -    
   1.125 -    executeLock = threading.Lock()
   1.126 -    #executes command on host system
   1.127 -    @staticmethod
   1.128 -    def execute(program, arguments, wait_return=True, window = False):
   1.129 -        _startupinfo = STARTUPINFO()
   1.130 -        if not window:
   1.131 -            _startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
   1.132 -            _startupinfo.wShowWindow = _subprocess.SW_HIDE
   1.133 -
   1.134 -            #logger.debug('trying to launch: ' + program + ' ' + ''.join(arguments))
   1.135 -        res_stderr = None
   1.136 -        try:
   1.137 -            process = Popen(executable=program, args=' ' + arguments, startupinfo = _startupinfo, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell = False)
   1.138 -            logger.debug('Launched: ' + program + ' ' + ''.join(arguments))
   1.139 -            if not wait_return:
   1.140 -                return [0, 'working in background', '']
   1.141 -            result = process.wait()
   1.142 -            res_stdout = process.stdout.read();
   1.143 -            res_stderr = process.stderr.read();
   1.144 -
   1.145 -        except Exception as ex:
   1.146 -            res_stderr = ''.join(ex.args)
   1.147 -            result = -1 
   1.148 -        
   1.149 -        if result != 0:
   1.150 -            logger.error('Failed to execute cygwin command.\n\tcommand=' + program + ' ' + ''.join(arguments) + '\n' + res_stderr)
   1.151 -            raise OpenSecurityException('Failed to execute cygwin command.\n\tcommand=' + program + ' ' + ''.join(arguments) + '\n' + res_stderr)
   1.152 -            
   1.153 -        return result, res_stdout, res_stderr
   1.154 -    
   1.155 -    @staticmethod
   1.156 -    def vboxExecute(command, wait_return=True, window = False, bash_opts=''):
   1.157 -        if Cygwin.executeLock.acquire(True):
   1.158 -            retry = 0
   1.159 -            while retry < 3:
   1.160 -                try:
   1.161 -                    result = Cygwin.execute(Cygwin.vbox_man, command, wait_return, window)
   1.162 -                    Cygwin.executeLock.release()
   1.163 -                    return result
   1.164 -                except OpenSecurityException as inst:
   1.165 -                    retry+=1
   1.166 -            Cygwin.executeLock.release()
   1.167 -            raise inst
   1.168 -        return result
   1.169 -        
   1.170 -    
   1.171 -    @staticmethod
   1.172 -    def bashExecute(command, wait_return=True, window = False, bash_opts=''):
   1.173 -        command = bash_opts + ' -l -c '  + command
   1.174 -        return Cygwin.execute(Cygwin.cygwin_bash, command, wait_return, window)
   1.175 -    
   1.176 -    @staticmethod
   1.177 -    def cmdExecute(command, wait_return=True, window = False, bash_opts=''):
   1.178 -        command = ' /c ' + command 
   1.179 -        return Cygwin.execute(Cygwin.win_cmd, command, wait_return, window)
   1.180 -
   1.181 -    # executes command over ssh on guest vm
   1.182 -    @staticmethod
   1.183 -    def sshExecute(command, address, user_name, certificate, wait_return=True, window = False):
   1.184 -        command = ' -v -i "' + certificate + '" ' + user_name + '@' + address + ' ' + command        
   1.185 -        return Cygwin.execute(Cygwin.cygwin_ssh, command, wait_return, window)     
   1.186 -    
   1.187 -    #machineFolder + '/' + vm_name + '/dvm_key
   1.188 -    #address = self.getHostOnlyIP(vm_name)
   1.189 -    #machineFolder = self.getDefaultMachineFolder()
   1.190 -    #machineFolder = Cygwin.cygwinPath(machineFolder)
   1.191 -    
   1.192 -    # executes command over ssh on guest vm with X forwarding
   1.193 -    @staticmethod
   1.194 -    def sshExecuteX11(command, address, user_name, certificate, wait_return=True):
   1.195 -        return Cygwin.bashExecute('"DISPLAY=:0.0 /usr/bin/ssh -v -Y -i \\"' + certificate +'\\" ' + user_name + '@' + address + ' ' + command + '\"')
   1.196 -
   1.197 -    @staticmethod
   1.198 -    def is_X11_running():
   1.199 -        """check if we can connect to a X11 running instance"""
   1.200 -        p = Cygwin.bashExecute('"DISPLAY=:0 /usr/bin/xset -q"')
   1.201 -        return p[0] == 0
   1.202 -        
   1.203 -        
   1.204 -    @staticmethod
   1.205 -    def start_X11():
   1.206 -        """start X11 in the background (if not already running) on DISPLAY=:0"""
   1.207 -        # do not start if already running
   1.208 -        if Cygwin.is_X11_running():
   1.209 -            return           
   1.210 -        # launch X11 (forget output and return immediately)
   1.211 -        return Cygwin.execute(Cygwin.cygwin_x11, ':0 -multiwindow', wait_return = False, window = False)
   1.212 -    
   1.213 -    @staticmethod    
   1.214 -    def cygPath(path):
   1.215 -        cmd = '"/usr/bin/cygpath -u \\"' + path + '\\""'
   1.216 -        return Cygwin.bashExecute(cmd)[1].rstrip('\n')
   1.217 -    
   1.218 -# start
   1.219 -if __name__ == "__main__":
   1.220 -    logger = setupLogger('Cygwin')
   1.221 -    c = Cygwin()
   1.222 -    logger.info(c.root())
   1.223 -    logger.info(c.bin())
   1.224 -    logger.info(c.bash())
   1.225 -    logger.info(c.ssh())
   1.226 -    
   1.227 -    c.cygPath('C:')
   1.228 -    c.start_X11()
   1.229 -
   1.230 -        
   1.231 -    
   1.232 -    
   1.233 +#!/bin/env python
   1.234 +# -*- coding: utf-8 -*-
   1.235 +
   1.236 +# ------------------------------------------------------------
   1.237 +# cygwin command
   1.238 +# 
   1.239 +# executes a cygwin command inside the opensecurity project
   1.240 +#
   1.241 +# Autor: Mihai Bartha, <mihai.bartha@ait.ac.at>
   1.242 +#        Oliver Maurhart, <oliver.maurhart@ait.ac.at>
   1.243 +#
   1.244 +# Copyright (C) 2013 AIT Austrian Institute of Technology
   1.245 +# AIT Austrian Institute of Technology GmbH
   1.246 +# Donau-City-Strasse 1 | 1220 Vienna | Austria
   1.247 +# http://www.ait.ac.at
   1.248 +#
   1.249 +# This program is free software; you can redistribute it and/or
   1.250 +# modify it under the terms of the GNU General Public License
   1.251 +# as published by the Free Software Foundation version 2.
   1.252 +# 
   1.253 +# This program is distributed in the hope that it will be useful,
   1.254 +# but WITHOUT ANY WARRANTY; without even the implied warranty of
   1.255 +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   1.256 +# GNU General Public License for more details.
   1.257 +# 
   1.258 +# You should have received a copy of the GNU General Public License
   1.259 +# along with this program; if not, write to the Free Software
   1.260 +# Foundation, Inc., 51 Franklin Street, Fifth Floor, 
   1.261 +# Boston, MA  02110-1301, USA.
   1.262 +# ------------------------------------------------------------
   1.263 +
   1.264 +
   1.265 +# ------------------------------------------------------------
   1.266 +# imports
   1.267 +
   1.268 +import os
   1.269 +import subprocess
   1.270 +import sys
   1.271 +import _winreg
   1.272 +from subprocess import Popen, PIPE, call, STARTUPINFO, _subprocess
   1.273 +import threading
   1.274 +# local
   1.275 +from environment import Environment
   1.276 +from opensecurity_util import logger, setupLogger, OpenSecurityException
   1.277 +
   1.278 +# ------------------------------------------------------------
   1.279 +# code
   1.280 +
   1.281 +def once(theClass):
   1.282 +    """get the path to our local cygwin installment"""
   1.283 +    home_drive = os.path.expandvars("%HOMEDRIVE%") + os.sep
   1.284 +    path_hint = [ 
   1.285 +        os.path.abspath(os.path.join(Environment('OpenSecurity').prefix_path, '..', 'cygwin')), 
   1.286 +        os.path.abspath(os.path.join(Environment('OpenSecurity').prefix_path, '..', 'cygwin64')), 
   1.287 +        os.path.abspath(os.path.join(home_drive, 'cygwin')),
   1.288 +        os.path.abspath(os.path.join(home_drive, 'cygwin64'))
   1.289 +    ]
   1.290 +    path_valid = [ p for p in path_hint if os.path.exists(p) ]
   1.291 +        
   1.292 +    theClass.cygwin_root = path_valid[0]
   1.293 +    theClass.cygwin_bin = os.path.join(theClass.cygwin_root, 'bin') + os.path.sep
   1.294 +    theClass.cygwin_bash = os.path.join(theClass.cygwin_bin, 'bash.exe')
   1.295 +    theClass.cygwin_ssh = os.path.join(theClass.cygwin_bin, 'ssh.exe')
   1.296 +    theClass.cygwin_x11 = os.path.join(theClass.cygwin_bin, 'XWin.exe')
   1.297 +    theClass.win_cmd = os.environ.get("COMSPEC", "cmd.exe") 
   1.298 +    
   1.299 +    """get the path to the VirtualBox installation on this system"""
   1.300 +    try:
   1.301 +        k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\Oracle\VirtualBox')
   1.302 +        theClass.vbox_root = _winreg.QueryValueEx(k, 'InstallDir')[0]
   1.303 +        theClass.vbox_man = os.path.join(theClass.vbox_root, 'VBoxManage.exe')
   1.304 +        _winreg.CloseKey(k)
   1.305 +    except:
   1.306 +        pass
   1.307 +    return theClass
   1.308 +
   1.309 +@once
   1.310 +class Cygwin(object):
   1.311 +    cygwin_root = ''
   1.312 +    cygwin_bin = ''
   1.313 +    cygwin_bash = ''
   1.314 +    cygwin_ssh = ''
   1.315 +    cygwin_x11 = ''
   1.316 +    vbox_root = ''
   1.317 +    vbox_man = ''
   1.318 +    win_cmd = ''
   1.319 +    """Some nifty methods working with Cygwin"""
   1.320 +    
   1.321 +    def __call__(self, command, arguments, wait_return=True, window = False):
   1.322 +        """make an instance of this object act as a function"""
   1.323 +        return self.execute(command, arguments, wait_return, window)
   1.324 +
   1.325 +        
   1.326 +    @staticmethod
   1.327 +    def root():
   1.328 +        return Cygwin.cygwin_root
   1.329 +
   1.330 +    @staticmethod
   1.331 +    def bin():
   1.332 +        return Cygwin.cygwin_bin
   1.333 +    
   1.334 +    @staticmethod
   1.335 +    def bash():
   1.336 +        return Cygwin.cygwin_bash
   1.337 +    
   1.338 +    @staticmethod    
   1.339 +    def ssh():
   1.340 +        return Cygwin.cygwin_ssh
   1.341 +
   1.342 +    @staticmethod    
   1.343 +    def x11():
   1.344 +        return Cygwin.cygwin_x11
   1.345 +    
   1.346 +    @staticmethod
   1.347 +    def vboxman():
   1.348 +        return Cygwin.vbox_man
   1.349 +    
   1.350 +    @staticmethod
   1.351 +    def cmd():
   1.352 +        return Cygwin.win_cmd
   1.353 +    
   1.354 +    executeLock = threading.Lock()
   1.355 +    #executes command on host system
   1.356 +    @staticmethod
   1.357 +    def execute(program, arguments, wait_return=True, window = False):
   1.358 +        _startupinfo = STARTUPINFO()
   1.359 +        if not window:
   1.360 +            _startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
   1.361 +            _startupinfo.wShowWindow = _subprocess.SW_HIDE
   1.362 +
   1.363 +            #logger.debug('trying to launch: ' + program + ' ' + ''.join(arguments))
   1.364 +        res_stderr = None
   1.365 +        try:
   1.366 +            process = Popen(executable=program, args=' ' + arguments, startupinfo = _startupinfo, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell = False)
   1.367 +            logger.debug('Launched: ' + program + ' ' + ''.join(arguments))
   1.368 +            if not wait_return:
   1.369 +                return [0, 'working in background', '']
   1.370 +            result = process.wait()
   1.371 +            res_stdout = process.stdout.read();
   1.372 +            res_stderr = process.stderr.read();
   1.373 +
   1.374 +        except Exception as ex:
   1.375 +            res_stderr = ''.join(ex.args)
   1.376 +            result = -1 
   1.377 +        
   1.378 +        if result != 0:
   1.379 +            logger.error('Failed to execute cygwin command.\n\tcommand=' + program + ' ' + ''.join(arguments) + '\n' + res_stderr)
   1.380 +            raise OpenSecurityException('Failed to execute cygwin command.\n\tcommand=' + program + ' ' + ''.join(arguments) + '\n' + res_stderr)
   1.381 +            
   1.382 +        return result, res_stdout, res_stderr
   1.383 +    
   1.384 +    @staticmethod
   1.385 +    def vboxExecute(command, wait_return=True, window = False, bash_opts=''):
   1.386 +        if Cygwin.executeLock.acquire(True):
   1.387 +            retry = 0
   1.388 +            while retry < 3:
   1.389 +                try:
   1.390 +                    result = Cygwin.execute(Cygwin.vbox_man, command, wait_return, window)
   1.391 +                    Cygwin.executeLock.release()
   1.392 +                    return result
   1.393 +                except OpenSecurityException as inst:
   1.394 +                    retry+=1
   1.395 +            Cygwin.executeLock.release()
   1.396 +            raise inst
   1.397 +        return result
   1.398 +        
   1.399 +    
   1.400 +    @staticmethod
   1.401 +    def bashExecute(command, wait_return=True, window = False, bash_opts=''):
   1.402 +        command = bash_opts + ' -l -c '  + command
   1.403 +        return Cygwin.execute(Cygwin.cygwin_bash, command, wait_return, window)
   1.404 +    
   1.405 +    @staticmethod
   1.406 +    def cmdExecute(command, wait_return=True, window = False, bash_opts=''):
   1.407 +        command = ' /c ' + command 
   1.408 +        return Cygwin.execute(Cygwin.win_cmd, command, wait_return, window)
   1.409 +
   1.410 +    # executes command over ssh on guest vm
   1.411 +    @staticmethod
   1.412 +    def sshExecute(command, address, user_name, certificate, wait_return=True, window = False):
   1.413 +        command = ' -v -i "' + certificate + '" ' + user_name + '@' + address + ' ' + command        
   1.414 +        return Cygwin.execute(Cygwin.cygwin_ssh, command, wait_return, window)     
   1.415 +    
   1.416 +    #machineFolder + '/' + vm_name + '/dvm_key
   1.417 +    #address = self.getHostOnlyIP(vm_name)
   1.418 +    #machineFolder = self.getDefaultMachineFolder()
   1.419 +    #machineFolder = Cygwin.cygwinPath(machineFolder)
   1.420 +    
   1.421 +    # executes command over ssh on guest vm with X forwarding
   1.422 +    @staticmethod
   1.423 +    def sshExecuteX11(command, address, user_name, certificate, wait_return=True):
   1.424 +        return Cygwin.bashExecute('"DISPLAY=:0.0 /usr/bin/ssh -v -Y -i \\"' + certificate +'\\" ' + user_name + '@' + address + ' ' + command + '\"')
   1.425 +
   1.426 +    @staticmethod
   1.427 +    def is_X11_running():
   1.428 +        """check if we can connect to a X11 running instance"""
   1.429 +        p = Cygwin.bashExecute('"DISPLAY=:0 /usr/bin/xset -q"')
   1.430 +        return p[0] == 0
   1.431 +        
   1.432 +        
   1.433 +    @staticmethod
   1.434 +    def start_X11():
   1.435 +        """start X11 in the background (if not already running) on DISPLAY=:0"""
   1.436 +        # do not start if already running
   1.437 +        if Cygwin.is_X11_running():
   1.438 +            return           
   1.439 +        # launch X11 (forget output and return immediately)
   1.440 +        return Cygwin.execute(Cygwin.cygwin_x11, ':0 -multiwindow', wait_return = False, window = False)
   1.441 +    
   1.442 +    @staticmethod    
   1.443 +    def cygPath(path):
   1.444 +        cmd = '"/usr/bin/cygpath -u \\"' + path + '\\""'
   1.445 +        return Cygwin.bashExecute(cmd)[1].rstrip('\n')
   1.446 +    
   1.447 +# start
   1.448 +if __name__ == "__main__":
   1.449 +    logger = setupLogger('Cygwin')
   1.450 +    c = Cygwin()
   1.451 +    logger.info(c.root())
   1.452 +    logger.info(c.bin())
   1.453 +    logger.info(c.bash())
   1.454 +    logger.info(c.ssh())
   1.455 +    
   1.456 +    c.cygPath('C:')
   1.457 +    c.start_X11()
   1.458 +
   1.459 +        
   1.460 +    
   1.461 +