OpenSecurity/bin/cygwin.py
author Oliver Maurhart <oliver.maurhart@ait.ac.at>
Mon, 10 Mar 2014 13:01:08 +0100
changeset 91 a26757850ea9
parent 90 bfd41c38d156
child 96 630b62946c9e
permissions -rwxr-xr-x
download and initial import from within service working
oliver@91
     1
#!/bin/env python
oliver@91
     2
# -*- coding: utf-8 -*-
oliver@91
     3
oliver@91
     4
# ------------------------------------------------------------
oliver@91
     5
# cygwin command
oliver@91
     6
# 
oliver@91
     7
# executes a cygwin command inside the opensecurity project
oliver@91
     8
#
oliver@91
     9
# Autor: Mihai Bartha, <mihai.bartha@ait.ac.at>
oliver@91
    10
#        Oliver Maurhart, <oliver.maurhart@ait.ac.at>
oliver@91
    11
#
oliver@91
    12
# Copyright (C) 2013 AIT Austrian Institute of Technology
oliver@91
    13
# AIT Austrian Institute of Technology GmbH
oliver@91
    14
# Donau-City-Strasse 1 | 1220 Vienna | Austria
oliver@91
    15
# http://www.ait.ac.at
oliver@91
    16
#
oliver@91
    17
# This program is free software; you can redistribute it and/or
oliver@91
    18
# modify it under the terms of the GNU General Public License
oliver@91
    19
# as published by the Free Software Foundation version 2.
oliver@91
    20
# 
oliver@91
    21
# This program is distributed in the hope that it will be useful,
oliver@91
    22
# but WITHOUT ANY WARRANTY; without even the implied warranty of
oliver@91
    23
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
oliver@91
    24
# GNU General Public License for more details.
oliver@91
    25
# 
oliver@91
    26
# You should have received a copy of the GNU General Public License
oliver@91
    27
# along with this program; if not, write to the Free Software
oliver@91
    28
# Foundation, Inc., 51 Franklin Street, Fifth Floor, 
oliver@91
    29
# Boston, MA  02110-1301, USA.
oliver@91
    30
# ------------------------------------------------------------
oliver@91
    31
oliver@91
    32
oliver@91
    33
# ------------------------------------------------------------
oliver@91
    34
# imports
oliver@91
    35
oliver@91
    36
import os
oliver@91
    37
import subprocess
oliver@91
    38
import sys
oliver@91
    39
import _winreg
oliver@91
    40
from subprocess import Popen, PIPE, call, STARTUPINFO, _subprocess
oliver@91
    41
import threading
oliver@91
    42
# local
oliver@91
    43
from environment import Environment
oliver@91
    44
from opensecurity_util import logger, setupLogger, OpenSecurityException
oliver@91
    45
oliver@91
    46
# ------------------------------------------------------------
oliver@91
    47
# code
oliver@91
    48
oliver@91
    49
def once(theClass):
oliver@91
    50
    """get the path to our local cygwin installment"""
oliver@91
    51
    home_drive = os.path.expandvars("%HOMEDRIVE%") + os.sep
oliver@91
    52
    path_hint = [ 
oliver@91
    53
        os.path.abspath(os.path.join(Environment('OpenSecurity').prefix_path, 'cygwin')), 
oliver@91
    54
        os.path.abspath(os.path.join(Environment('OpenSecurity').prefix_path, 'cygwin64')), 
oliver@91
    55
        os.path.abspath(os.path.join(home_drive, 'cygwin')),
oliver@91
    56
        os.path.abspath(os.path.join(home_drive, 'cygwin64'))
oliver@91
    57
    ]
oliver@91
    58
    path_valid = [ p for p in path_hint if os.path.exists(p) ]
oliver@91
    59
        
oliver@91
    60
    theClass.cygwin_root = path_valid[0]
oliver@91
    61
    theClass.cygwin_bin = os.path.join(theClass.cygwin_root, 'bin') + os.path.sep
oliver@91
    62
    theClass.cygwin_bash = os.path.join(theClass.cygwin_bin, 'bash.exe')
oliver@91
    63
    theClass.cygwin_ssh = os.path.join(theClass.cygwin_bin, 'ssh.exe')
oliver@91
    64
    theClass.cygwin_x11 = os.path.join(theClass.cygwin_bin, 'XWin.exe')
oliver@91
    65
    theClass.win_cmd = os.environ.get("COMSPEC", "cmd.exe") 
oliver@91
    66
    """get the path to the VirtualBox installation on this system"""
oliver@91
    67
    theClass.vbox_root = theClass.getRegEntry('SOFTWARE\Oracle\VirtualBox', 'InstallDir')[0]  
oliver@91
    68
    theClass.vbox_man = os.path.join(theClass.vbox_root, 'VBoxManage.exe')
oliver@91
    69
    
oliver@91
    70
    return theClass
oliver@91
    71
oliver@91
    72
@once
oliver@91
    73
class Cygwin(object):
oliver@91
    74
    cygwin_root = ''
oliver@91
    75
    cygwin_bin = ''
oliver@91
    76
    cygwin_bash = ''
oliver@91
    77
    cygwin_ssh = ''
oliver@91
    78
    cygwin_x11 = ''
oliver@91
    79
    vbox_root = ''
oliver@91
    80
    vbox_man = ''
oliver@91
    81
    win_cmd = ''
oliver@91
    82
    """Some nifty methods working with Cygwin"""
oliver@91
    83
    
oliver@91
    84
    def __call__(self, command, arguments, wait_return=True, window = False):
oliver@91
    85
        """make an instance of this object act as a function"""
oliver@91
    86
        return self.execute(command, arguments, wait_return, window)
oliver@91
    87
oliver@91
    88
    @staticmethod
oliver@91
    89
    def getRegEntry(key, value):
oliver@91
    90
        try:
oliver@91
    91
            k = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, key)
oliver@91
    92
            value = _winreg.QueryValueEx(k, value)
oliver@91
    93
            _winreg.CloseKey(k)
oliver@91
    94
            return value
oliver@91
    95
        except:
oliver@91
    96
            pass
oliver@91
    97
    
oliver@91
    98
            
oliver@91
    99
    @staticmethod
oliver@91
   100
    def root():
oliver@91
   101
        return Cygwin.cygwin_root
oliver@91
   102
oliver@91
   103
    @staticmethod
oliver@91
   104
    def bin():
oliver@91
   105
        return Cygwin.cygwin_bin
oliver@91
   106
    
oliver@91
   107
    @staticmethod
oliver@91
   108
    def bash():
oliver@91
   109
        return Cygwin.cygwin_bash
oliver@91
   110
    
oliver@91
   111
    @staticmethod    
oliver@91
   112
    def ssh():
oliver@91
   113
        return Cygwin.cygwin_ssh
oliver@91
   114
oliver@91
   115
    @staticmethod    
oliver@91
   116
    def x11():
oliver@91
   117
        return Cygwin.cygwin_x11
oliver@91
   118
    
oliver@91
   119
    @staticmethod
oliver@91
   120
    def vboxman():
oliver@91
   121
        return Cygwin.vbox_man
oliver@91
   122
    
oliver@91
   123
    @staticmethod
oliver@91
   124
    def cmd():
oliver@91
   125
        return Cygwin.win_cmd
oliver@91
   126
    
oliver@91
   127
    executeLock = threading.Lock()
oliver@91
   128
    #executes command on host system
oliver@91
   129
    @staticmethod
oliver@91
   130
    def execute(program, arguments, wait_return=True, window = False, stdin = PIPE, stdout = PIPE, stderr = PIPE):
oliver@91
   131
        _startupinfo = STARTUPINFO()
oliver@91
   132
        if not window:
oliver@91
   133
            _startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
oliver@91
   134
            _startupinfo.wShowWindow = _subprocess.SW_HIDE
oliver@91
   135
oliver@91
   136
            #logger.debug('trying to launch: ' + program + ' ' + ''.join(arguments))
oliver@91
   137
        res_stderr = None
oliver@91
   138
        try:
oliver@91
   139
            # quote the executable otherwise we run into troubles
oliver@91
   140
            # when the path contains spaces and additonal arguments
oliver@91
   141
            # are presented as well.
oliver@91
   142
            # special: invoking bash as login shell here with
oliver@91
   143
            # an unquoted command does not execute /etc/profile
oliver@91
   144
            args = '"' + program + '" ' + arguments
oliver@91
   145
            process = Popen(args, startupinfo = _startupinfo, stdin = stdin, stdout = stdout, stderr = stderr, shell = False)
oliver@91
   146
            logger.debug('Launched: ' + program + ' ' + ''.join(arguments))
oliver@91
   147
            if not wait_return:
oliver@91
   148
                return [0, 'working in background', '']
oliver@91
   149
            result = process.wait()
oliver@91
   150
            res_stdout = process.stdout.read();
oliver@91
   151
            res_stderr = process.stderr.read();
oliver@91
   152
oliver@91
   153
        except Exception as ex:
oliver@91
   154
            res_stderr = ''.join(str(ex.args))
oliver@91
   155
            result = 1 
oliver@91
   156
            
oliver@91
   157
        return result, res_stdout, res_stderr
oliver@91
   158
    
oliver@91
   159
    @staticmethod
oliver@91
   160
    def vboxExecute(command, wait_return=True, window = False, bash_opts=''):
oliver@91
   161
        retry = 0
oliver@91
   162
        result = None
oliver@91
   163
        while retry < 3:
oliver@91
   164
            if Cygwin.executeLock.acquire(True):
oliver@91
   165
                result = Cygwin.execute(Cygwin.vbox_man, command, wait_return, window)
oliver@91
   166
                Cygwin.executeLock.release()
oliver@91
   167
                if result[0] == 0:
oliver@91
   168
                    return result
oliver@91
   169
                retry+=1
oliver@91
   170
        return result
oliver@91
   171
oliver@91
   172
oliver@91
   173
    @staticmethod
oliver@91
   174
    def bashExecute(command, wait_return=True, window = False, bash_opts='', stdin = PIPE, stdout = PIPE, stderr = PIPE):
oliver@91
   175
        # for some reason, the '-l' is ignored when started via python
oliver@91
   176
        # so the same behavior is triggered by calling /etc/profile 
oliver@91
   177
        # directly
oliver@91
   178
        command = bash_opts + ' -l -c "'  + command + '"'
oliver@91
   179
        return Cygwin.execute(Cygwin.cygwin_bash, command, wait_return, window, stdin = stdin, stdout = stdout, stderr = stderr)
oliver@91
   180
    
oliver@91
   181
    @staticmethod
oliver@91
   182
    def cmdExecute(command, wait_return=True, window = False, bash_opts=''):
oliver@91
   183
        command = ' /c ' + command 
oliver@91
   184
        return Cygwin.execute(Cygwin.win_cmd, command, wait_return, window)
oliver@91
   185
oliver@91
   186
    # executes command over ssh on guest vm
oliver@91
   187
    @staticmethod
oliver@91
   188
    def sshExecute(command, address, user_name, certificate, wait_return=True, window = False):
oliver@91
   189
        command = ' -v -i "' + certificate + '" ' + user_name + '@' + address + ' ' + command        
oliver@91
   190
        return Cygwin.execute(Cygwin.cygwin_ssh, command, wait_return, window)     
oliver@91
   191
    
oliver@91
   192
    #machineFolder + '/' + vm_name + '/dvm_key
oliver@91
   193
    #address = self.getHostOnlyIP(vm_name)
oliver@91
   194
    #machineFolder = self.getDefaultMachineFolder()
oliver@91
   195
    #machineFolder = Cygwin.cygwinPath(machineFolder)
oliver@91
   196
    
oliver@91
   197
    # executes command over ssh on guest vm with X forwarding
oliver@91
   198
    @staticmethod
oliver@91
   199
    def sshExecuteX11(command, address, user_name, certificate, wait_return=True):
oliver@91
   200
        return Cygwin.bashExecute('"DISPLAY=:0.0 /usr/bin/ssh -v -Y -i \\"' + certificate +'\\" ' + user_name + '@' + address + ' ' + command + '\"')
oliver@91
   201
oliver@91
   202
    @staticmethod
oliver@91
   203
    def is_X11_running():
oliver@91
   204
        """check if we can connect to a X11 running instance"""
oliver@91
   205
        p = Cygwin.bashExecute('DISPLAY=:0 /usr/bin/xset -q')
oliver@91
   206
        return p[0] == 0
oliver@91
   207
        
oliver@91
   208
        
oliver@91
   209
    @staticmethod
oliver@91
   210
    def start_X11():
oliver@91
   211
        """start X11 in the background (if not already running) on DISPLAY=:0"""
oliver@91
   212
        # do not start if already running
oliver@91
   213
        if Cygwin.is_X11_running():
oliver@91
   214
            return           
oliver@91
   215
        # launch X11 (forget output and return immediately)
oliver@91
   216
        return Cygwin.execute(Cygwin.cygwin_x11, ':0 -multiwindow', wait_return = False, window = False)
oliver@91
   217
    
oliver@91
   218
    @staticmethod    
oliver@91
   219
    def cygPath(path):
oliver@91
   220
        cmd = 'cygpath -u \'' + path + '\''
oliver@91
   221
        return Cygwin.bashExecute(cmd)[1].rstrip('\n')
oliver@91
   222
    
oliver@91
   223
# start
oliver@91
   224
if __name__ == "__main__":
oliver@91
   225
    logger = setupLogger('Cygwin')
oliver@91
   226
    c = Cygwin()
oliver@91
   227
    logger.info(c.root())
oliver@91
   228
    logger.info(c.bin())
oliver@91
   229
    logger.info(c.bash())
oliver@91
   230
    logger.info(c.ssh())
oliver@91
   231
    
oliver@91
   232
    print(c.bashExecute('echo $PATH')[1])
oliver@91
   233
    print(c.cygPath('C:'))
oliver@91
   234
    print('C:\\Program Files\\OpenSecurity: ' + c.cygPath('C:\\Program Files\\OpenSecurity'))
oliver@91
   235
    c.start_X11()
oliver@91
   236