Commit cbf7078e by Csók Tamás

fix style to better match pep8, solved some compatibility issues

parent 65959e4c
#!/usr/bin/python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
## """
# A cloudban létrehozott virtuális gépekhez történő kapcsolódást segítő program A cloudban létrehozott virtuális gépekhez történő kapcsolódást segítő
## program
"""
import platform, argparse, sys, time import platform
import argparse
import sys
import time
try:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
except ImporError:
pass
##
# Paraméterek átadására használt struktúra
# state A virtuális gép állapota, azt figyeljük, hogy fut-e
# protocol SSH, NX és RDP lehetséges
# host A virtuális gép címe
# port Ezen a porton csatlakozunk a virtuális géphez
# user Csatlakozáshoz használt név
# password Csatlakozáshoz használt jelszó
class Struct: class Struct:
"""
Paraméterek átadására használt struktúra
Keyword arguments:
state -- A virtuális gép állapota, azt figyeljük, hogy fut-e
protocol -- SSH, NX és RDP lehetséges
host -- A virtuális gép címe
port -- Ezen a porton csatlakozunk a virtuális géphez
user -- Csatlakozáshoz használt név
password -- Csatlakozáshoz használt jelszó
"""
pass pass
##
# Argument parser, argparse modulon alapszik
# @return args
#
def pars_arguments(): def parse_arguments():
parser = argparse.ArgumentParser(); """
parser.add_argument("uri", type=str, help="Specific schema handler", nargs='?', default=None) Argument parser, argparse modulon alapszik
Keyword arguments:
@return args -- arguments given by console
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"uri", type=str, help="Specific schema handler", nargs='?',
default=None)
parser.add_argument("-u", "--username", type=str) parser.add_argument("-u", "--username", type=str)
parser.add_argument("-p", "--password", type=str) parser.add_argument("-p", "--password", type=str)
parser.add_argument("-d", "--driver", help="Select webdriver. Aside from Firefox, you have to install first the proper driver.", \ parser.add_argument(
type=str, choices=['firefox', 'chrome', 'ie', 'opera'], default="firefox") "-d", "--driver",
parser.add_argument("-o", "--old", help="Use old interface", action="store_true") help="Select webdriver. Aside from Firefox, you have to install "+
args = parser.parse_args(); "first the proper driver.", type=str,
choices=['firefox', 'chrome', 'ie', 'opera'],
default="firefox")
parser.add_argument(
"-o", "--old", help="Use old interface", action="store_true")
args = parser.parse_args()
return args return args
class Browser: class Browser:
## """
# Browser inicializálás Browser inicializálás
# @param args Az args.driver paraméterrel meghatározhatjuk, melyik böngészőt akarjuk használni.
# Keyword arguments:
@param args -- Az args.driver paraméterrel meghatározhatjuk,
melyik böngészőt akarjuk használni.
"""
def __init__(self, args): def __init__(self, args):
self.args = args self.args = args
if args.driver == "firefox": if args.driver == "firefox":
...@@ -52,10 +78,11 @@ class Browser: ...@@ -52,10 +78,11 @@ class Browser:
self.driver = webdriver.Opera() self.driver = webdriver.Opera()
self.driver.implicitly_wait(10) self.driver.implicitly_wait(10)
##
# Címtáras beléptetés a parancssorban megadott paraméterek alapján
#
def login(self): def login(self):
"""
Címtáras beléptetés a parancssorban megadott paraméterek
alapján
"""
driver = self.driver driver = self.driver
args = self.args args = self.args
if args.username is not None: if args.username is not None:
...@@ -65,13 +92,17 @@ class Browser: ...@@ -65,13 +92,17 @@ class Browser:
driver.find_element_by_name("j_password").clear() driver.find_element_by_name("j_password").clear()
driver.find_element_by_name("j_password").send_keys(args.password) driver.find_element_by_name("j_password").send_keys(args.password)
if args.username is not None and args.password is not None: if args.username is not None and args.password is not None:
driver.find_element_by_css_selector("input[type='submit']").click() driver.find_element_by_css_selector(
"input[type='submit']").click()
##
# A régi webes felület használata
# @return vm Virtuális gép csatlakozásához szükséges paraméterek
#
def old_main(self): def old_main(self):
"""
A régi webes felület használata
Keyword arguments:
@return vm -- Virtuális gép csatlakozásához szükséges
paraméterek
"""
vm = Struct() vm = Struct()
driver = self.driver driver = self.driver
driver.maximize_window() driver.maximize_window()
...@@ -81,23 +112,36 @@ class Browser: ...@@ -81,23 +112,36 @@ class Browser:
vm.state, vm.protocol = "", "NONE" vm.state, vm.protocol = "", "NONE"
try: try:
while vm.state.upper()[:3] not in ("FUT", "RUN"): while vm.state.upper()[:3] not in ("FUT", "RUN"):
element = WebDriverWait(driver, 7200).until(EC.presence_of_element_located((By.CSS_SELECTOR, "input.hidden-password.shown[type='text']"))) element = WebDriverWait(driver, 7200).until(
EC.presence_of_element_located((
By.CSS_SELECTOR,
"input.hidden-password.shown[type='text']")))
vm.password = element.get_attribute("value") vm.password = element.get_attribute("value")
vm.state = driver.find_element_by_css_selector("#state > div > p").text vm.state = driver.find_element_by_css_selector(
vm.protocol = driver.find_element_by_css_selector("#vm-credentials > div > table > tbody > tr:nth-child(1) > td").text "#state > div > p").text
vm.host,vm.port = driver.find_element_by_css_selector("#vm-credentials > div > table > tbody > tr:nth-child(2) > td").text.split(':') vm.protocol = driver.find_element_by_css_selector(
vm.user = driver.find_element_by_css_selector("#vm-credentials > div > table > tbody > tr:nth-child(4) > td").text "#vm-credentials > div > table > tbody > "+
"tr:nth-child(1) > td").text
vm.host,vm.port = driver.find_element_by_css_selector(
"#vm-credentials > div > table > tbody > "+
"tr:nth-child(2) > td").text.split(':')
vm.user = driver.find_element_by_css_selector(
"#vm-credentials > div > table > tbody > "+
"tr:nth-child(4) > td").text
driver.find_element_by_css_selector("a[href*='/logout/']").click() driver.find_element_by_css_selector("a[href*='/logout/']").click()
except: except:
print "Browser session timed out!" print "Browser session timed out!"
raise raise
return vm return vm
##
# Az új webes felület használata
# @return vm Virtuális gép csatlakozásához szükséges paraméterek
#
def main(self): def main(self):
"""
Az új webes felület használata
Keyword arguments:
@return vm -- Virtuális gép csatlakozásához szükséges
paraméterek
"""
vm = Struct() vm = Struct()
driver = self.driver driver = self.driver
driver.maximize_window() driver.maximize_window()
...@@ -107,10 +151,16 @@ class Browser: ...@@ -107,10 +151,16 @@ class Browser:
vm.state, vm.protocol = "", "NONE" vm.state, vm.protocol = "", "NONE"
try: try:
while vm.state.upper()[:3] not in ("FUT", "RUN"): while vm.state.upper()[:3] not in ("FUT", "RUN"):
element = WebDriverWait(driver,7200).until(EC.presence_of_element_located((By.CSS_SELECTOR, "#vm-details-pw-eye.icon-eye-close"))) element = WebDriverWait(driver,7200).until(
vm.state = driver.find_element_by_css_selector("#vm-details-state > span").text EC.presence_of_element_located((
By.CSS_SELECTOR,
"#vm-details-pw-eye.fa.fa-eye-slash")))
vm.state = driver.find_element_by_css_selector(
"#vm-details-state > span").text
#cl: connection string converted to list #cl: connection string converted to list
cl = driver.find_element_by_css_selector("#vm-details-connection-string").get_attribute("value").split() cl = driver.find_element_by_css_selector(
"#vm-details-connection-string").get_attribute(
"value").split()
if cl[0] == "sshpass": if cl[0] == "sshpass":
vm.protocol = "SSH" vm.protocol = "SSH"
vm.user, vm.host = cl[6].split("@") vm.user, vm.host = cl[6].split("@")
...@@ -125,27 +175,26 @@ class Browser: ...@@ -125,27 +175,26 @@ class Browser:
raise raise
return vm return vm
##
# Főprogram
# beolvassuk a paramétereket
# megnyitjuk a kiválasztott böngészőben a weboldalt
# bejelentkezünk a címtárba
# kiválasztjuk a futtatni kívánt klienst
# kapcsolódunk a klienshez
def main(): def main():
"""
Főprogram
Job:
beolvassuk a paramétereket
megnyitjuk a kiválasztott böngészőben a weboldalt
bejelentkezünk a címtárba
kiválasztjuk a futtatni kívánt klienst
kapcsolódunk a klienshez
"""
try: try:
args = pars_arguments() args = parse_arguments()
if args.uri is not None: if args.uri is not None:
vm = Struct() vm = Struct()
vm.protocol, vm.user, vm.password, vm.host, vm.port = args.uri.split(':',4) vm.protocol,vm.user,vm.password,vm.host,vm.port = \
args.uri.split(':',4)
vm.protocol = vm.protocol.upper() vm.protocol = vm.protocol.upper()
vm.state = "RUN" vm.state = "RUN"
else: else:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
browser = Browser(args) browser = Browser(args)
try: try:
if args.old: if args.old:
...@@ -163,5 +212,7 @@ def main(): ...@@ -163,5 +212,7 @@ def main():
connect(vm) connect(vm)
except: except:
print "Unknown error occurred! Please contact the developers!" print "Unknown error occurred! Please contact the developers!"
if __name__ == "__main__": if __name__ == "__main__":
main() main()
...@@ -4,7 +4,14 @@ ...@@ -4,7 +4,14 @@
# Távoli klienshez csatlakozás windows OS alól # Távoli klienshez csatlakozás windows OS alól
## ##
import sys, os, time, subprocess, glob, nxkey, win32crypt, binascii import time
import os
import subprocess
import glob
import win32crypt
import binascii
import nxkey
## ##
# A távoli klienshez csatlakozás valósítja majd meg windows alól # A távoli klienshez csatlakozás valósítja majd meg windows alól
# @param vm Paraméterek a csatlakozáshoz # @param vm Paraméterek a csatlakozáshoz
......
...@@ -162,9 +162,9 @@ IF NOT "!output_on_screen!"=="False" ( ...@@ -162,9 +162,9 @@ IF NOT "!output_on_screen!"=="False" (
goto loop goto loop
) else ( ) else (
set test=%install_path:~0,-1% set test=%install_path:~0,-1%
call %running_directory%inPath test && (IF NOT "!output_on_screen!"=="False" (@echo %test% is already in PATH)) || (call %running_directory%addPath test & setx>nul PATH "%PATH%;%test%" & IF NOT "!output_on_screen!"=="False" ( @echo %test% set to local PATH)) call %running_directory%inPath test && (IF NOT "!output_on_screen!"=="False" (@echo %test% is already in PATH)) || (call %running_directory%addPath test & setx>nul PATH "%PATH%;%test%" /m & IF NOT "!output_on_screen!"=="False" ( @echo %test% set to PATH))
set test=%install_path%Scripts set test=%install_path%Scripts
call %running_directory%inPath test && (IF NOT "!output_on_screen!"=="False" (@echo %test% is already in PATH)) || (call %running_directory%addPath test & setx>nul PATH "%PATH%;%test%" & IF NOT "!output_on_screen!"=="False" ( @echo %test% set to local PATH)) call %running_directory%inPath test && (IF NOT "!output_on_screen!"=="False" (@echo %test% is already in PATH)) || (call %running_directory%addPath test & setx>nul PATH "%PATH%;%test%" /m & IF NOT "!output_on_screen!"=="False" ( @echo %test% set to PATH))
) )
GOTO PIP_CHECK GOTO PIP_CHECK
...@@ -395,7 +395,7 @@ if "!browserToUse!"=="None" ( ...@@ -395,7 +395,7 @@ if "!browserToUse!"=="None" (
call :Split "%browser_path%" test call :Split "%browser_path%" test
set myTest=!test:~0,-1! set myTest=!test:~0,-1!
rem Set that path in the PATH environment variable rem Set that path in the PATH environment variable
call %running_directory%inPath myTest && (IF NOT "!output_on_screen!"=="False" ( @echo !myTest! is already in PATH)) || (call %running_directory%addPath myTest & setx>nul PATH "%PATH%;!myTest!" & IF NOT "!output_on_screen!"=="False" ( @echo !myTest! set to local PATH) ) call %running_directory%inPath myTest && (IF NOT "!output_on_screen!"=="False" ( @echo !myTest! is already in PATH)) || (call %running_directory%addPath myTest & setx>nul PATH "%PATH%;!myTest!" /m & IF NOT "!output_on_screen!"=="False" ( @echo !myTest! set to PATH) )
:install_driver :install_driver
IF NOT "%install_selenium%"=="False" ( IF NOT "%install_selenium%"=="False" (
if NOT "!selenium_driver_name!"=="" ( if NOT "!selenium_driver_name!"=="" (
...@@ -448,7 +448,7 @@ rem Create folder if needed and set it to PATH ...@@ -448,7 +448,7 @@ rem Create folder if needed and set it to PATH
IF NOT "!output_on_screen!"=="False" ( IF NOT "!output_on_screen!"=="False" (
@echo Checking wheter ^'%install_location%^\^' exists already @echo Checking wheter ^'%install_location%^\^' exists already
) )
call %running_directory%inPath install_location && (IF NOT "!output_on_screen!"=="False" ( @echo !install_location! is already in PATH)) || (call %running_directory%addPath install_location & setx>nul PATH "%PATH%;!install_location!" & IF NOT "!output_on_screen!"=="False" ( @echo !install_location! set to local PATH)) call %running_directory%inPath install_location && (IF NOT "!output_on_screen!"=="False" ( @echo !install_location! is already in PATH)) || (call %running_directory%addPath install_location & setx>nul PATH "%PATH%;!install_location!" /m & IF NOT "!output_on_screen!"=="False" ( @echo !install_location! set to PATH))
if not exist "%install_location%\" ( if not exist "%install_location%\" (
mkdir "%install_location%" mkdir "%install_location%"
) )
......
#!/usr/bin/python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
## """
# NX Client for Windows installer with RegistryHandler and DecideArchitecture classes NX Client for Windows installer with RegistryHandler and
# Checks whether NX Client for Windows is installed in the system, the classes used for this DecideArchitecture classes.
# process are used for other operations too Checks whether NX Client for Windows is installed in the system, the
## classes used for this process are used for other operations too.
"""
import os, sys, argparse, errno, subprocess, time import os
if sys.hexversion > 0x02070000: import sys
import argparse
import errno
import subprocess
import time
from _winreg import *
try:
from collections import * from collections import *
else: except ImporError:
from OrderedDict import * from OrderedDict import *
from _winreg import *
##
# Argument parser, based on argparse module def parse_arguments():
# @return args """
# Argument parser, based on argparse module
def pars_arguments():
parser = argparse.ArgumentParser(); Keyword arguments:
@return args -- arguments given by console
"""
parser = argparse.ArgumentParser()
if DecideArchitecture.Is64Windows(): if DecideArchitecture.Is64Windows():
local_default = DecideArchitecture.GetProgramFiles64()+"\\CIRCLE\\" local_default = DecideArchitecture.GetProgramFiles64()+"\\CIRCLE\\"
else: else:
local_default = DecideArchitecture.GetProgramFiles32()+"\\CIRCLE\\" local_default = DecideArchitecture.GetProgramFiles32()+"\\CIRCLE\\"
if not os.path.exists(local_default[:-1]) and os.path.exists(os.environ['APPDATA']+"\\CIRCLE"): if (not os.path.exists(local_default[:-1])
and os.path.exists(os.environ['APPDATA']+"\\CIRCLE")):
local_default = os.environ['APPDATA']+"\\CIRCLE\\" local_default = os.environ['APPDATA']+"\\CIRCLE\\"
parser.add_argument("-l", "--location", help="Location of the client files in the system", default=local_default) parser.add_argument(
parser.add_argument("-g", "--global", help="Whether we want to edit registry globally or just locally", action="store_true") "-l", "--location",
parser.add_argument("-d", "--different", help="Only handle the architecture specific registry area", action="store_true") help="Location of the client files in the system",
parser.add_argument("-r", "--registry", help="Which HKEY_* const registry type the program should use", \ default=local_default)
type=str, choices=['HKLM', 'HKCR', 'HKCU', 'HKU', 'HKPD', 'HKCC'], default="HKLM") parser.add_argument(
args = parser.parse_args(); "-g", "--global",
help="Whether we want to edit registry globally or just locally",
action="store_true")
parser.add_argument(
"-d", "--different",
help="Only handle the architecture specific registry area",
action="store_true")
parser.add_argument(
"-r", "--registry",
help="Which HKEY_* const registry type the program should use",
type=str, choices=['HKLM', 'HKCR', 'HKCU', 'HKU', 'HKPD', 'HKCC'],
default="HKLM")
args = parser.parse_args()
return args return args
##
# Parameter bypassing struct
#
class Struct: class Struct:
"""
Parameter bypassing struct
"""
pass pass
##
# Registry handling class, makes registry based queries and manipulations easier
# This class can handle WOW64 based application differently and none differently (default)
#
class RegistryHandler: class RegistryHandler:
## """
# Initialise RegistryHandler Registry handling class, makes registry based queries and
# @param args The args.registry tells us what registry we need to handle manipulations easier.
# This class can handle WOW64 based application differently and none
differently (default)
"""
def __init__(self, args = None): def __init__(self, args = None):
"""Initialise RegistryHandler
Keyword arguments:
@param args -- The arguments that decide how the we should
handle the registry
args.registry -- What base registry should we use
(default: HKLM)
Raises AttributeError if not supported base registry type is
given
args.different -- Whether we handle registry redirection or not
"""
if args is None: if args is None:
self.args = Struct() self.args = Struct()
self.args.different = None self.args.different = None
...@@ -77,90 +111,139 @@ class RegistryHandler: ...@@ -77,90 +111,139 @@ class RegistryHandler:
else: else:
#print "Non supported registry type" #print "Non supported registry type"
raise AttributeError raise AttributeError
##
# Getting a registry open
# @return connected_registy The registry which we successfully opened
#
def connect_registry(self): def connect_registry(self):
"""
Getting a registry open
Keyword arguments:
@return connected_registy -- Reference to the newly opened
registry
"""
return ConnectRegistry(None,self.args.registry) return ConnectRegistry(None,self.args.registry)
## def create_registry_from_dict_chain(
# Create registry key and value multilevel tree by simple chained dictionaries self, dict_chain, both = False, architect = KEY_WOW64_64KEY,
# Can raise AttributeError if the provided dict chain isn't correct needed_rights = KEY_ALL_ACCESS):
# @param key_value_chain The dict chain containing all the information """"
# @param both Whether create the registry in WOW64 node too Create registry key and value multilevel tree by chained
# @param architect The current registry view (only change it if we want to fill the dictionaries.
# WOW6432 registry only [both = False], on x64 windows) Can raise AttributeError if the provided dict chain isn't
# @param needed_rights SAM rights to access the key correct
#
def create_registry_from_dict_chain(self, dict_chain, both = False, architect = KEY_WOW64_64KEY, needed_rights = KEY_ALL_ACCESS): Keyword arguments:
@param key_value_chain -- The dict chain containing all the
information
@param both -- Whether create the registry in WOW64
node too
@param architect -- The current registry view (
only change it if we want to fill the
WOW6432 registry only [both = False],
on x64 windows)
@param needed_rights -- SAM rights to access the key
"""
if both and architect is KEY_WOW64_64KEY: if both and architect is KEY_WOW64_64KEY:
self.create_registry_from_dict_chain(dict_chain, False, KEY_WOW64_32KEY, needed_rights) self.create_registry_from_dict_chain(
dict_chain, False, KEY_WOW64_32KEY, needed_rights)
if not DecideArchitecture.Is64Windows(): if not DecideArchitecture.Is64Windows():
architect = 0 architect = 0
connected_registy = self.connect_registry() connected_registy = self.connect_registry()
if isinstance(dict_chain, dict) or isinstance(dict_chain, OrderedDict): if (isinstance(dict_chain, dict)
or isinstance(dict_chain, OrderedDict)):
for key, value in dict_chain.iteritems(): for key, value in dict_chain.iteritems():
if isinstance(value, dict) or isinstance(value, OrderedDict): if isinstance(value, dict) or isinstance(value, OrderedDict):
temp_dict = OrderedDict() temp_dict = OrderedDict()
for my_key, my_value in value.iteritems(): for my_key, my_value in value.iteritems():
temp_dict[key+"\\"+my_key] = my_value temp_dict[key+"\\"+my_key] = my_value
self.create_registry_from_dict_chain(temp_dict, False, architect, needed_rights) self.create_registry_from_dict_chain(
temp_dict, False, architect, needed_rights)
else: else:
if isinstance(value, list): if isinstance(value, list):
if len(value)%2 != 0: if len(value)%2 != 0:
#print "Not enough member in the list" #print "Not enough member in the list"
raise AttributeError raise AttributeError
else: else:
new_key = CreateKeyEx(connected_registy, key, 0, needed_rights | architect) new_key = CreateKeyEx(
temp_dict = OrderedDict(value[i:i+2] for i in range(0, len(value), 2)) connected_registy, key, 0,
needed_rights | architect)
temp_dict = OrderedDict(
value[i:i+2] for i in range(
0, len(value), 2))
for my_key, my_value in temp_dict.iteritems(): for my_key, my_value in temp_dict.iteritems():
SetValueEx(new_key,my_key,0, REG_SZ, my_value) if my_key == "default":
my_key = None
SetValueEx(
new_key, my_key, 0, REG_SZ, my_value)
else: else:
new_key = CreateKeyEx(connected_registy, key, 0, needed_rights | architect) new_key = CreateKeyEx(
SetValueEx(new_key,None,0, REG_SZ, value) connected_registy, key, 0,
needed_rights | architect)
SetValueEx(new_key, None, 0, REG_SZ, value)
else: else:
print "The provided attribute wasn't a dictionary chain" print "The provided attribute wasn't a dictionary chain"
raise AttributeError raise AttributeError
##
# Getting a registry value by it's key's name
# Can raise KeyError if key is not found in the registry
# @param key_name The specific key name of which value we are interested in
# @param needed_rights SAM rights to access the key
# @return [key, architect]
# key: The reference to the opened key handler
# architect: 0 for x86
# KEY_WOW64_32KEY or KEY_WOW64_64KEY depending where we found the key on x64
#
def get_key(self, key_name, needed_rights = KEY_ALL_ACCESS): def get_key(self, key_name, needed_rights = KEY_ALL_ACCESS):
"""
Getting a registry value by it's key's name
Can raise KeyError if key is not found in the registry
Keyword arguments:
@param key_name -- The specific key name of which value we
are interested in
@param needed_rights -- SAM rights to access the key
@return -- [key, architect]
key -- Reference to the opened
key handler
architect -- 0 for x86
KEY_WOW64_32KEY or
KEY_WOW64_64KEY
depending where we
found the key on x64
"""
connected_registy = self.connect_registry() connected_registy = self.connect_registry()
architect = 0 architect = 0
if DecideArchitecture.Is64Windows(): if DecideArchitecture.Is64Windows():
architect = KEY_WOW64_64KEY architect = KEY_WOW64_64KEY
try: try:
key = OpenKey(connected_registy, key_name, 0, needed_rights | architect) key = OpenKey(connected_registy, key_name, 0,
needed_rights | architect)
except WindowsError: except WindowsError:
if DecideArchitecture.Is64Windows() and not self.args.different: if DecideArchitecture.Is64Windows() and not self.args.different:
try: try:
architect = KEY_WOW64_32KEY architect = KEY_WOW64_32KEY
key = OpenKey(connected_registy, key_name, 0, needed_rights | architect) key = OpenKey(connected_registy, key_name,
0, needed_rights | architect)
except WindowsError: except WindowsError:
raise KeyError raise KeyError
else: else:
raise KeyError raise KeyError
return [key, architect] return [key, architect]
##
# Getting registry subkeys value by it's key's name and subkeys name def get_key_values(
# Can raise LookupError exception if there are missing data self, key_name, subkey_list, subroutine = False,
# Can raise AttributeError exception if depth attribute is wrong depth = "subkeys"):
# @param key_name The specific key name of which subkey's we are interested in """
# @param subkey_list List containing all the subkeys names which values we are interested in Getting registry subkeys value by it's key's name and subkeys
# @param subroutine Whether suppress exception about not having enough results or not - default False name
# @param depth How depth the search should go for (key, subkeys, all) - default: subkeys Can raise LookupError exception if there are missing data
# @return results{} Dictionary with the subkey_name - value combinations as keys and values Can raise AttributeError exception if depth attribute is wrong
#
def get_key_values(self, key_name, subkey_list, subroutine = False, depth = "subkeys"): Keyword arguments:
@param key_name -- The specific key name of which subkey's
we are interested in
@param subkey_list -- List containing all the subkeys names
which values we are interested in
@param subroutine -- Whether suppress exception about not
having enough results or not
(default: False)
@param depth -- How depth the search should go for
[options: key, subkeys, all]
(default: subkeys)
@return results{} -- Dictionary with the subkey_name - value
combinations as keys and values
"""
if depth == "key": if depth == "key":
int_depth = 0; int_depth = 0;
elif depth == "subkeys": elif depth == "subkeys":
...@@ -174,23 +257,26 @@ class RegistryHandler: ...@@ -174,23 +257,26 @@ class RegistryHandler:
key = key_and_architect[0] key = key_and_architect[0]
architect = key_and_architect[1] architect = key_and_architect[1]
except KeyError: except KeyError:
#print key_name+" doesn't exist in the registry" #print "%s doesn't exist in the registry" % key_name
raise LookupError raise LookupError
#print key_name+" found in the registry" #print "%s found in the registry" % key_name
results = {} results = {}
if int_depth >= 1: if int_depth >= 1:
for i in xrange(0, QueryInfoKey(key)[0]-1): for i in xrange(0, QueryInfoKey(key)[0]-1):
skey_name = EnumKey(key, i) skey_name = EnumKey(key, i)
skey = OpenKey(key, skey_name, 0, KEY_ALL_ACCESS | architect) skey = OpenKey(key, skey_name, 0, KEY_ALL_ACCESS | architect)
if int_depth == 2 and QueryInfoKey(skey)[0] > 0: if int_depth == 2 and QueryInfoKey(skey)[0] > 0:
for key, value in self.get_key_values(skey_name, subkey_list, True, depth).iteritems(): for key, value in self.get_key_values(
skey_name, subkey_list, True, depth).iteritems():
results[key] = value results[key] = value
for subkey_name in subkey_list: for subkey_name in subkey_list:
try: try:
results[subkey_name] = QueryValueEx(skey, subkey_name)[0] results[subkey_name] = QueryValueEx(
skey, subkey_name)[0]
except OSError as e: except OSError as e:
if e.errno == errno.ENOENT: if e.errno == errno.ENOENT:
#print subkey_name+" doesn't exist in this subkey" #print ("%s doesn't exist in this" % subkey_name
# " subkey")
pass pass
skey.Close() skey.Close()
if not results or len(results) != len(subkey_list): if not results or len(results) != len(subkey_list):
...@@ -201,34 +287,46 @@ class RegistryHandler: ...@@ -201,34 +287,46 @@ class RegistryHandler:
pass pass
key.Close() key.Close()
if len(results) != len(subkey_list): if len(results) != len(subkey_list):
#print We are missing important variables #print "We are missing important variables"
raise LookupError raise LookupError
return results return results
## def get_key_value(
# This is a wrapper for the get_key_values to be easier to use for single subkeys self, key_name, subkey_name, subroutine = None, depth = None):
# Getting registry subkey value by it's key's name and subkey name """
# @param key_name The specific key name of which subkey's we are interested in This is a wrapper for the get_key_values to be easier to use
# @param subkey_name The specific subkey name which value we are interested in for single subkeys.
# @param subroutine can be found at: get_key_values Getting registry subkey value by it's key's name and subkey
# @param depth can be found at: get_key_values name
# @return value Value of the specific subkey
# Keyword arguments:
def get_key_value(self, key_name, subkey_name, subroutine = None, depth = None): @param key_name -- The specific key name of which subkey's
we are interested in
@param subkey_name -- The specific subkey name which value we
are interested in
@param subroutine -- can be found at: get_key_values
@param depth -- can be found at: get_key_values
@return value -- Value of the specific subkey
"""
try: try:
if subroutine is None: if subroutine is None:
return self.get_key_values(key_name, [subkey_name])[subkey_name] return self.get_key_values(key_name,
[subkey_name])[subkey_name]
elif depth is None: elif depth is None:
return self.get_key_values(key_name, [subkey_name], subroutine)[subkey_name] return self.get_key_values(key_name, [subkey_name],
subroutine)[subkey_name]
else: else:
return self.get_key_values(key_name, [subkey_name], subroutine, depth)[subkey_name] return self.get_key_values(key_name, [subkey_name],
subroutine, depth)[subkey_name]
except: except:
raise raise
##
# Helper class to get the true ProgramFiles directory.
# This class doesn't depend on Phyton or Windows architecture.
#
class DecideArchitecture: class DecideArchitecture:
"""
Helper class to get the true ProgramFiles directory.
This class doesn't depend on Phyton or Windows architecture.
"""
@staticmethod @staticmethod
def Is64Windows(): def Is64Windows():
return 'PROGRAMFILES(X86)' in os.environ return 'PROGRAMFILES(X86)' in os.environ
...@@ -247,22 +345,31 @@ class DecideArchitecture: ...@@ -247,22 +345,31 @@ class DecideArchitecture:
def main(): def main():
try: try:
args = pars_arguments() args = parse_arguments()
nx_install_location = None nx_install_location = None
while nx_install_location is None: while nx_install_location is None:
print "Checking whether NX Client for Windows is installed" print "Checking whether NX Client for Windows is installed"
handler = RegistryHandler() handler = RegistryHandler()
try: try:
nx_install_location = handler.get_key_value("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\nxclient_is1", "InstallLocation", "key") nx_install_location = handler.get_key_value(
print "NX Client for Windows is found at '"+nx_install_location+"'" "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\"+
process = subprocess.Popen("%s\\nxclient.exe" % nx_install_location) "Uninstall\\nxclient_is1",
"InstallLocation", "key")
print ("NX Client for Windows is found at "
"'%s'" % nx_install_location)
process = subprocess.Popen(
"%s\\nxclient.exe" % nx_install_location)
time.sleep(2) time.sleep(2)
process.terminate() process.terminate()
except: except:
print "NX Client for Windows isn't installed on the system." print "NX Client for Windows isn't installed on the system."
print "\tCommencing the install" print "\tCommencing the install"
subprocess.Popen(os.path.dirname(os.path.realpath(__file__))+"\\nxclient-3.5.0-9.exe").wait() subprocess.Popen(os.path.dirname(
os.path.realpath(__file__))+
"\\nxclient-3.5.0-9.exe").wait()
except: except:
pass pass
if __name__ == "__main__": if __name__ == "__main__":
main() main()
\ No newline at end of file
#!/usr/bin/python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
## """
# Generating NoMachine NX scrambled key according to https://www.nomachine.com/AR01C00125 Generating NoMachine NX scrambled key according to
## https://www.nomachine.com/AR01C00125
"""
import sys import sys
import random import random
import re import re
from xml.sax.saxutils import escape from xml.sax.saxutils import escape
##
# NXKeyGen class
# Creates NoMachine NX scrambled keys
#
class NXKeyGen: class NXKeyGen:
"""
NXKeyGen class
Creates NoMachine NX scrambled keys
"""
numValidCharList = 85 numValidCharList = 85
dummyString = "{{{{" dummyString = "{{{{"
##
# Initialize the class
# @param password Password that will be scrambled
#
def __init__(self, password): def __init__(self, password):
"""
Initialize the class
Keyword arguments:
@param password -- Password that will be scrambled
"""
self.password = password self.password = password
##
# Encrypt (scramble) the given password
# @return scrambleString Scrambled version of the original password
#
def getEncrypted(self): def getEncrypted(self):
"""
Encrypt (scramble) the given password
Keyword arguments:
@return scrambleString -- Scrambled version of the original
password
"""
return self.scrambleString(self.password) return self.scrambleString(self.password)
##
# Valid character list
# @return validcharlist List of the valid characters
#
def getvalidCharList(self, pos): def getvalidCharList(self, pos):
"""
Valid character list
Keyword arguments:
@return validcharlist -- List of the valid characters
"""
validcharlist = [ validcharlist = [
"!", "#", "$", "%", "&", "(", ")", "*", "+", "-", "!", "#", "$", "%", "&", "(", ")", "*", "+", "-",
".", "0", "1", "2", "3", "4", "5", "6", "7", "8", ".", "0", "1", "2", "3", "4", "5", "6", "7", "8",
...@@ -47,11 +57,13 @@ class NXKeyGen: ...@@ -47,11 +57,13 @@ class NXKeyGen:
] ]
return validcharlist[pos] return validcharlist[pos]
##
# Password encoder
# @return sPass Encoded password
#
def encodePassword(self, p): def encodePassword(self, p):
"""
Password encoder
Keyword arguments:
@return sPass -- Encoded password
"""
sPass = ":" sPass = ":"
sTmp = "" sTmp = ""
if not p: if not p:
...@@ -64,12 +76,14 @@ class NXKeyGen: ...@@ -64,12 +76,14 @@ class NXKeyGen:
sTmp = "" sTmp = ""
return sPass return sPass
##
# Character position finder
# @param c Character that needs to be matched if valid
# @return i Place where the character is in the valid list
#
def findCharInList(self, c): def findCharInList(self, c):
"""
Character position finder
Keyword arguments:
@param c -- Character that needs to be matched if valid
@return i -- Place where the character is in the valid list
"""
i = -1 i = -1
for j in range(self.numValidCharList): for j in range(self.numValidCharList):
randchar = self.getvalidCharList(j); randchar = self.getvalidCharList(j);
...@@ -78,19 +92,23 @@ class NXKeyGen: ...@@ -78,19 +92,23 @@ class NXKeyGen:
return i return i
return i return i
##
# Random valid character getter
# @return char Valid character placed 0-60 in the valid list
#
def getRandomValidCharFromList(self): def getRandomValidCharFromList(self):
"""
Random valid character getter
Keyword arguments:
@return char -- Valid character placed 0-60 in the valid list
"""
return self.getvalidCharList(random.randint(0,60)) return self.getvalidCharList(random.randint(0,60))
##
# Password scrambler
# @param s Password that needs to be scrambled
# @return sRet NoMachine NX scrambled password
#
def scrambleString(self, s): def scrambleString(self, s):
"""
Password scrambler
Keyword arguments:
@param s -- Password that needs to be scrambled
@return sRet -- NoMachine NX scrambled password
"""
sRet = "" sRet = ""
if not s: if not s:
return s return s
...@@ -118,10 +136,10 @@ class NXKeyGen: ...@@ -118,10 +136,10 @@ class NXKeyGen:
sRet = sRet + c2 sRet = sRet + c2
return escape(sRet) return escape(sRet)
##
# Replace a character at a special position
#
def substr_replace(self,in_str,ch,pos,qt): def substr_replace(self,in_str,ch,pos,qt):
"""
Replace a character at a special position
"""
clist = list(in_str) clist = list(in_str)
count = 0; count = 0;
tmp_str = ''; tmp_str = '';
...@@ -134,7 +152,6 @@ class NXKeyGen: ...@@ -134,7 +152,6 @@ class NXKeyGen:
return tmp_str return tmp_str
if __name__ == "__main__": if __name__ == "__main__":
NXPass = NXKeyGen(sys.argv[1]) NXPass = NXKeyGen(sys.argv[1])
print NXPass.password print NXPass.password
......
#!/usr/bin/python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
## """
# Pywin32 installer for CIRCLE client application Pywin32 installer for CIRCLE client application
## """
import os, sys, subprocess import os
import sys
import subprocess
from nx_client_installer import DecideArchitecture from nx_client_installer import DecideArchitecture
##
# Main program
# Install Pywin32 to the computer
#
def main(): def main():
"""
Main program
Job:
Install Pywin32 to the computer
"""
if sys.hexversion < 0x02060000: if sys.hexversion < 0x02060000:
print "Not a 2.6+ version Python is running, commencing update" print "Not a 2.6+ version Python is running, commencing update"
subprocess.Popen(os.path.dirname(os.path.realpath(__file__))+"\\no_root_install.bat") subprocess.Popen(
"%s\\no_root_install.bat" % os.path.dirname(
os.path.realpath(__file__)))
sys.exit(1) sys.exit(1)
else: else:
pywin32_version = str(219) pywin32_version = str(219)
if sys.hexversion < 0x02070000: if sys.hexversion < 0x02070000:
if DecideArchitecture.Is64Windows(): if DecideArchitecture.Is64Windows():
subprocess.Popen(os.path.dirname(os.path.realpath(__file__))+"\\x64\\pywin32-"+pywin32_version+".win-amd64-py2.6.exe").wait() subprocess.Popen(
"%s\\x64\\pywin32-%s.win-amd64-py2.6.exe" % (
os.path.dirname(os.path.realpath(__file__)),
pywin32_version)).wait()
else: else:
subprocess.Popen(os.path.dirname(os.path.realpath(__file__))+"\\x86\\pywin32-"+pywin32_version+".win32-py2.6.exe").wait() subprocess.Popen(
"%s\\x86\\pywin32-%s.win32-py2.6.exe" % (
os.path.dirname(os.path.realpath(__file__)),
pywin32_version)).wait()
elif sys.hexversion < 0x02080000: elif sys.hexversion < 0x02080000:
if DecideArchitecture.Is64Windows(): if DecideArchitecture.Is64Windows():
subprocess.Popen(os.path.dirname(os.path.realpath(__file__))+"\\x64\\pywin32-"+pywin32_version+".win-amd64-py2.7.exe").wait() subprocess.Popen(
"%s\\x64\\pywin32-%s.win-amd64-py2.7.exe" % (
os.path.dirname(os.path.realpath(__file__)),
pywin32_version)).wait()
else: else:
subprocess.Popen(os.path.dirname(os.path.realpath(__file__))+"\\x86\\pywin32-"+pywin32_version+".win32-py2.7.exe").wait() subprocess.Popen(
"%s\\x86\\pywin32-%s.win32-py2.7.exe" % (
os.path.dirname(os.path.realpath(__file__)),
pywin32_version)).wait()
else: else:
print "Unsupported Python version is found!" print "Unsupported Python version is found!"
if __name__ == "__main__": if __name__ == "__main__":
main() main()
\ No newline at end of file
#!/usr/bin/python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
## """
# Windows icon installer for CIRCLE client application Windows icon installer for CIRCLE client application
## """
import os, sys, argparse, subprocess import os
if sys.hexversion > 0x02070000: import argparse
from collections import * import subprocess
else:
from OrderedDict import *
import pythoncom import pythoncom
from win32com.shell import shell, shellcon from win32com.shell import shell, shellcon
from nx_client_installer import DecideArchitecture, RegistryHandler, Struct from nx_client_installer import DecideArchitecture, RegistryHandler, Struct
try:
from collections import *
except ImporError:
from OrderedDict import *
##
# Argument parser, based on argparse module
# @return args def parse_arguments():
# """
def pars_arguments(): Argument parser, based on argparse module
parser = argparse.ArgumentParser();
parser.add_argument("-d", "--driver", help="Select webdriver. Aside from Firefox, you have to install first the proper driver.", \ Keyword arguments:
type=str, choices=['firefox', 'chrome', 'iexplore', 'opera'], default="firefox", required=False) @return args -- arguments given by console
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"-d", "--driver",
help="Select webdriver. Aside from Firefox, you have to install "+
"first the proper driver.", type=str, default="firefox",
required=False, choices=['firefox', 'chrome',
'iexplore', 'opera'])
if DecideArchitecture.Is64Windows(): if DecideArchitecture.Is64Windows():
local_default = DecideArchitecture.GetProgramFiles64()+"\\CIRCLE\\" local_default = DecideArchitecture.GetProgramFiles64()+"\\CIRCLE\\"
else: else:
local_default = DecideArchitecture.GetProgramFiles32()+"\\CIRCLE\\" local_default = DecideArchitecture.GetProgramFiles32()+"\\CIRCLE\\"
if not os.path.exists(local_default[:-1]) and os.path.exists(os.environ['APPDATA']+"\\CIRCLE"): if (not os.path.exists(local_default[:-1])
and os.path.exists(os.environ['APPDATA']+"\\CIRCLE")):
local_default = os.environ['APPDATA']+"\\CIRCLE\\" local_default = os.environ['APPDATA']+"\\CIRCLE\\"
parser.add_argument("-l", "--location", help="Location of the client files in the system", default=local_default, required=False) parser.add_argument(
parser.add_argument("-r", "--remove", help="Remove installed files instead of creating them", action="store_true", required=False) "-l", "--location", help="Location of the client files in the system",
parser.add_argument("-u", "--url", help="Whether we installed and we want to use selenium or not", action="store_true", required=False) default=local_default, required=False)
parser.add_argument("-t", "--target", help="If this is an URL icon, where should it point", default="https://pc3.szgt.uni-miskolc.hu/", required=False) parser.add_argument(
args = parser.parse_args(); "-r", "--remove",
help="Remove installed files instead of creating them",
action="store_true", required=False)
parser.add_argument(
"-u", "--url",
help="Whether we installed and we want to use selenium or not",
action="store_true", required=False)
parser.add_argument(
"-t", "--target",
help="If this is an URL icon, where should it point",
default="https://pc3.szgt.uni-miskolc.hu/", required=False)
args = parser.parse_args()
return args return args
##
# Custom protocol register based on RegistryHandler module
# Can raise AttributeError on wrongly provided dictionary chain
# @param dict_chain OrderedDictionary chain of the registry tree
#
def custom_protocol_register(custom_protocol): def custom_protocol_register(custom_protocol):
"""
Custom protocol register based on RegistryHandler module
Can raise AttributeError on wrongly provided dictionary chain
Keyword arguments:
@param dict_chain -- OrderedDictionary chain of the registry tree
"""
if not isinstance(custom_protocol, OrderedDict): if not isinstance(custom_protocol, OrderedDict):
raise AttributeError raise AttributeError
print "\t"+custom_protocol.iterkeys().next() print "\t"+custom_protocol.iterkeys().next()
...@@ -53,14 +77,18 @@ def custom_protocol_register(custom_protocol): ...@@ -53,14 +77,18 @@ def custom_protocol_register(custom_protocol):
except: except:
raise raise
##
# Main program
# read the parameters
# create a proper icon with the proper driver
# call the nx_client_installer
def main(): def main():
#try: """
args = pars_arguments() Main program
Jobs:
read the parameters
create a proper icon with the proper driver (or delete)
call the nx_client_installer
"""
try:
args = parse_arguments()
shortcut = pythoncom.CoCreateInstance ( shortcut = pythoncom.CoCreateInstance (
shell.CLSID_ShellLink, shell.CLSID_ShellLink,
None, None,
...@@ -75,7 +103,9 @@ def main(): ...@@ -75,7 +103,9 @@ def main():
if os.path.isfile("%s%s" % (location, ".url")): if os.path.isfile("%s%s" % (location, ".url")):
os.remove("%s%s" % (location, ".url")) os.remove("%s%s" % (location, ".url"))
else: else:
subprocess.call("python "+os.path.dirname(os.path.realpath(__file__))+"\\nx_client_installer.py") subprocess.call(
"python %s\\nx_client_installer.py" % os.path.dirname(
os.path.realpath(__file__)))
if args.url: if args.url:
location = os.path.join(desktop_path, "Cloud GUI.url") location = os.path.join(desktop_path, "Cloud GUI.url")
shortcut = file(location, 'w') shortcut = file(location, 'w')
...@@ -92,27 +122,44 @@ def main(): ...@@ -92,27 +122,44 @@ def main():
shortcut.SetArguments("-d opera") shortcut.SetArguments("-d opera")
shortcut.SetDescription ("Tool to use CIRCLE Cloud") shortcut.SetDescription ("Tool to use CIRCLE Cloud")
shortcut.SetIconLocation (args.location+"cloud.ico", 0) shortcut.SetIconLocation (args.location+"cloud.ico", 0)
desktop_path = shell.SHGetFolderPath (0, shellcon.CSIDL_DESKTOP, 0, 0) desktop_path = shell.SHGetFolderPath(
persist_file = shortcut.QueryInterface (pythoncom.IID_IPersistFile) 0, shellcon.CSIDL_DESKTOP, 0, 0)
persist_file.Save (os.path.join (desktop_path, "Cloud GUI.lnk"), 0) persist_file = shortcut.QueryInterface(
pythoncom.IID_IPersistFile)
persist_file.Save(
os.path.join(desktop_path, "Cloud GUI.lnk"), 0)
print "Icon successfully created on desktop" print "Icon successfully created on desktop"
print "Creating custom URL protocol handlers" print "Creating custom URL protocol handlers"
try: try:
custom_ssh = OrderedDict([('ssh', "URL:CIRCLE-SSH Protocol"), ('ssh\\URL Protocol', ""),\ custom_ssh = OrderedDict(
('ssh\\DefaultIcon', args.location+"cloud.ico"),\ [('ssh', ["default", "URL:ssh Protocol", "URL Protocol", ""]),
('ssh\\shell', {'open': {'command': "\"python.exe\" \""+args.location+"cloud.py\" \"%1\""}})]) ('ssh\\URL Protocol', ""),
('ssh\\DefaultIcon', args.location+"cloud.ico"),
('ssh\\shell', {'open': {
'command': "\"python.exe\" \"%s" % args.location+
"cloud.py\" \"%1\""}})])
custom_protocol_register(custom_ssh) custom_protocol_register(custom_ssh)
custom_rdp = OrderedDict([('rdp', "URL:CIRCLE-RDP Protocol"), ('rdp\\URL Protocol', ""),\ custom_rdp = OrderedDict(
('rdp\\DefaultIcon', args.location+"cloud.ico"),\ [('rdp', ["default", "URL:rdp Protocol", "URL Protocol", ""]),
('rdp\\shell', {'open': {'command': "\"python.exe\" \""+args.location+"cloud.py\" \"%1\""}})]) ('rdp\\URL Protocol', ""),
('rdp\\DefaultIcon', args.location+"cloud.ico"),
('rdp\\shell', {'open': {
'command': "\"python.exe\" \"%s" % args.location+
"cloud.py\" \"%1\""}})])
custom_protocol_register(custom_rdp) custom_protocol_register(custom_rdp)
custom_nx = OrderedDict([('nx', "URL:CIRCLE-NX Protocol"), ('nx\\URL Protocol', ""),\ custom_nx = OrderedDict(
('nx\\DefaultIcon', args.location+"cloud.ico"),\ [('nx', ["default", "URL:nx Protocol", "URL Protocol", ""]),
('nx\\shell', {'open': {'command': "\"python.exe\" \""+args.location+"cloud.py\" \"%1\""}})]) ('nx\\URL Protocol', ""),
('nx\\DefaultIcon', args.location+"cloud.ico"),
('nx\\shell', {'open': {
'command': "\"python.exe\" \"%s" % args.location+
"cloud.py\" \"%1\""}})])
custom_protocol_register(custom_nx) custom_protocol_register(custom_nx)
except: except:
print "Error! URL Protocol handler installation aborted!" print "Error! URL Protocol handler installation aborted!"
#except: except:
# print "Unknown error occurred! Please contact the developers!" print "Unknown error occurred! Please contact the developers!"
if __name__ == "__main__": if __name__ == "__main__":
main() main()
\ No newline at end of file
#!/usr/bin/python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
## """
# A cloudban létrehozott virtuális gépekhez történő kapcsolódást segítő program A cloudban létrehozott virtuális gépekhez történő kapcsolódást segítő
## program
"""
import platform, argparse, sys, time import platform
import argparse
import sys
import time
try:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
except ImporError:
pass
##
# Paraméterek átadására használt struktúra
# state A virtuális gép állapota, azt figyeljük, hogy fut-e
# protocol SSH, NX és RDP lehetséges
# host A virtuális gép címe
# port Ezen a porton csatlakozunk a virtuális géphez
# user Csatlakozáshoz használt név
# password Csatlakozáshoz használt jelszó
class Struct: class Struct:
"""
Paraméterek átadására használt struktúra
Keyword arguments:
state -- A virtuális gép állapota, azt figyeljük, hogy fut-e
protocol -- SSH, NX és RDP lehetséges
host -- A virtuális gép címe
port -- Ezen a porton csatlakozunk a virtuális géphez
user -- Csatlakozáshoz használt név
password -- Csatlakozáshoz használt jelszó
"""
pass pass
##
# Argument parser, argparse modulon alapszik
# @return args
#
def pars_arguments(): def parse_arguments():
parser = argparse.ArgumentParser(); """
parser.add_argument("uri", type=str, help="Specific schema handler", nargs='?', default=None) Argument parser, argparse modulon alapszik
Keyword arguments:
@return args -- arguments given by console
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"uri", type=str, help="Specific schema handler", nargs='?',
default=None)
parser.add_argument("-u", "--username", type=str) parser.add_argument("-u", "--username", type=str)
parser.add_argument("-p", "--password", type=str) parser.add_argument("-p", "--password", type=str)
parser.add_argument("-d", "--driver", help="Select webdriver. Aside from Firefox, you have to install first the proper driver.", \ parser.add_argument(
type=str, choices=['firefox', 'chrome', 'ie', 'opera'], default="firefox") "-d", "--driver",
parser.add_argument("-o", "--old", help="Use old interface", action="store_true") help="Select webdriver. Aside from Firefox, you have to install "+
args = parser.parse_args(); "first the proper driver.", type=str,
choices=['firefox', 'chrome', 'ie', 'opera'],
default="firefox")
parser.add_argument(
"-o", "--old", help="Use old interface", action="store_true")
args = parser.parse_args()
return args return args
class Browser: class Browser:
## """
# Browser inicializálás Browser inicializálás
# @param args Az args.driver paraméterrel meghatározhatjuk, melyik böngészőt akarjuk használni.
# Keyword arguments:
@param args -- Az args.driver paraméterrel meghatározhatjuk,
melyik böngészőt akarjuk használni.
"""
def __init__(self, args): def __init__(self, args):
self.args = args self.args = args
if args.driver == "firefox": if args.driver == "firefox":
...@@ -52,10 +78,11 @@ class Browser: ...@@ -52,10 +78,11 @@ class Browser:
self.driver = webdriver.Opera() self.driver = webdriver.Opera()
self.driver.implicitly_wait(10) self.driver.implicitly_wait(10)
##
# Címtáras beléptetés a parancssorban megadott paraméterek alapján
#
def login(self): def login(self):
"""
Címtáras beléptetés a parancssorban megadott paraméterek
alapján
"""
driver = self.driver driver = self.driver
args = self.args args = self.args
if args.username is not None: if args.username is not None:
...@@ -65,13 +92,17 @@ class Browser: ...@@ -65,13 +92,17 @@ class Browser:
driver.find_element_by_name("j_password").clear() driver.find_element_by_name("j_password").clear()
driver.find_element_by_name("j_password").send_keys(args.password) driver.find_element_by_name("j_password").send_keys(args.password)
if args.username is not None and args.password is not None: if args.username is not None and args.password is not None:
driver.find_element_by_css_selector("input[type='submit']").click() driver.find_element_by_css_selector(
"input[type='submit']").click()
##
# A régi webes felület használata
# @return vm Virtuális gép csatlakozásához szükséges paraméterek
#
def old_main(self): def old_main(self):
"""
A régi webes felület használata
Keyword arguments:
@return vm -- Virtuális gép csatlakozásához szükséges
paraméterek
"""
vm = Struct() vm = Struct()
driver = self.driver driver = self.driver
driver.maximize_window() driver.maximize_window()
...@@ -81,23 +112,36 @@ class Browser: ...@@ -81,23 +112,36 @@ class Browser:
vm.state, vm.protocol = "", "NONE" vm.state, vm.protocol = "", "NONE"
try: try:
while vm.state.upper()[:3] not in ("FUT", "RUN"): while vm.state.upper()[:3] not in ("FUT", "RUN"):
element = WebDriverWait(driver, 7200).until(EC.presence_of_element_located((By.CSS_SELECTOR, "input.hidden-password.shown[type='text']"))) element = WebDriverWait(driver, 7200).until(
EC.presence_of_element_located((
By.CSS_SELECTOR,
"input.hidden-password.shown[type='text']")))
vm.password = element.get_attribute("value") vm.password = element.get_attribute("value")
vm.state = driver.find_element_by_css_selector("#state > div > p").text vm.state = driver.find_element_by_css_selector(
vm.protocol = driver.find_element_by_css_selector("#vm-credentials > div > table > tbody > tr:nth-child(1) > td").text "#state > div > p").text
vm.host,vm.port = driver.find_element_by_css_selector("#vm-credentials > div > table > tbody > tr:nth-child(2) > td").text.split(':') vm.protocol = driver.find_element_by_css_selector(
vm.user = driver.find_element_by_css_selector("#vm-credentials > div > table > tbody > tr:nth-child(4) > td").text "#vm-credentials > div > table > tbody > "+
"tr:nth-child(1) > td").text
vm.host,vm.port = driver.find_element_by_css_selector(
"#vm-credentials > div > table > tbody > "+
"tr:nth-child(2) > td").text.split(':')
vm.user = driver.find_element_by_css_selector(
"#vm-credentials > div > table > tbody > "+
"tr:nth-child(4) > td").text
driver.find_element_by_css_selector("a[href*='/logout/']").click() driver.find_element_by_css_selector("a[href*='/logout/']").click()
except: except:
print "Browser session timed out!" print "Browser session timed out!"
raise raise
return vm return vm
##
# Az új webes felület használata
# @return vm Virtuális gép csatlakozásához szükséges paraméterek
#
def main(self): def main(self):
"""
Az új webes felület használata
Keyword arguments:
@return vm -- Virtuális gép csatlakozásához szükséges
paraméterek
"""
vm = Struct() vm = Struct()
driver = self.driver driver = self.driver
driver.maximize_window() driver.maximize_window()
...@@ -107,10 +151,16 @@ class Browser: ...@@ -107,10 +151,16 @@ class Browser:
vm.state, vm.protocol = "", "NONE" vm.state, vm.protocol = "", "NONE"
try: try:
while vm.state.upper()[:3] not in ("FUT", "RUN"): while vm.state.upper()[:3] not in ("FUT", "RUN"):
element = WebDriverWait(driver,7200).until(EC.presence_of_element_located((By.CSS_SELECTOR, "#vm-details-pw-eye.icon-eye-close"))) element = WebDriverWait(driver,7200).until(
vm.state = driver.find_element_by_css_selector("#vm-details-state > span").text EC.presence_of_element_located((
By.CSS_SELECTOR,
"#vm-details-pw-eye.fa.fa-eye-slash")))
vm.state = driver.find_element_by_css_selector(
"#vm-details-state > span").text
#cl: connection string converted to list #cl: connection string converted to list
cl = driver.find_element_by_css_selector("#vm-details-connection-string").get_attribute("value").split() cl = driver.find_element_by_css_selector(
"#vm-details-connection-string").get_attribute(
"value").split()
if cl[0] == "sshpass": if cl[0] == "sshpass":
vm.protocol = "SSH" vm.protocol = "SSH"
vm.user, vm.host = cl[6].split("@") vm.user, vm.host = cl[6].split("@")
...@@ -125,27 +175,26 @@ class Browser: ...@@ -125,27 +175,26 @@ class Browser:
raise raise
return vm return vm
##
# Főprogram
# beolvassuk a paramétereket
# megnyitjuk a kiválasztott böngészőben a weboldalt
# bejelentkezünk a címtárba
# kiválasztjuk a futtatni kívánt klienst
# kapcsolódunk a klienshez
def main(): def main():
"""
Főprogram
Job:
beolvassuk a paramétereket
megnyitjuk a kiválasztott böngészőben a weboldalt
bejelentkezünk a címtárba
kiválasztjuk a futtatni kívánt klienst
kapcsolódunk a klienshez
"""
try: try:
args = pars_arguments() args = parse_arguments()
if args.uri is not None: if args.uri is not None:
vm = Struct() vm = Struct()
vm.protocol, vm.user, vm.password, vm.host, vm.port = args.uri.split(':',4) vm.protocol,vm.user,vm.password,vm.host,vm.port = \
args.uri.split(':',4)
vm.protocol = vm.protocol.upper() vm.protocol = vm.protocol.upper()
vm.state = "RUN" vm.state = "RUN"
else: else:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
browser = Browser(args) browser = Browser(args)
try: try:
if args.old: if args.old:
...@@ -163,5 +212,7 @@ def main(): ...@@ -163,5 +212,7 @@ def main():
connect(vm) connect(vm)
except: except:
print "Unknown error occurred! Please contact the developers!" print "Unknown error occurred! Please contact the developers!"
if __name__ == "__main__": if __name__ == "__main__":
main() main()
...@@ -4,7 +4,14 @@ ...@@ -4,7 +4,14 @@
# Távoli klienshez csatlakozás windows OS alól # Távoli klienshez csatlakozás windows OS alól
## ##
import sys, os, time, subprocess, glob, nxkey, win32crypt, binascii import time
import os
import subprocess
import glob
import win32crypt
import binascii
import nxkey
## ##
# A távoli klienshez csatlakozás valósítja majd meg windows alól # A távoli klienshez csatlakozás valósítja majd meg windows alól
# @param vm Paraméterek a csatlakozáshoz # @param vm Paraméterek a csatlakozáshoz
......
#!/usr/bin/python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
## """
# NX Client for Windows installer with RegistryHandler and DecideArchitecture classes NX Client for Windows installer with RegistryHandler and
# Checks whether NX Client for Windows is installed in the system, the classes used for this DecideArchitecture classes.
# process are used for other operations too Checks whether NX Client for Windows is installed in the system, the
## classes used for this process are used for other operations too.
"""
import os, sys, argparse, errno, subprocess, time import os
if sys.hexversion > 0x02070000: import sys
import argparse
import errno
import subprocess
import time
from _winreg import *
try:
from collections import * from collections import *
else: except ImporError:
from OrderedDict import * from OrderedDict import *
from _winreg import *
##
# Argument parser, based on argparse module def parse_arguments():
# @return args """
# Argument parser, based on argparse module
def pars_arguments():
parser = argparse.ArgumentParser(); Keyword arguments:
@return args -- arguments given by console
"""
parser = argparse.ArgumentParser()
if DecideArchitecture.Is64Windows(): if DecideArchitecture.Is64Windows():
local_default = DecideArchitecture.GetProgramFiles64()+"\\CIRCLE\\" local_default = DecideArchitecture.GetProgramFiles64()+"\\CIRCLE\\"
else: else:
local_default = DecideArchitecture.GetProgramFiles32()+"\\CIRCLE\\" local_default = DecideArchitecture.GetProgramFiles32()+"\\CIRCLE\\"
if not os.path.exists(local_default[:-1]) and os.path.exists(os.environ['APPDATA']+"\\CIRCLE"): if (not os.path.exists(local_default[:-1])
and os.path.exists(os.environ['APPDATA']+"\\CIRCLE")):
local_default = os.environ['APPDATA']+"\\CIRCLE\\" local_default = os.environ['APPDATA']+"\\CIRCLE\\"
parser.add_argument("-l", "--location", help="Location of the client files in the system", default=local_default) parser.add_argument(
parser.add_argument("-g", "--global", help="Whether we want to edit registry globally or just locally", action="store_true") "-l", "--location",
parser.add_argument("-d", "--different", help="Only handle the architecture specific registry area", action="store_true") help="Location of the client files in the system",
parser.add_argument("-r", "--registry", help="Which HKEY_* const registry type the program should use", \ default=local_default)
type=str, choices=['HKLM', 'HKCR', 'HKCU', 'HKU', 'HKPD', 'HKCC'], default="HKLM") parser.add_argument(
args = parser.parse_args(); "-g", "--global",
help="Whether we want to edit registry globally or just locally",
action="store_true")
parser.add_argument(
"-d", "--different",
help="Only handle the architecture specific registry area",
action="store_true")
parser.add_argument(
"-r", "--registry",
help="Which HKEY_* const registry type the program should use",
type=str, choices=['HKLM', 'HKCR', 'HKCU', 'HKU', 'HKPD', 'HKCC'],
default="HKLM")
args = parser.parse_args()
return args return args
##
# Parameter bypassing struct
#
class Struct: class Struct:
"""
Parameter bypassing struct
"""
pass pass
##
# Registry handling class, makes registry based queries and manipulations easier
# This class can handle WOW64 based application differently and none differently (default)
#
class RegistryHandler: class RegistryHandler:
## """
# Initialise RegistryHandler Registry handling class, makes registry based queries and
# @param args The args.registry tells us what registry we need to handle manipulations easier.
# This class can handle WOW64 based application differently and none
differently (default)
"""
def __init__(self, args = None): def __init__(self, args = None):
"""Initialise RegistryHandler
Keyword arguments:
@param args -- The arguments that decide how the we should
handle the registry
args.registry -- What base registry should we use
(default: HKLM)
Raises AttributeError if not supported base registry type is
given
args.different -- Whether we handle registry redirection or not
"""
if args is None: if args is None:
self.args = Struct() self.args = Struct()
self.args.different = None self.args.different = None
...@@ -77,90 +111,139 @@ class RegistryHandler: ...@@ -77,90 +111,139 @@ class RegistryHandler:
else: else:
#print "Non supported registry type" #print "Non supported registry type"
raise AttributeError raise AttributeError
##
# Getting a registry open
# @return connected_registy The registry which we successfully opened
#
def connect_registry(self): def connect_registry(self):
"""
Getting a registry open
Keyword arguments:
@return connected_registy -- Reference to the newly opened
registry
"""
return ConnectRegistry(None,self.args.registry) return ConnectRegistry(None,self.args.registry)
## def create_registry_from_dict_chain(
# Create registry key and value multilevel tree by simple chained dictionaries self, dict_chain, both = False, architect = KEY_WOW64_64KEY,
# Can raise AttributeError if the provided dict chain isn't correct needed_rights = KEY_ALL_ACCESS):
# @param key_value_chain The dict chain containing all the information """"
# @param both Whether create the registry in WOW64 node too Create registry key and value multilevel tree by chained
# @param architect The current registry view (only change it if we want to fill the dictionaries.
# WOW6432 registry only [both = False], on x64 windows) Can raise AttributeError if the provided dict chain isn't
# @param needed_rights SAM rights to access the key correct
#
def create_registry_from_dict_chain(self, dict_chain, both = False, architect = KEY_WOW64_64KEY, needed_rights = KEY_ALL_ACCESS): Keyword arguments:
@param key_value_chain -- The dict chain containing all the
information
@param both -- Whether create the registry in WOW64
node too
@param architect -- The current registry view (
only change it if we want to fill the
WOW6432 registry only [both = False],
on x64 windows)
@param needed_rights -- SAM rights to access the key
"""
if both and architect is KEY_WOW64_64KEY: if both and architect is KEY_WOW64_64KEY:
self.create_registry_from_dict_chain(dict_chain, False, KEY_WOW64_32KEY, needed_rights) self.create_registry_from_dict_chain(
dict_chain, False, KEY_WOW64_32KEY, needed_rights)
if not DecideArchitecture.Is64Windows(): if not DecideArchitecture.Is64Windows():
architect = 0 architect = 0
connected_registy = self.connect_registry() connected_registy = self.connect_registry()
if isinstance(dict_chain, dict) or isinstance(dict_chain, OrderedDict): if (isinstance(dict_chain, dict)
or isinstance(dict_chain, OrderedDict)):
for key, value in dict_chain.iteritems(): for key, value in dict_chain.iteritems():
if isinstance(value, dict) or isinstance(value, OrderedDict): if isinstance(value, dict) or isinstance(value, OrderedDict):
temp_dict = OrderedDict() temp_dict = OrderedDict()
for my_key, my_value in value.iteritems(): for my_key, my_value in value.iteritems():
temp_dict[key+"\\"+my_key] = my_value temp_dict[key+"\\"+my_key] = my_value
self.create_registry_from_dict_chain(temp_dict, False, architect, needed_rights) self.create_registry_from_dict_chain(
temp_dict, False, architect, needed_rights)
else: else:
if isinstance(value, list): if isinstance(value, list):
if len(value)%2 != 0: if len(value)%2 != 0:
#print "Not enough member in the list" #print "Not enough member in the list"
raise AttributeError raise AttributeError
else: else:
new_key = CreateKeyEx(connected_registy, key, 0, needed_rights | architect) new_key = CreateKeyEx(
temp_dict = OrderedDict(value[i:i+2] for i in range(0, len(value), 2)) connected_registy, key, 0,
needed_rights | architect)
temp_dict = OrderedDict(
value[i:i+2] for i in range(
0, len(value), 2))
for my_key, my_value in temp_dict.iteritems(): for my_key, my_value in temp_dict.iteritems():
SetValueEx(new_key,my_key,0, REG_SZ, my_value) if my_key == "default":
my_key = None
SetValueEx(
new_key, my_key, 0, REG_SZ, my_value)
else: else:
new_key = CreateKeyEx(connected_registy, key, 0, needed_rights | architect) new_key = CreateKeyEx(
SetValueEx(new_key,None,0, REG_SZ, value) connected_registy, key, 0,
needed_rights | architect)
SetValueEx(new_key, None, 0, REG_SZ, value)
else: else:
print "The provided attribute wasn't a dictionary chain" print "The provided attribute wasn't a dictionary chain"
raise AttributeError raise AttributeError
##
# Getting a registry value by it's key's name
# Can raise KeyError if key is not found in the registry
# @param key_name The specific key name of which value we are interested in
# @param needed_rights SAM rights to access the key
# @return [key, architect]
# key: The reference to the opened key handler
# architect: 0 for x86
# KEY_WOW64_32KEY or KEY_WOW64_64KEY depending where we found the key on x64
#
def get_key(self, key_name, needed_rights = KEY_ALL_ACCESS): def get_key(self, key_name, needed_rights = KEY_ALL_ACCESS):
"""
Getting a registry value by it's key's name
Can raise KeyError if key is not found in the registry
Keyword arguments:
@param key_name -- The specific key name of which value we
are interested in
@param needed_rights -- SAM rights to access the key
@return -- [key, architect]
key -- Reference to the opened
key handler
architect -- 0 for x86
KEY_WOW64_32KEY or
KEY_WOW64_64KEY
depending where we
found the key on x64
"""
connected_registy = self.connect_registry() connected_registy = self.connect_registry()
architect = 0 architect = 0
if DecideArchitecture.Is64Windows(): if DecideArchitecture.Is64Windows():
architect = KEY_WOW64_64KEY architect = KEY_WOW64_64KEY
try: try:
key = OpenKey(connected_registy, key_name, 0, needed_rights | architect) key = OpenKey(connected_registy, key_name, 0,
needed_rights | architect)
except WindowsError: except WindowsError:
if DecideArchitecture.Is64Windows() and not self.args.different: if DecideArchitecture.Is64Windows() and not self.args.different:
try: try:
architect = KEY_WOW64_32KEY architect = KEY_WOW64_32KEY
key = OpenKey(connected_registy, key_name, 0, needed_rights | architect) key = OpenKey(connected_registy, key_name,
0, needed_rights | architect)
except WindowsError: except WindowsError:
raise KeyError raise KeyError
else: else:
raise KeyError raise KeyError
return [key, architect] return [key, architect]
##
# Getting registry subkeys value by it's key's name and subkeys name def get_key_values(
# Can raise LookupError exception if there are missing data self, key_name, subkey_list, subroutine = False,
# Can raise AttributeError exception if depth attribute is wrong depth = "subkeys"):
# @param key_name The specific key name of which subkey's we are interested in """
# @param subkey_list List containing all the subkeys names which values we are interested in Getting registry subkeys value by it's key's name and subkeys
# @param subroutine Whether suppress exception about not having enough results or not - default False name
# @param depth How depth the search should go for (key, subkeys, all) - default: subkeys Can raise LookupError exception if there are missing data
# @return results{} Dictionary with the subkey_name - value combinations as keys and values Can raise AttributeError exception if depth attribute is wrong
#
def get_key_values(self, key_name, subkey_list, subroutine = False, depth = "subkeys"): Keyword arguments:
@param key_name -- The specific key name of which subkey's
we are interested in
@param subkey_list -- List containing all the subkeys names
which values we are interested in
@param subroutine -- Whether suppress exception about not
having enough results or not
(default: False)
@param depth -- How depth the search should go for
[options: key, subkeys, all]
(default: subkeys)
@return results{} -- Dictionary with the subkey_name - value
combinations as keys and values
"""
if depth == "key": if depth == "key":
int_depth = 0; int_depth = 0;
elif depth == "subkeys": elif depth == "subkeys":
...@@ -174,23 +257,26 @@ class RegistryHandler: ...@@ -174,23 +257,26 @@ class RegistryHandler:
key = key_and_architect[0] key = key_and_architect[0]
architect = key_and_architect[1] architect = key_and_architect[1]
except KeyError: except KeyError:
#print key_name+" doesn't exist in the registry" #print "%s doesn't exist in the registry" % key_name
raise LookupError raise LookupError
#print key_name+" found in the registry" #print "%s found in the registry" % key_name
results = {} results = {}
if int_depth >= 1: if int_depth >= 1:
for i in xrange(0, QueryInfoKey(key)[0]-1): for i in xrange(0, QueryInfoKey(key)[0]-1):
skey_name = EnumKey(key, i) skey_name = EnumKey(key, i)
skey = OpenKey(key, skey_name, 0, KEY_ALL_ACCESS | architect) skey = OpenKey(key, skey_name, 0, KEY_ALL_ACCESS | architect)
if int_depth == 2 and QueryInfoKey(skey)[0] > 0: if int_depth == 2 and QueryInfoKey(skey)[0] > 0:
for key, value in self.get_key_values(skey_name, subkey_list, True, depth).iteritems(): for key, value in self.get_key_values(
skey_name, subkey_list, True, depth).iteritems():
results[key] = value results[key] = value
for subkey_name in subkey_list: for subkey_name in subkey_list:
try: try:
results[subkey_name] = QueryValueEx(skey, subkey_name)[0] results[subkey_name] = QueryValueEx(
skey, subkey_name)[0]
except OSError as e: except OSError as e:
if e.errno == errno.ENOENT: if e.errno == errno.ENOENT:
#print subkey_name+" doesn't exist in this subkey" #print ("%s doesn't exist in this" % subkey_name
# " subkey")
pass pass
skey.Close() skey.Close()
if not results or len(results) != len(subkey_list): if not results or len(results) != len(subkey_list):
...@@ -201,34 +287,46 @@ class RegistryHandler: ...@@ -201,34 +287,46 @@ class RegistryHandler:
pass pass
key.Close() key.Close()
if len(results) != len(subkey_list): if len(results) != len(subkey_list):
#print We are missing important variables #print "We are missing important variables"
raise LookupError raise LookupError
return results return results
## def get_key_value(
# This is a wrapper for the get_key_values to be easier to use for single subkeys self, key_name, subkey_name, subroutine = None, depth = None):
# Getting registry subkey value by it's key's name and subkey name """
# @param key_name The specific key name of which subkey's we are interested in This is a wrapper for the get_key_values to be easier to use
# @param subkey_name The specific subkey name which value we are interested in for single subkeys.
# @param subroutine can be found at: get_key_values Getting registry subkey value by it's key's name and subkey
# @param depth can be found at: get_key_values name
# @return value Value of the specific subkey
# Keyword arguments:
def get_key_value(self, key_name, subkey_name, subroutine = None, depth = None): @param key_name -- The specific key name of which subkey's
we are interested in
@param subkey_name -- The specific subkey name which value we
are interested in
@param subroutine -- can be found at: get_key_values
@param depth -- can be found at: get_key_values
@return value -- Value of the specific subkey
"""
try: try:
if subroutine is None: if subroutine is None:
return self.get_key_values(key_name, [subkey_name])[subkey_name] return self.get_key_values(key_name,
[subkey_name])[subkey_name]
elif depth is None: elif depth is None:
return self.get_key_values(key_name, [subkey_name], subroutine)[subkey_name] return self.get_key_values(key_name, [subkey_name],
subroutine)[subkey_name]
else: else:
return self.get_key_values(key_name, [subkey_name], subroutine, depth)[subkey_name] return self.get_key_values(key_name, [subkey_name],
subroutine, depth)[subkey_name]
except: except:
raise raise
##
# Helper class to get the true ProgramFiles directory.
# This class doesn't depend on Phyton or Windows architecture.
#
class DecideArchitecture: class DecideArchitecture:
"""
Helper class to get the true ProgramFiles directory.
This class doesn't depend on Phyton or Windows architecture.
"""
@staticmethod @staticmethod
def Is64Windows(): def Is64Windows():
return 'PROGRAMFILES(X86)' in os.environ return 'PROGRAMFILES(X86)' in os.environ
...@@ -247,22 +345,31 @@ class DecideArchitecture: ...@@ -247,22 +345,31 @@ class DecideArchitecture:
def main(): def main():
try: try:
args = pars_arguments() args = parse_arguments()
nx_install_location = None nx_install_location = None
while nx_install_location is None: while nx_install_location is None:
print "Checking whether NX Client for Windows is installed" print "Checking whether NX Client for Windows is installed"
handler = RegistryHandler() handler = RegistryHandler()
try: try:
nx_install_location = handler.get_key_value("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\nxclient_is1", "InstallLocation", "key") nx_install_location = handler.get_key_value(
print "NX Client for Windows is found at '"+nx_install_location+"'" "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\"+
process = subprocess.Popen("%s\\nxclient.exe" % nx_install_location) "Uninstall\\nxclient_is1",
"InstallLocation", "key")
print ("NX Client for Windows is found at "
"'%s'" % nx_install_location)
process = subprocess.Popen(
"%s\\nxclient.exe" % nx_install_location)
time.sleep(2) time.sleep(2)
process.terminate() process.terminate()
except: except:
print "NX Client for Windows isn't installed on the system." print "NX Client for Windows isn't installed on the system."
print "\tCommencing the install" print "\tCommencing the install"
subprocess.Popen(os.path.dirname(os.path.realpath(__file__))+"\\nxclient-3.5.0-9.exe").wait() subprocess.Popen(os.path.dirname(
os.path.realpath(__file__))+
"\\nxclient-3.5.0-9.exe").wait()
except: except:
pass pass
if __name__ == "__main__": if __name__ == "__main__":
main() main()
\ No newline at end of file
#!/usr/bin/python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
## """
# Generating NoMachine NX scrambled key according to https://www.nomachine.com/AR01C00125 Generating NoMachine NX scrambled key according to
## https://www.nomachine.com/AR01C00125
"""
import sys import sys
import random import random
import re import re
from xml.sax.saxutils import escape from xml.sax.saxutils import escape
##
# NXKeyGen class
# Creates NoMachine NX scrambled keys
#
class NXKeyGen: class NXKeyGen:
"""
NXKeyGen class
Creates NoMachine NX scrambled keys
"""
numValidCharList = 85 numValidCharList = 85
dummyString = "{{{{" dummyString = "{{{{"
##
# Initialize the class
# @param password Password that will be scrambled
#
def __init__(self, password): def __init__(self, password):
"""
Initialize the class
Keyword arguments:
@param password -- Password that will be scrambled
"""
self.password = password self.password = password
##
# Encrypt (scramble) the given password
# @return scrambleString Scrambled version of the original password
#
def getEncrypted(self): def getEncrypted(self):
"""
Encrypt (scramble) the given password
Keyword arguments:
@return scrambleString -- Scrambled version of the original
password
"""
return self.scrambleString(self.password) return self.scrambleString(self.password)
##
# Valid character list
# @return validcharlist List of the valid characters
#
def getvalidCharList(self, pos): def getvalidCharList(self, pos):
"""
Valid character list
Keyword arguments:
@return validcharlist -- List of the valid characters
"""
validcharlist = [ validcharlist = [
"!", "#", "$", "%", "&", "(", ")", "*", "+", "-", "!", "#", "$", "%", "&", "(", ")", "*", "+", "-",
".", "0", "1", "2", "3", "4", "5", "6", "7", "8", ".", "0", "1", "2", "3", "4", "5", "6", "7", "8",
...@@ -47,11 +57,13 @@ class NXKeyGen: ...@@ -47,11 +57,13 @@ class NXKeyGen:
] ]
return validcharlist[pos] return validcharlist[pos]
##
# Password encoder
# @return sPass Encoded password
#
def encodePassword(self, p): def encodePassword(self, p):
"""
Password encoder
Keyword arguments:
@return sPass -- Encoded password
"""
sPass = ":" sPass = ":"
sTmp = "" sTmp = ""
if not p: if not p:
...@@ -64,12 +76,14 @@ class NXKeyGen: ...@@ -64,12 +76,14 @@ class NXKeyGen:
sTmp = "" sTmp = ""
return sPass return sPass
##
# Character position finder
# @param c Character that needs to be matched if valid
# @return i Place where the character is in the valid list
#
def findCharInList(self, c): def findCharInList(self, c):
"""
Character position finder
Keyword arguments:
@param c -- Character that needs to be matched if valid
@return i -- Place where the character is in the valid list
"""
i = -1 i = -1
for j in range(self.numValidCharList): for j in range(self.numValidCharList):
randchar = self.getvalidCharList(j); randchar = self.getvalidCharList(j);
...@@ -78,19 +92,23 @@ class NXKeyGen: ...@@ -78,19 +92,23 @@ class NXKeyGen:
return i return i
return i return i
##
# Random valid character getter
# @return char Valid character placed 0-60 in the valid list
#
def getRandomValidCharFromList(self): def getRandomValidCharFromList(self):
"""
Random valid character getter
Keyword arguments:
@return char -- Valid character placed 0-60 in the valid list
"""
return self.getvalidCharList(random.randint(0,60)) return self.getvalidCharList(random.randint(0,60))
##
# Password scrambler
# @param s Password that needs to be scrambled
# @return sRet NoMachine NX scrambled password
#
def scrambleString(self, s): def scrambleString(self, s):
"""
Password scrambler
Keyword arguments:
@param s -- Password that needs to be scrambled
@return sRet -- NoMachine NX scrambled password
"""
sRet = "" sRet = ""
if not s: if not s:
return s return s
...@@ -118,10 +136,10 @@ class NXKeyGen: ...@@ -118,10 +136,10 @@ class NXKeyGen:
sRet = sRet + c2 sRet = sRet + c2
return escape(sRet) return escape(sRet)
##
# Replace a character at a special position
#
def substr_replace(self,in_str,ch,pos,qt): def substr_replace(self,in_str,ch,pos,qt):
"""
Replace a character at a special position
"""
clist = list(in_str) clist = list(in_str)
count = 0; count = 0;
tmp_str = ''; tmp_str = '';
...@@ -134,7 +152,6 @@ class NXKeyGen: ...@@ -134,7 +152,6 @@ class NXKeyGen:
return tmp_str return tmp_str
if __name__ == "__main__": if __name__ == "__main__":
NXPass = NXKeyGen(sys.argv[1]) NXPass = NXKeyGen(sys.argv[1])
print NXPass.password print NXPass.password
......
#!/usr/bin/python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
## """
# Pywin32 installer for CIRCLE client application Pywin32 installer for CIRCLE client application
## """
import os, sys, subprocess import os
import sys
import subprocess
from nx_client_installer import DecideArchitecture from nx_client_installer import DecideArchitecture
##
# Main program
# Install Pywin32 to the computer
#
def main(): def main():
"""
Main program
Job:
Install Pywin32 to the computer
"""
if sys.hexversion < 0x02060000: if sys.hexversion < 0x02060000:
print "Not a 2.6+ version Python is running, commencing update" print "Not a 2.6+ version Python is running, commencing update"
subprocess.Popen(os.path.dirname(os.path.realpath(__file__))+"\\no_root_install.bat") subprocess.Popen(
"%s\\no_root_install.bat" % os.path.dirname(
os.path.realpath(__file__)))
sys.exit(1) sys.exit(1)
else: else:
pywin32_version = str(219) pywin32_version = str(219)
if sys.hexversion < 0x02070000: if sys.hexversion < 0x02070000:
if DecideArchitecture.Is64Windows(): if DecideArchitecture.Is64Windows():
subprocess.Popen(os.path.dirname(os.path.realpath(__file__))+"\\x64\\pywin32-"+pywin32_version+".win-amd64-py2.6.exe").wait() subprocess.Popen(
"%s\\x64\\pywin32-%s.win-amd64-py2.6.exe" % (
os.path.dirname(os.path.realpath(__file__)),
pywin32_version)).wait()
else: else:
subprocess.Popen(os.path.dirname(os.path.realpath(__file__))+"\\x86\\pywin32-"+pywin32_version+".win32-py2.6.exe").wait() subprocess.Popen(
"%s\\x86\\pywin32-%s.win32-py2.6.exe" % (
os.path.dirname(os.path.realpath(__file__)),
pywin32_version)).wait()
elif sys.hexversion < 0x02080000: elif sys.hexversion < 0x02080000:
if DecideArchitecture.Is64Windows(): if DecideArchitecture.Is64Windows():
subprocess.Popen(os.path.dirname(os.path.realpath(__file__))+"\\x64\\pywin32-"+pywin32_version+".win-amd64-py2.7.exe").wait() subprocess.Popen(
"%s\\x64\\pywin32-%s.win-amd64-py2.7.exe" % (
os.path.dirname(os.path.realpath(__file__)),
pywin32_version)).wait()
else: else:
subprocess.Popen(os.path.dirname(os.path.realpath(__file__))+"\\x86\\pywin32-"+pywin32_version+".win32-py2.7.exe").wait() subprocess.Popen(
"%s\\x86\\pywin32-%s.win32-py2.7.exe" % (
os.path.dirname(os.path.realpath(__file__)),
pywin32_version)).wait()
else: else:
print "Unsupported Python version is found!" print "Unsupported Python version is found!"
if __name__ == "__main__": if __name__ == "__main__":
main() main()
\ No newline at end of file
#!/usr/bin/python #!/usr/bin/env python
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
## """
# Windows icon installer for CIRCLE client application Windows icon installer for CIRCLE client application
## """
import os, sys, argparse, subprocess import os
if sys.hexversion > 0x02070000: import argparse
from collections import * import subprocess
else:
from OrderedDict import *
import pythoncom import pythoncom
from win32com.shell import shell, shellcon from win32com.shell import shell, shellcon
from nx_client_installer import DecideArchitecture, RegistryHandler, Struct from nx_client_installer import DecideArchitecture, RegistryHandler, Struct
try:
from collections import *
except ImporError:
from OrderedDict import *
##
# Argument parser, based on argparse module
# @return args def parse_arguments():
# """
def pars_arguments(): Argument parser, based on argparse module
parser = argparse.ArgumentParser();
parser.add_argument("-d", "--driver", help="Select webdriver. Aside from Firefox, you have to install first the proper driver.", \ Keyword arguments:
type=str, choices=['firefox', 'chrome', 'iexplore', 'opera'], default="firefox", required=False) @return args -- arguments given by console
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"-d", "--driver",
help="Select webdriver. Aside from Firefox, you have to install "+
"first the proper driver.", type=str, default="firefox",
required=False, choices=['firefox', 'chrome',
'iexplore', 'opera'])
if DecideArchitecture.Is64Windows(): if DecideArchitecture.Is64Windows():
local_default = DecideArchitecture.GetProgramFiles64()+"\\CIRCLE\\" local_default = DecideArchitecture.GetProgramFiles64()+"\\CIRCLE\\"
else: else:
local_default = DecideArchitecture.GetProgramFiles32()+"\\CIRCLE\\" local_default = DecideArchitecture.GetProgramFiles32()+"\\CIRCLE\\"
if not os.path.exists(local_default[:-1]) and os.path.exists(os.environ['APPDATA']+"\\CIRCLE"): if (not os.path.exists(local_default[:-1])
and os.path.exists(os.environ['APPDATA']+"\\CIRCLE")):
local_default = os.environ['APPDATA']+"\\CIRCLE\\" local_default = os.environ['APPDATA']+"\\CIRCLE\\"
parser.add_argument("-l", "--location", help="Location of the client files in the system", default=local_default, required=False) parser.add_argument(
parser.add_argument("-r", "--remove", help="Remove installed files instead of creating them", action="store_true", required=False) "-l", "--location", help="Location of the client files in the system",
parser.add_argument("-u", "--url", help="Whether we installed and we want to use selenium or not", action="store_true", required=False) default=local_default, required=False)
parser.add_argument("-t", "--target", help="If this is an URL icon, where should it point", default="https://pc3.szgt.uni-miskolc.hu/", required=False) parser.add_argument(
args = parser.parse_args(); "-r", "--remove",
help="Remove installed files instead of creating them",
action="store_true", required=False)
parser.add_argument(
"-u", "--url",
help="Whether we installed and we want to use selenium or not",
action="store_true", required=False)
parser.add_argument(
"-t", "--target",
help="If this is an URL icon, where should it point",
default="https://pc3.szgt.uni-miskolc.hu/", required=False)
args = parser.parse_args()
return args return args
##
# Custom protocol register based on RegistryHandler module
# Can raise AttributeError on wrongly provided dictionary chain
# @param dict_chain OrderedDictionary chain of the registry tree
#
def custom_protocol_register(custom_protocol): def custom_protocol_register(custom_protocol):
"""
Custom protocol register based on RegistryHandler module
Can raise AttributeError on wrongly provided dictionary chain
Keyword arguments:
@param dict_chain -- OrderedDictionary chain of the registry tree
"""
if not isinstance(custom_protocol, OrderedDict): if not isinstance(custom_protocol, OrderedDict):
raise AttributeError raise AttributeError
print "\t"+custom_protocol.iterkeys().next() print "\t"+custom_protocol.iterkeys().next()
...@@ -53,14 +77,18 @@ def custom_protocol_register(custom_protocol): ...@@ -53,14 +77,18 @@ def custom_protocol_register(custom_protocol):
except: except:
raise raise
##
# Main program
# read the parameters
# create a proper icon with the proper driver
# call the nx_client_installer
def main(): def main():
#try: """
args = pars_arguments() Main program
Jobs:
read the parameters
create a proper icon with the proper driver (or delete)
call the nx_client_installer
"""
try:
args = parse_arguments()
shortcut = pythoncom.CoCreateInstance ( shortcut = pythoncom.CoCreateInstance (
shell.CLSID_ShellLink, shell.CLSID_ShellLink,
None, None,
...@@ -75,7 +103,9 @@ def main(): ...@@ -75,7 +103,9 @@ def main():
if os.path.isfile("%s%s" % (location, ".url")): if os.path.isfile("%s%s" % (location, ".url")):
os.remove("%s%s" % (location, ".url")) os.remove("%s%s" % (location, ".url"))
else: else:
subprocess.call("python "+os.path.dirname(os.path.realpath(__file__))+"\\nx_client_installer.py") subprocess.call(
"python %s\\nx_client_installer.py" % os.path.dirname(
os.path.realpath(__file__)))
if args.url: if args.url:
location = os.path.join(desktop_path, "Cloud GUI.url") location = os.path.join(desktop_path, "Cloud GUI.url")
shortcut = file(location, 'w') shortcut = file(location, 'w')
...@@ -92,27 +122,44 @@ def main(): ...@@ -92,27 +122,44 @@ def main():
shortcut.SetArguments("-d opera") shortcut.SetArguments("-d opera")
shortcut.SetDescription ("Tool to use CIRCLE Cloud") shortcut.SetDescription ("Tool to use CIRCLE Cloud")
shortcut.SetIconLocation (args.location+"cloud.ico", 0) shortcut.SetIconLocation (args.location+"cloud.ico", 0)
desktop_path = shell.SHGetFolderPath (0, shellcon.CSIDL_DESKTOP, 0, 0) desktop_path = shell.SHGetFolderPath(
persist_file = shortcut.QueryInterface (pythoncom.IID_IPersistFile) 0, shellcon.CSIDL_DESKTOP, 0, 0)
persist_file.Save (os.path.join (desktop_path, "Cloud GUI.lnk"), 0) persist_file = shortcut.QueryInterface(
pythoncom.IID_IPersistFile)
persist_file.Save(
os.path.join(desktop_path, "Cloud GUI.lnk"), 0)
print "Icon successfully created on desktop" print "Icon successfully created on desktop"
print "Creating custom URL protocol handlers" print "Creating custom URL protocol handlers"
try: try:
custom_ssh = OrderedDict([('ssh', "URL:CIRCLE-SSH Protocol"), ('ssh\\URL Protocol', ""),\ custom_ssh = OrderedDict(
('ssh\\DefaultIcon', args.location+"cloud.ico"),\ [('ssh', ["default", "URL:ssh Protocol", "URL Protocol", ""]),
('ssh\\shell', {'open': {'command': "\"python.exe\" \""+args.location+"cloud.py\" \"%1\""}})]) ('ssh\\URL Protocol', ""),
('ssh\\DefaultIcon', args.location+"cloud.ico"),
('ssh\\shell', {'open': {
'command': "\"python.exe\" \"%s" % args.location+
"cloud.py\" \"%1\""}})])
custom_protocol_register(custom_ssh) custom_protocol_register(custom_ssh)
custom_rdp = OrderedDict([('rdp', "URL:CIRCLE-RDP Protocol"), ('rdp\\URL Protocol', ""),\ custom_rdp = OrderedDict(
('rdp\\DefaultIcon', args.location+"cloud.ico"),\ [('rdp', ["default", "URL:rdp Protocol", "URL Protocol", ""]),
('rdp\\shell', {'open': {'command': "\"python.exe\" \""+args.location+"cloud.py\" \"%1\""}})]) ('rdp\\URL Protocol', ""),
('rdp\\DefaultIcon', args.location+"cloud.ico"),
('rdp\\shell', {'open': {
'command': "\"python.exe\" \"%s" % args.location+
"cloud.py\" \"%1\""}})])
custom_protocol_register(custom_rdp) custom_protocol_register(custom_rdp)
custom_nx = OrderedDict([('nx', "URL:CIRCLE-NX Protocol"), ('nx\\URL Protocol', ""),\ custom_nx = OrderedDict(
('nx\\DefaultIcon', args.location+"cloud.ico"),\ [('nx', ["default", "URL:nx Protocol", "URL Protocol", ""]),
('nx\\shell', {'open': {'command': "\"python.exe\" \""+args.location+"cloud.py\" \"%1\""}})]) ('nx\\URL Protocol', ""),
('nx\\DefaultIcon', args.location+"cloud.ico"),
('nx\\shell', {'open': {
'command': "\"python.exe\" \"%s" % args.location+
"cloud.py\" \"%1\""}})])
custom_protocol_register(custom_nx) custom_protocol_register(custom_nx)
except: except:
print "Error! URL Protocol handler installation aborted!" print "Error! URL Protocol handler installation aborted!"
#except: except:
# print "Unknown error occurred! Please contact the developers!" print "Unknown error occurred! Please contact the developers!"
if __name__ == "__main__": if __name__ == "__main__":
main() main()
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment