OpenSecurity/bin/launch.py
author om
Fri, 06 Dec 2013 12:10:30 +0100
changeset 14 c187aaceca32
parent 3 OpenSecurity/client/launch.py@65432e6c6042
child 16 e16d64b5e008
permissions -rwxr-xr-x
renamed "client" to "bin"
     1 #!/bin/env python
     2 # -*- coding: utf-8 -*-
     3 
     4 # ------------------------------------------------------------
     5 # opensecurity-launcher
     6 # 
     7 # launches an application inside a VM
     8 #
     9 # Autor: Oliver Maurhart, <oliver.maurhart@ait.ac.at>
    10 #
    11 # Copyright (C) 2013 AIT Austrian Institute of Technology
    12 # AIT Austrian Institute of Technology GmbH
    13 # Donau-City-Strasse 1 | 1220 Vienna | Austria
    14 # http://www.ait.ac.at
    15 #
    16 # This program is free software; you can redistribute it and/or
    17 # modify it under the terms of the GNU General Public License
    18 # as published by the Free Software Foundation version 2.
    19 # 
    20 # This program is distributed in the hope that it will be useful,
    21 # but WITHOUT ANY WARRANTY; without even the implied warranty of
    22 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    23 # GNU General Public License for more details.
    24 # 
    25 # You should have received a copy of the GNU General Public License
    26 # along with this program; if not, write to the Free Software
    27 # Foundation, Inc., 51 Franklin Street, Fifth Floor, 
    28 # Boston, MA  02110-1301, USA.
    29 # ------------------------------------------------------------
    30 
    31 
    32 # ------------------------------------------------------------
    33 # imports
    34 
    35 import argparse
    36 import os
    37 import subprocess
    38 import sys
    39 
    40 from PyQt4 import QtCore
    41 from PyQt4 import QtGui
    42 
    43 # local
    44 from about import About
    45 from cygwin import Cygwin
    46 from environment import Environment
    47 import opensecurity_server
    48 
    49 
    50 # ------------------------------------------------------------
    51 # code
    52 
    53 
    54 class Chooser(QtGui.QDialog, object):
    55     
    56     """Ask the user what to launch."""
    57     
    58     def __init__(self, parent = None, flags = QtCore.Qt.WindowFlags(0)):
    59     
    60         super(Chooser, self).__init__(parent, flags)
    61         self.setWindowTitle('OpenSecuirty Launch Application')
    62         self.setup_ui()
    63         
    64         # known vms and applications
    65         self._apps, self_vms = [], []
    66         
    67         # positionate ourself central
    68         screen = QtGui.QDesktopWidget().screenGeometry()
    69         self.resize(self.geometry().width() * 1.25, self.geometry().height())
    70         size = self.geometry()
    71         self.move((screen.width() - size.width()) / 2, (screen.height() - size.height()) / 2)
    72         
    73         # refresh vm and command input
    74         self.refresh()
    75         
    76         
    77     def app_get(self):
    78         """The application of the user."""
    79         a = str(self._cbApplication.currentText())
    80         for app in self._apps:
    81             if a == app['name']:
    82                 return app['command']
    83         return a
    84         
    85     app = property(app_get)
    86         
    87 
    88     def clicked_about(self):
    89         """clicked the about button"""
    90         dlgAbout = About()
    91         dlgAbout.exec_()
    92 
    93 
    94     def clicked_cancel(self):
    95         """clicked the cancel button"""
    96         self.reject()
    97     
    98 
    99     def clicked_ok(self):
   100         """clicked the ok button"""
   101         self.accept()
   102     
   103     
   104     def refresh(self):
   105         """load the known vms and commands and adjust input fields"""
   106         
   107         self._apps = opensecurity_server.query_apps()
   108         self._vms = opensecurity_server.query_vms()
   109         
   110         # add the VMs we know
   111         self._cbApplication.clear()
   112         for app in self._apps:
   113             self._cbApplication.addItem(app['name'])
   114         
   115         # add the commands we know
   116         self._cbVM.clear()
   117         for vm in self._vms:
   118             self._cbVM.addItem(vm['name'])
   119         
   120         
   121     def setup_ui(self):
   122         """Create the widgets."""
   123         
   124         lyMain = QtGui.QVBoxLayout(self)
   125         lyMain.setContentsMargins(8, 8, 8, 8)
   126         
   127         # content area: left pixmap, right text
   128         lyContent = QtGui.QHBoxLayout()
   129         lyMain.addLayout(lyContent)
   130         
   131         # pixmap
   132         lbPix = QtGui.QLabel()
   133         lbPix.setPixmap(QtGui.QPixmapCache.find('opensecurity_icon_64'))
   134         lyContent.addWidget(lbPix, 0, QtCore.Qt.Alignment(QtCore.Qt.AlignTop + QtCore.Qt.AlignHCenter))
   135         lyContent.addSpacing(16)
   136         
   137         # launch ...
   138         lyLaunch = QtGui.QGridLayout()
   139         lyContent.addLayout(lyLaunch)
   140         lbTitle = QtGui.QLabel('Specify details for application to launch.')
   141         lyLaunch.addWidget(lbTitle, 0, 0, 1, 2)
   142         
   143         lbVM = QtGui.QLabel('&VM-ID:')
   144         lyLaunch.addWidget(lbVM, 1, 0)
   145         self._cbVM = QtGui.QComboBox()
   146         self._cbVM.setEditable(True)
   147         self._cbVM.setInsertPolicy(QtGui.QComboBox.InsertAlphabetically)
   148         lyLaunch.addWidget(self._cbVM, 1, 1)
   149         lbVM.setBuddy(self._cbVM)
   150         
   151         lbApplication = QtGui.QLabel('&Application:')
   152         lyLaunch.addWidget(lbApplication, 2, 0)
   153         self._cbApplication = QtGui.QComboBox()
   154         self._cbApplication.setEditable(True)
   155         self._cbApplication.setInsertPolicy(QtGui.QComboBox.InsertAlphabetically)
   156         lyLaunch.addWidget(self._cbApplication, 2, 1)
   157         lbApplication.setBuddy(self._cbApplication)
   158         
   159         lyLaunch.addWidget(QtGui.QWidget(), 3, 0, 1, 2)
   160         lyLaunch.setColumnStretch(1, 1)
   161         lyLaunch.setRowStretch(3, 1)
   162         
   163         lyMain.addStretch(1)
   164         
   165         # buttons
   166         lyButton = QtGui.QHBoxLayout()
   167         lyMain.addLayout(lyButton)
   168         
   169         lyButton.addStretch(1)
   170         btnOk = QtGui.QPushButton('&Ok', self)
   171         btnOk.setDefault(True)
   172         btnOk.setMinimumWidth(100)
   173         lyButton.addWidget(btnOk)
   174         btnCancel = QtGui.QPushButton('&Cancel', self)
   175         btnCancel.setMinimumWidth(100)
   176         lyButton.addWidget(btnCancel)
   177         btnAbout = QtGui.QPushButton('&About', self)
   178         btnAbout.setMinimumWidth(100)
   179         lyButton.addWidget(btnAbout)
   180         
   181         button_width = max(btnOk.width(), btnCancel.width(), btnAbout.width())
   182         btnOk.setMinimumWidth(button_width)
   183         btnCancel.setMinimumWidth(button_width)
   184         btnAbout.setMinimumWidth(button_width)
   185         
   186         # reduce to the max
   187         self.resize(lyMain.minimumSize())
   188         
   189         # connectors
   190         btnOk.clicked.connect(self.clicked_ok)
   191         btnCancel.clicked.connect(self.clicked_cancel)
   192         btnAbout.clicked.connect(self.clicked_about)
   193 
   194         
   195     def user_get(self):
   196         """The user of the vm of choice."""
   197         v = str(self._cbVM.currentText())
   198         for vm in self._vms:
   199             if v == vm['name']:
   200                 return vm['user']
   201         return v
   202         
   203     user = property(user_get)
   204     
   205     
   206     def vm_get(self):
   207         """The vm of choice."""
   208         v = str(self._cbVM.currentText())
   209         for vm in self._vms:
   210             if v == vm['name']:
   211                 return vm['ip']
   212         return v
   213         
   214     vm = property(vm_get)
   215         
   216         
   217 def ask_user():
   218     """ask the user for VM and app to start"""
   219     
   220     # launch Qt
   221     app = QtGui.QApplication(sys.argv)
   222     
   223     # prebuild the pixmap cache: fetch all jpg, png and jpeg images and load them
   224     image_path = os.path.join(Environment("OpenSecurity").data_path, '..', 'gfx')
   225     for file in os.listdir(image_path):
   226         if file.lower().rpartition('.')[2] in ('jpg', 'png', 'jpeg'):
   227             QtGui.QPixmapCache.insert(file.lower().rpartition('.')[0], QtGui.QPixmap(os.path.join(image_path, file)))
   228             
   229     # we should have now our application icon
   230     app.setWindowIcon(QtGui.QIcon(QtGui.QPixmapCache.find('opensecurity_icon_64')))
   231     
   232     # pop up the dialog
   233     dlg = Chooser()
   234     dlg.show()
   235     app.exec_()
   236     
   237     if dlg.result() == QtGui.QDialog.Accepted:
   238         return dlg.user, dlg.vm, dlg.app
   239 
   240     return '', '', ''
   241     
   242 
   243 def main():
   244     """entry point"""
   245     
   246     # parse command line
   247     parser = argparse.ArgumentParser(description = 'OpenSecurity Launcher: run application in VM')
   248     parser.add_argument('user', metavar='USER', help='USER on Virtual Machine', nargs='?', type=str, default='')
   249     parser.add_argument('ip', metavar='IP', help='IP of Virtual Machine', nargs='?', type=str, default='')
   250     parser.add_argument('command', metavar='COMMAND', help='Full path of command and arguments to start inside VM', nargs='?', type=str, default='')
   251     args = parser.parse_args()
   252     
   253     # we must have at least all or none set
   254     set_user = args.user != ''
   255     set_ip = args.ip != ''
   256     set_command = args.command != ''
   257     set_ALL = set_user and set_ip and set_command
   258     set_NONE = (not set_user) and (not set_ip) and (not set_command)
   259     if (not set_ALL) and (not set_NONE):
   260         sys.stderr.write("Please specify user, ip and command or none.\n")
   261         sys.stderr.write("Type '--help' for help.\n")
   262         sys.exit(1)
   263         
   264     # check if we need to ask the user
   265     if set_NONE:
   266         args.user, args.ip, args.command = ask_user()
   267         
   268     # still no IP? --> no chance, over and out!
   269     if args.ip == '':
   270         sys.exit(0)
   271         
   272     # ensure we have our X11 running
   273     Cygwin.start_X11()
   274     
   275     # the SSH command
   276     user_at_guest = args.user + '@' + args.ip
   277     ssh = 'DISPLAY=:0 /usr/bin/ssh -Y ' + user_at_guest + ' ' + args.command
   278     print(ssh)
   279     
   280     # off we go!
   281     Cygwin()(['/bin/bash', '--login', '-i', '-c', ssh], None, None, None)
   282 
   283     
   284 # start
   285 if __name__ == "__main__":
   286     main()
   287