* Extracting script to "template" files for transports

* Fixes to UDS Client
This commit is contained in:
Adolfo Gómez García 2015-04-07 07:59:47 +02:00
parent 2f655dce16
commit f8b95382b0
9 changed files with 203 additions and 153 deletions

View File

@ -53,6 +53,7 @@ class UDSClient(QtGui.QMainWindow):
ticket = None
scrambler = None
withError = False
def __init__(self):
QtGui.QMainWindow.__init__(self)
@ -83,6 +84,7 @@ class UDSClient(QtGui.QMainWindow):
self.ui.info.setText('Error')
QtGui.QMessageBox.critical(self, 'Error', six.text_type(e), QtGui.QMessageBox.Ok)
self.closeWindow()
self.withError = True
def cancelPushed(self):
self.close()
@ -119,7 +121,7 @@ class UDSClient(QtGui.QMainWindow):
self.ui.progressBar.setValue(20)
self.processError(data)
script = data['result']
script = data['result'].decode('base64').decode('bz2')
print script
six.exec_(script, globals(), {'parent': self})
@ -178,24 +180,28 @@ if __name__ == "__main__":
exitVal = app.exec_()
win.showMinimized() # This is a top most window, minimize to bar because it is not closed in fact until app exit
tools.waitForTasks()
sys.exit(exitVal)
except Exception as e:
QtGui.QMessageBox.critical(None, 'Error', six.text_type(e), QtGui.QMessageBox.Ok)
time.sleep(3)
try:
tools.unlinkFiles()
except Exception:
pass
if win.withError is False:
win.showMinimized() # This is a top most window, minimize to bar because it is not closed in fact until app exit
try:
tools.waitForTasks()
except Exception:
pass
try:
tools.execBeforeExit()
except Exception:
pass
time.sleep(3)
try:
tools.unlinkFiles()
except Exception:
pass
try:
tools.execBeforeExit()
except Exception:
pass
sys.exit(exitVal)
# Build base REST

View File

@ -125,7 +125,7 @@ class Client(Handler):
logger.debug('Script:\n{}'.format(transportScript))
return Client.result(transportScript)
return Client.result(transportScript.encode('bz2').encode('base64'))
except Exception as e:
logger.exception("Exception")
return Client.result(error=six.text_type(e))

View File

@ -37,9 +37,9 @@ from uds.core.ui.UserInterface import gui
from uds.core.transports.BaseTransport import Transport
from uds.core.transports import protocols
from uds.core.util import connection
from .web import generateHtmlForRdp, getHtmlComponent
import logging
import os
logger = logging.getLogger(__name__)
@ -121,7 +121,7 @@ class BaseRDPTransport(Transport):
def getConnectionInfo(self, service, user, password):
return self.processUserPassword(service, user, password)
def getHtmlComponent(self, _id, _os, componentId):
logger.debug('Component: ID={}'.format(_id))
# We use helper to keep this clean
return getHtmlComponent(self.__module__, componentId)
def getScript(self, script):
with open(os.path.join(os.path.dirname(__file__), script)) as f:
data = f.read()
return data

View File

@ -38,6 +38,7 @@ from .BaseRDPTransport import BaseRDPTransport
from .RDPFile import RDPFile
import logging
import os
logger = logging.getLogger(__name__)
@ -79,27 +80,7 @@ class RDPTransport(BaseRDPTransport):
r.multimon = self.multimon.isTrue()
# The password must be encoded, to be included in a .rdp file, as 'UTF-16LE' before protecting (CtrpyProtectData) it in order to work with mstsc
return '''
from __future__ import unicode_literals
from PyQt4 import QtCore, QtGui
import win32crypt
import os
import subprocess
from uds import tools
import six
file = \'\'\'{file}\'\'\'.format(password=win32crypt.CryptProtectData(six.binary_type('{password}'.encode('UTF-16LE')), None, None, None, None, 0x01).encode('hex'))
filename = tools.saveTempFile(file)
executable = os.path.join(os.path.join(os.environ['WINDIR'], 'system32'), 'mstsc.exe')
subprocess.call([executable, filename])
#tools.addFileToUnlink(filename)
# QtGui.QMessageBox.critical(parent, 'Notice', filename + ", " + executable, QtGui.QMessageBox.Ok)
'''.format(os=data['os'], file=r.get(), password=data['password'])
return self.getScript('scripts/windows/direct.py').format(os=data['os'], file=r.get(), password=data['password'])
def macOsXScript(self, data):
r = RDPFile(data['fullScreen'], data['width'], data['height'], data['depth'], target=OsDetector.Macintosh)
@ -118,86 +99,14 @@ subprocess.call([executable, filename])
else:
username = data['username']
return '''
from __future__ import unicode_literals
from PyQt4 import QtCore, QtGui
import subprocess
import os
from uds import tools
import six
file = \'\'\'{file}\'\'\'
# First, try to locate Remote Desktop Connection (version 2, from Microsoft website, not the app store one)
filename = tools.saveTempFile(file)
msrdc = '/Applications/Remote Desktop Connection.app/Contents/MacOS/Remote Desktop Connection'
cord = "/Applications/CoRD.app/Contents/MacOS/CoRD"
if os.path.isfile(msrdc):
executable = msrdc
elif os.path.isfile(cord):
executable = cord
else:
executable = None
def onExit():
import subprocess
subprocess.call(['security',
'delete-generic-password',
'-a', '{username}',
'-s', 'Remote Desktop Connection 2 Password for {ip}',
])
if executable is None:
QtGui.QMessageBox.critical(parent, 'Notice', \'\'\'
<p><b>Microsoft Remote Desktop Connection not found</b></p>
<p>In order to connect to UDS RDP Sessions, you need to have at least one of the following:<p>
<ul>
<li>
<p><b>Microsoft Remote Desktop Connection version 2.</b> (Recommended)</p>
<p>You can get it from <a href="http://www.microsoft.com/es-es/download/details.aspx?id=18140">this link</a></p>
<p>Remember that you need to use the One from the Microsoft site (the link provided), not the one from the AppStore</p>
</li>
<li>
<p><b>CoRD</b> (A bit unstable from 10.7 onwards)</p>
<p>You can get it from <a href="{this_server}static/other/CoRD.pkg">this link</a></p>
</li>
</ul>
<p>If both apps are installed, Remote Desktop Connection will be used as first option</p>
\'\'\', QtGui.QMessageBox.Ok)
elif executable == msrdc:
try:
subprocess.call(['security',
'add-generic-password',
'-w', '{password}',
'-U',
'-a', '{username}',
'-s', 'Remote Desktop Connection 2 Password for {ip}',
'-T', '/Applications/Remote Desktop Connection.app',
])
# Call but do not wait for exit
tools.addTaskToWait(subprocess.Popen([executable, filename]))
tools.addExecBeforeExit(onExit)
tools.addFileToUnlink(filename)
except Exception as e:
QtGui.QMessageBox.critical(parent, 'Notice', six.text_type(e), QtGui.QMessageBox.Ok)
else: # CoRD
pass
'''.format(os=data['os'],
file=r.get(),
password=data['password'],
username=username,
ip=data['ip'],
this_server=data['this_server']
)
return self.getScript('scripts/macosx/direct.py').format(os=data['os'],
file=r.get(),
password=data['password'],
username=username,
ip=data['ip'],
this_server=data['this_server'],
r=r
)
def getUDSTransportScript(self, userService, transport, ip, os, user, password, request):
# We use helper to keep this clean

View File

@ -98,35 +98,7 @@ class TSRDPTransport(BaseRDPTransport):
r.multimon = self.multimon.isTrue()
# The password must be encoded, to be included in a .rdp file, as 'UTF-16LE' before protecting (CtrpyProtectData) it in order to work with mstsc
return '''
from __future__ import unicode_literals
from PyQt4 import QtCore, QtGui
import win32crypt
import os
import subprocess
from uds.forward import forward
from uds import tools
import six
forwardThread, port = forward('{tunHost}', {tunPort}, '{tunUser}', '{tunPass}', '{server}', {port})
file = \'\'\'{file}\'\'\'.format(
password=win32crypt.CryptProtectData(six.binary_type('{password}'.encode('UTF-16LE')), None, None, None, None, 0x01).encode('hex'),
address='127.0.0.1:{{}}'.format(port)
)
filename = tools.saveTempFile(file)
executable = os.path.join(os.path.join(os.environ['WINDIR'], 'system32'), 'mstsc.exe')
subprocess.call([executable, filename])
tools.addFileToUnlink(filename)
# QtGui.QMessageBox.critical(parent, 'Notice', filename + ", " + executable, QtGui.QMessageBox.Ok)
'''.format(
return self.getScript('scripts/windows/tunnel.py').format(
file=r.get(), password=data['password'],
server=data['ip'],
port=3389,

View File

@ -1,3 +0,0 @@
/rdp.jar
/rdppass.dll
/launcher.jar

View File

@ -0,0 +1,113 @@
# This is a template
# Saved as .py for easier editing
from __future__ import unicode_literals
# pylint: disable=import-error, no-name-in-module, too-many-format-args, undefined-variable, invalid-sequence-index
from PyQt4 import QtCore, QtGui
import subprocess
import os
import urllib
from uds import tools # @UnresolvedImport
import six
theFile = '''{file}'''
# First, try to locate Remote Desktop Connection (version 2, from Microsoft website, not the app store one)
filename = tools.saveTempFile(theFile)
msrdc = '/Applications/Remote Desktop Connection.app/Contents/MacOS/Remote Desktop Connection'
cord = "/Applications/CoRD.app/Contents/MacOS/CoRD"
if os.path.isfile(msrdc):
executable = msrdc
elif os.path.isfile(cord):
executable = cord
else:
executable = None
def onExit():
import subprocess # @Reimport
subprocess.call(
[
'security',
'delete-generic-password',
'-a', '{username}',
'-s', 'Remote Desktop Connection 2 Password for {ip}',
]
)
if executable is None:
QtGui.QMessageBox.critical(parent, 'Notice', # @UndefinedVariable
'''<p><b>Microsoft Remote Desktop Connection not found</b></p>
<p>In order to connect to UDS RDP Sessions, you need to have at least one of the following:<p>
<ul>
<li>
<p><b>Microsoft Remote Desktop Connection version 2.</b> (Recommended)</p>
<p>You can get it from <a href="http://www.microsoft.com/es-es/download/details.aspx?id=18140">this link</a></p>
<p>Remember that you need to use the One from the Microsoft site (the link provided), not the one from the AppStore</p>
</li>
<li>
<p><b>CoRD</b> (A bit unstable from 10.7 onwards)</p>
<p>You can get it from <a href="{this_server}static/other/CoRD.pkg">this link</a></p>
</li>
</ul>
<p>If both apps are installed, Remote Desktop Connection will be used as first option</p>
''', QtGui.QMessageBox.Ok)
elif executable == msrdc:
try:
if '{username}' != '' and '{password}' != '':
subprocess.call(
[
'security',
'add-generic-password',
'-w', '{password}',
'-U',
'-a', '{username}',
'-s', 'Remote Desktop Connection 2 Password for {ip}',
'-T', '/Applications/Remote Desktop Connection.app',
]
)
# Call but do not wait for exit
tools.addTaskToWait(subprocess.Popen([executable, filename]))
tools.addExecBeforeExit(onExit)
tools.addFileToUnlink(filename)
except Exception as e:
QtGui.QMessageBox.critical(parent, 'Notice', six.text_type(e), QtGui.QMessageBox.Ok) # @UndefinedVariable
else: # CoRD
url = 'rdp://'
if '\\' in '{username}':
username, domain = '{username}'.split('\\')
else:
username, domain = '{username}', ''
if username != '':
url += username
if '{password}' != '':
url += ':' + urllib.quote('{password}')
url += '@'
url += '{ip}/'
if domain != '':
url += domain
url += '?screenDepth={r.bpp}'
if {r.fullScreen}: # @UndefinedVariable
url += '&fullscreen=true'
else:
url += 'screenWidth={r.width}&screenHeight={r.height}'
url += '&forwardAudio=' + '01'[{r.redirectAudio}] # @UndefinedVariable
if {r.redirectDrives}: # @UndefinedVariable
url += '&forwardDisks=true'
if {r.redirectPrinters}: # @UndefinedVariable
url += '&forwardPrinters=true'
tools.addTaskToWait(subprocess.Popen(['open', url]))

View File

@ -0,0 +1,22 @@
# This is a template
# Saved as .py for easier editing
from __future__ import unicode_literals
# pylint: disable=import-error, no-name-in-module
from PyQt4 import QtCore, QtGui
import win32crypt # @UnresolvedImport
import os
import subprocess
from uds import tools # @UnresolvedImport
import six
theFile = '''{file}'''.format(password=win32crypt.CryptProtectData(six.binary_type('{password}'.encode('UTF-16LE')), None, None, None, None, 0x01).encode('hex'))
filename = tools.saveTempFile(theFile)
executable = os.path.join(os.path.join(os.environ['WINDIR'], 'system32'), 'mstsc.exe')
subprocess.call([executable, filename])
# tools.addFileToUnlink(filename)
# QtGui.QMessageBox.critical(parent, 'Notice', filename + ", " + executable, QtGui.QMessageBox.Ok)

View File

@ -0,0 +1,31 @@
# This is a template
# Saved as .py for easier editing
from __future__ import unicode_literals
# pylint: disable=import-error, no-name-in-module, too-many-format-args
from PyQt4 import QtCore, QtGui
import win32crypt # @UnresolvedImport
import os
import subprocess
from uds.forward import forward # @UnresolvedImport
from uds import tools # @UnresolvedImport
import six
forwardThread, port = forward('{tunHost}', '{tunPort}', '{tunUser}', '{tunPass}', '{server}', '{port}')
theFile = '''{file}'''.format(
password=win32crypt.CryptProtectData(six.binary_type('{password}'.encode('UTF-16LE')), None, None, None, None, 0x01).encode('hex'),
address='127.0.0.1:{{}}'.format(port)
)
filename = tools.saveTempFile(theFile)
executable = os.path.join(os.path.join(os.environ['WINDIR'], 'system32'), 'mstsc.exe')
subprocess.call([executable, filename])
tools.addFileToUnlink(filename)
# QtGui.QMessageBox.critical(parent, 'Notice', filename + ", " + executable, QtGui.QMessageBox.Ok)