def CreateGIT(): return pythoncom.CoCreateInstance(pythoncom.CLSID_StdGlobalInterfaceTable, None, pythoncom.CLSCTX_INPROC, pythoncom.IID_IGlobalInterfaceTable)
def __init__(self, lnkname): self.shortcut = pythoncom.CoCreateInstance( shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) self.shortcut.QueryInterface(pythoncom.IID_IPersistFile).Load(lnkname)
def __init__( self ): self._base = pythoncom.CoCreateInstance( shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink )
def __init__( self ): self._base = pythoncom.CoCreateInstance( shell.CLSID_InternetShortcut, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IUniformResourceLocator )
def create_win_shortcut(name, target, arguments="", startin="", icon="", description="", menugroup="OpenAlea"): """ Create windows shortcut :param name: link name :param target: executable file path (ex : Pythonroot + pythonw.exe) :param arguments: (ex python module path) :param startin: execution path (same as python module path) :param icon: icon path (ex Pythonroot + '\\py.ico') :param description: ... :param menugroup: Menu group entry :example: >>> TempDir = os.environ["TEMP"] >>> Name = "New Link" >>> Target = Pythonroot + "pythonw.exe " >>> Arguments = TempDir + "\\test.py" >>> StartIn = TempDir >>> Icon = Pythonroot + "\\py.ico" >>> Description = "New Link" >>> create_win_shortcut(Path,Target,Arguments,StartIn,Icon,Description) """ (Name, Target, Arguments, StartIn, Icon, Description, MenuGroup) = \ (name, target, arguments, startin, icon, description, menugroup) if ((not 'win32' in sys.platform)): return try: from openalea.deploy import get_base_dir win32dir = get_base_dir('pywin32') os.environ['PATH'] += ';' + os.path.join(win32dir, 'pywin32_system32') from win32com.shell import shell, shellcon except Exception as e: print(e) print("ERROR : pywin32 is not installed. Cannot create shortcut.") return import win32api import pythoncom MenuRoot = shell.SHGetFolderPath(0, shellcon.CSIDL_COMMON_PROGRAMS, 0, 0) MenuRoot = MenuRoot + "\\" + MenuGroup + "\\" if (not os.path.isdir(MenuRoot)): os.mkdir(MenuRoot) Path = MenuRoot + "\\%s.lnk" % (Name) Icon = (Icon, 0) # Get the shell interface. sh = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, \ pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) # Set the data sh.SetPath(Target) sh.SetDescription(Description) sh.SetArguments(Arguments) sh.SetWorkingDirectory(StartIn) if (Icon[0]): sh.SetIconLocation(Icon[0], Icon[1]) # Save the link itself. sh.QueryInterface(pythoncom.IID_IPersistFile).Save(Path, 0)
import pythoncom, time, win32api from win32com.taskscheduler import taskscheduler task_name = 'test_addtask_2.job' ts = pythoncom.CoCreateInstance(taskscheduler.CLSID_CTaskScheduler, None, pythoncom.CLSCTX_INPROC_SERVER, taskscheduler.IID_ITaskScheduler) tasks = ts.Enum() for task in tasks: print task if task_name in tasks: print 'Deleting existing task ' + task_name ts.Delete(task_name) t = ts.NewWorkItem(task_name) t.SetComment('Test a task running as local system acct') t.SetApplicationName('c:\\python23\\python.exe') t.SetPriority(taskscheduler.REALTIME_PRIORITY_CLASS) t.SetParameters('test_localsystem.py') t.SetWorkingDirectory('c:\\python23') t.SetCreator('test_addtask_2.py') t.SetMaxRunTime(20000) #milliseconds t.SetFlags(taskscheduler.TASK_FLAG_DELETE_WHEN_DONE) t.SetAccountInformation( '', None) ## empty string for account name means to use local system ## None is only valid for local system acct or if task flags contain TASK_FLAG_RUN_ONLY_IF_LOGGED_ON run_time = time.localtime(time.time() + 60) tr_ind, tr = t.CreateTrigger() tt = tr.GetTrigger() tt.Flags = 0 ## flags for a new trigger default to TASK_TRIGGER_FLAG_DISABLED (4), make sure to clear them if not using any
def _windows_file_process(self, src_dst_mapping, to_remove): """Windows specific file processing asking for admin permissions. It is required to have administration permissions to modify plugin files in TVPaint installation folder. Method requires `pywin32` python module. Args: src_dst_mapping (list, tuple, set): Mapping of source file to destination. Both must be full path. Each item must be iterable of size 2 `(C:/src/file.dll, C:/dst/file.dll)`. to_remove (list): Fullpath to files that should be removed. """ import pythoncom from win32comext.shell import shell # Create temp folder where plugin files are temporary copied # - reason is that copy to TVPaint requires administartion permissions # but admin may not have access to source folder tmp_dir = os.path.normpath(tempfile.mkdtemp(prefix="tvpaint_copy_")) # Copy source to temp folder and create new mapping dst_folders = collections.defaultdict(list) new_src_dst_mapping = [] for old_src, dst in src_dst_mapping: new_src = os.path.join(tmp_dir, os.path.split(old_src)[1]) shutil.copy(old_src, new_src) new_src_dst_mapping.append((new_src, dst)) for src, dst in new_src_dst_mapping: src = os.path.normpath(src) dst = os.path.normpath(dst) dst_filename = os.path.basename(dst) dst_folder_path = os.path.dirname(dst) dst_folders[dst_folder_path].append((dst_filename, src)) # create an instance of IFileOperation fo = pythoncom.CoCreateInstance(shell.CLSID_FileOperation, None, pythoncom.CLSCTX_ALL, shell.IID_IFileOperation) # Add delete command to file operation object for filepath in to_remove: item = shell.SHCreateItemFromParsingName(filepath, None, shell.IID_IShellItem) fo.DeleteItem(item) # here you can use SetOperationFlags, progress Sinks, etc. for folder_path, items in dst_folders.items(): # create an instance of IShellItem for the target folder folder_item = shell.SHCreateItemFromParsingName( folder_path, None, shell.IID_IShellItem) for _dst_filename, source_file_path in items: # create an instance of IShellItem for the source item copy_item = shell.SHCreateItemFromParsingName( source_file_path, None, shell.IID_IShellItem) # queue the copy operation fo.CopyItem(copy_item, folder_item, _dst_filename, None) # commit fo.PerformOperations() # Remove temp folder shutil.rmtree(tmp_dir)
import os, sys import pythoncom from win32com.shell import shell, shellcon shortcut = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) shortcut.SetPath(sys.executable) shortcut.SetDescription("Python %s" % sys.version) shortcut.SetIconLocation(sys.executable, 0) desktop_path = shell.SHGetFolderPath(0, shellcon.CSIDL_DESKTOP, 0, 0) persist_file = shortcut.QueryInterface(pythoncom.IID_IPersistFile) persist_file.Save(os.path.join(desktop_path, "python.lnk"), 0)
def main(): global admin_user, admin_pass, smc_url, student_user, server_name, home_root canvas_access_token = "" print_app_header() # Ask for admnin user/pass and website tmp = raw_input( term.translateColorCodes( "}}ynEnter URL for SMC Server }}cn[enter for default " + smc_url + "]:}}dn ")) tmp = tmp.strip() if tmp == "": tmp = smc_url smc_url = tmp tmp = raw_input( term.translateColorCodes( "}}ynPlease enter the ADMIN user name }}cn[enter for default " + admin_user + "]:}}dn ")) tmp = tmp.strip() if tmp == "": tmp = admin_user admin_user = tmp p("}}ynPlease enter ADMIN password }}cn[characters will not show]:}}dn", False) tmp = getpass.getpass(" ") if tmp == "": p("}}rbA password is required.}}dn") return False admin_pass = tmp tmp = "" while tmp.strip() == "": tmp = raw_input( term.translateColorCodes( "}}ynPlease enter the username for the student:}}dn ")) student_user = tmp.strip() txt = """ }}mn====================================================================== }}mn| }}ybCredential Computer }}mn| }}mn| }}ynSMC URL: }}cn<smc_url>}}mn| }}mn| }}ynAdmin User: }}cn<admin_user>}}mn| }}mn| }}ynAdmin Password: }}cn<admin_pass>}}mn| }}mn| }}ynStudent Username: }}cn<student_user>}}mn| }}mn======================================================================}}dn """ txt = txt.replace("<smc_url>", smc_url.ljust(47)) txt = txt.replace("<admin_user>", admin_user.ljust(47)) txt = txt.replace("<admin_pass>", "******".ljust(47)) txt = txt.replace("<student_user>", student_user.ljust(47)) p(txt) tmp = raw_input(term.translateColorCodes("}}ybPress Y to continue: }}dn")) tmp = tmp.strip().lower() if tmp == "y": api_url = smc_url if not api_url.endswith("/"): api_url += "/" key = base64.b64encode(admin_user + ':' + admin_pass) headers = {'Authorization': 'Basic ' + key} # password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm() # password_manager.add_password(None, api_url, admin_user, admin_pass) # handler = urllib2.HTTPBasicAuthHandler(password_manager) # opener = urllib2.build_opener(handler) # ssl_context = ssl._create_unverified_context() p("\n}}gnGetting Canvas Auth Key...}}dn\n") url = api_url + "lms/credential_student.json/" + student_user request = urllib2.Request(url, None, headers) json_str = "" try: response = urllib2.urlopen(request) json_str = response.read() except urllib2.HTTPError as ex: if ex.code == 403: p("}}rbInvalid ADMIN Password!}}dn") return False else: p("}}rbHTTP Error!}}dn") p("}}mn" + str(ex) + "}}dn") return False except Exception as ex: p("}}rbUnable to communicate with SMC tool!}}dn") p("}}mn" + str(ex) + "}}dn") return False canvas_response = None try: canvas_response = json.loads(json_str) except Exception as ex: p("}}rbUnable to interpret response from SMC}}dn") p("}}mn" + str(ex) + "}}dn") return False if "msg" in canvas_response: if canvas_response["msg"] == "Invalid User!": p("\n}}rbInvalid User!}}dn") p("}}mnUser doesn't exit in system, please import this student in the SMC first!}}dn" ) return False if "Unable to find user in canvas:" in canvas_response["msg"]: p("\n}}rbInvalid User!}}dn") p("}}mnUser exists in SMC but not in Canvas, please rerun import this student in the SMC to correct the issue!}}dn" ) return False canvas_access_token = str(canvas_response["key"]) hash = str(canvas_response["hash"]) student_full_name = str(canvas_response["full_name"]) # print("Response: " + canvas_access_token + " ---- " + hash) pw = win_util.decrypt(hash, canvas_access_token) p("}}gnCreating local windows account...") win_util.create_local_student_account(student_user, student_full_name, pw) # Store the access token in the registry where the LMS app can pick it up p("}}gnSaving canvas credentials for student...") key = win_util.create_reg_key(r"HKLM\Software\OPE\OPELMS", student_user) key = win_util.create_reg_key(r"HKLM\Software\OPE\OPELMS\student") key.canvas_access_token = canvas_access_token print("Canvas access granted for student.") print("Setting up LMS App...") # Create shortcut lnk_path = "c:\\users\\public\\desktop\\OPE LMS.lnk" exe_path = "c:\\programdata\\ope\\ope_laptop_binaries\\lms\\ope_lms.exe" ico_path = "c:\\programdata\\ope\\ope_laptop_binaries\\lms\\logo_icon.ico" shortcut = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) shortcut.SetPath(exe_path) shortcut.SetDescription( "Offline LMS app for Open Prison Education project") shortcut.SetIconLocation(ico_path, 0) persist_file = shortcut.QueryInterface(pythoncom.IID_IPersistFile) persist_file.Save(lnk_path, 0) return True # print("Installing Admin Services...") # print("Installing offline LMS app...") # print ("Applying security rules...") p("\tDownloading firewall rules...") url = api_url + "lms/get_firewall_list.json" p("\n\nURL: " + url) request = urllib2.Request(url, None, headers) json_str = "" try: response = urllib2.urlopen(request) json_str = response.read() except urllib2.HTTPError as ex: if ex.code == 403: p("}}rbInvalid ADMIN Password!}}dn") return False else: p("}}rbHTTP Error!}}dn") p("}}mn" + str(ex) + "}}dn") return False except Exception as ex: p("}}rbUnable to communicate with SMC tool!}}dn") p("}}mn" + str(ex) + "}}dn") return False firewall_response = None try: firewall_response = json.loads(json_str) except Exception as ex: p("}}rbUnable to interpret firewall response from SMC}}dn") p("}}mn" + str(ex) + "}}dn") return False for rule in firewall_response: p("}}ybApplying Firewall Rule: " + str(rule["rule_name"])) fw_cmd = "netsh advfirewall firewall delete rule \"" + str( rule["rule_name"]) + "\"" p("\t\t}}rn" + fw_cmd) os.system(fw_cmd) fw_cmd = "netsh advfirewall firewall add rule name=\"" + str( rule["rule_name"]) + "\"" if rule["protocol"] != "": fw_cmd += " protocol=" + rule["protocol"] if rule["rmtusrgrp"] != "": fw_cmd += " rmtusrgrp=" + rule["rmtusrgrp"] if rule["rmtcomputergrp"] != "": fw_cmd += " rmtcomputergrp=" + rule["rmtcomputergrp"] if rule["description"] != "": fw_cmd += " description=\"" + rule["description"].replace( "\"", "") + "\"" if rule["service"] != "": fw_cmd += " service=\"" + rule["service"] + "\"" if rule["fw_action"] != "": fw_cmd += " action=" + rule["fw_action"] if rule["fw_security"] != "": fw_cmd += " security=" + rule["fw_security"] if rule["program"] != "": fw_cmd += " program=\"" + rule["program"].replace("\"", "") + "\"" if rule["profile"] != "": fw_cmd += " profile=" + rule["profile"] if rule["direction"] != "": fw_cmd += " direction=" + rule["direction"] if rule["remoteip"] != "": fw_cmd += " remoteip=" + rule["remoteip"] if rule["fw_enable"] != "": fw_cmd += " enable=" + rule["fw_enable"] if rule["remoteport"] != "": fw_cmd += " remoteport=" + rule["remoteport"] if rule["localport"] != "": fw_cmd += " localport=" + rule["localport"] if rule["localip"] != "": fw_cmd += " localip=" + rule["localip"] if rule["edge"] != "": fw_cmd += " edge=" + rule["edge"] if rule["interfacetype"] != "": fw_cmd += " interfacetype=" + rule["interfacetype"] p("\t\t}}rb" + fw_cmd) os.system(fw_cmd) # Turn the firewall on # netsh advfirewall set allprofiles state on # Default Settings # netsh advfirewall reset # Set logging # netsh advfirewall set currentprofile logging filename "C:\temp\pfirewall.log" # Block ping # netsh advfirewall firewall add rule name="All ICMP V4" dir=in action=block protocol=icmpv4 # Allow ping # netsh advfirewall firewall add rule name="All ICMP V4" dir=in action=allow protocol=icmpv4 # Allow or deny port # netsh advfirewall firewall add rule name="Open SQL Server Port 1433" dir=in action=allow protocol=TCP localport=1433 # netsh advfirewall firewall delete rule name="Open SQL Server Port 1433" protocol=tcp localport=1433 # Enable program # netsh advfirewall firewall add rule name="Allow Messenger" dir=in action=allow program="C:\programfiles\messenger\msnmsgr.exe" # Enable remote manatement # netsh advfirewall firewall set rule group="remote administration" new enable=yes # Enable remote desktop # netsh advfirewall firewall set rule group="remote desktop" new enable=Yes # Export settings # netsh advfirewall export "C:\temp\WFconfiguration.wfw" # Get repo over test cert # git -c http.sslVerify=false clone https://example.com/path/to/git # TODO # Download current policy zip file # unzip # import # /mergedpolicy -- to combine domain/local cmd = "cd policy_dir; secedit /export /cfg gp.ini /log export.log" # netsh -- import firewall rules # download netsh import # run netsh import command print_checklist_warning() a = raw_input( term.translateColorCodes("}}ybPress enter when done}}dn")) return True
def createStartMenuShortcut(self, description, executable, workingDir, startMenuSubdir="", iconLocation=None, createDesktopShortcut=False, putInStartup=False): '''Create a shortcut in the Start menu @type description: string @param description: The description of the shortcut. @type executable: string @param executable: The path in which the executable of the application is located. @type workingDir: string @param workingDir: The working folder of the application @type startMenuSubdir: string @param startMenuSubdir: The name of the folder in the Start menu. @type iconLocation: string @param iconLocation: The folder in which the application icon is located. @type createDesktopShortcut: boolean @param createDesktopShortcut: Indicates if a shortcut must be put on the desktop. @type putInStartup: boolean @param putInStartup: Indicates if an application must be started with Windows. ''' import pythoncom from win32com.shell import shell import os # Add shortcut to startmenu startmenu = self.getStartMenuProgramsPath() if not j.sal.fs.exists("%s\\%s" % (startmenu, startMenuSubdir)): j.sal.fs.createDir("%s\\%s" % (startmenu, startMenuSubdir)) shortcut_startmenu = pythoncom.CoCreateInstance( shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) shortcut_startmenu.SetPath(executable) shortcut_startmenu.SetDescription(description) if not iconLocation is None: shortcut_startmenu.SetIconLocation(iconLocation, 0) shortcut_startmenu.SetWorkingDirectory(workingDir) shortcut_startmenu.QueryInterface(pythoncom.IID_IPersistFile).Save( "%s\\%s\\%s.lnk" % (startmenu, startMenuSubdir, description), 0) if putInStartup: startupfolder = self.getStartupPath() if not j.sal.fs.exists(startupfolder): j.sal.fs.createDir(startupfolder) shortcut_startup = pythoncom.CoCreateInstance( shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) shortcut_startup.SetPath(executable) shortcut_startup.SetDescription(description) if not iconLocation is None: shortcut_startup.SetIconLocation(iconLocation, 0) shortcut_startup.SetWorkingDirectory(workingDir) shortcut_startup.QueryInterface(pythoncom.IID_IPersistFile).Save( "%s\\%s.lnk" % (startupfolder, description), 0) if createDesktopShortcut: desktopfolder = self.getDesktopPath() shortcut_desktop = pythoncom.CoCreateInstance( shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) shortcut_desktop.SetPath(executable) shortcut_desktop.SetDescription(description) if not iconLocation is None: shortcut_desktop.SetIconLocation(iconLocation, 0) shortcut_desktop.SetWorkingDirectory(workingDir) shortcut_desktop.QueryInterface(pythoncom.IID_IPersistFile).Save( "%s\\%s.lnk" % (desktopfolder, description), 0) j.tools.console.echo('Shortcuts created')
def task_exists(name): """Return true if a sheduled task names 'name.job' is defined""" ts = pythoncom.CoCreateInstance(taskscheduler.CLSID_CTaskScheduler, None, pythoncom.CLSCTX_INPROC_SERVER, taskscheduler.IID_ITaskScheduler) return '%s.job' % name in ts.Enum()
def _cat_registrar(): return pythoncom.CoCreateInstance( pythoncom.CLSID_StdComponentCategoriesMgr, None, pythoncom.CLSCTX_INPROC_SERVER, pythoncom.IID_ICatRegister)
def __init__(self): base = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) _PyShortcut.__init__(self, base)
def _scheduler_instance(self): # noinspection PyUnresolvedReferences scheduler = pythoncom.CoCreateInstance( taskscheduler.CLSID_CTaskScheduler, None, pythoncom.CLSCTX_INPROC_SERVER, taskscheduler.IID_ITaskScheduler) return scheduler
def main(): global APP_FOLDER if win_util.is_admin() is not True: p("}}rbApp must be run as Admin user with elevated (UAC) privileges!!!}}xx" ) return False global admin_user, admin_pass, smc_url, student_user, server_name, home_root canvas_access_token = "" canvas_url = "https://canvas.ed" win_util.disable_guest_account() # win_util.test_reg() # See if we already have a user credentialed. last_student_user = win_util.get_credentialed_student_name( default_value="") last_smc_url = win_util.get_last_smc_url(default_value="https://smc.ed") last_admin_user = win_util.get_last_admin_user(default_value="admin") # p("LAST STUDENT USER: "******"}}ynEnter URL for SMC Server }}cn[enter for " + last_smc_url + "]:}}xx ")) tmp = tmp.strip() if tmp == "": tmp = last_smc_url smc_url = tmp tmp = raw_input( term.translate_color_codes( "}}ynPlease enter the ADMIN user name }}cn[enter for " + last_admin_user + "]:}}xx ")) tmp = tmp.strip() if tmp == "": tmp = last_admin_user admin_user = tmp p("}}ynPlease enter ADMIN password }}cn[characters will not show]:}}xx", False) tmp = getpass.getpass(" ") if tmp == "": p("}}rbA password is required.}}xx") return False admin_pass = tmp tmp = "" last_student_user_prompt = "" while tmp.strip() == "": if last_student_user != "": last_student_user_prompt = " }}cn[enter for previous student " + last_student_user + "]" # p("}}mb\t- Found previously credentialed user: }}xx" + str(last_student_user)) tmp = raw_input( term.translate_color_codes( "}}ynPlease enter the username for the student" + last_student_user_prompt + ":}}xx ")) if tmp.strip() == "": tmp = last_student_user student_user = tmp.strip() result = verify_ope_account_in_smc(student_user, smc_url, admin_user, admin_pass) if result is None: p("}}rbERR - User doesn't exist in smc??}}xx") sys.exit(-1) laptop_admin_user, laptop_admin_password, student_full_name = result if laptop_admin_user == "" or laptop_admin_password == "": p("}}rbERR - Please set the laptop admin credentials in the SMC before continuing (Admin -> Configure App -> Laptop Admin Credentials) }}xx" ) sys.exit(-1) if student_full_name == "": p("}}rbERR - Unable to find student user in the SMC? Make sure it is imported.}}xx" ) sys.exit(-1) # Show confirm info txt = """ }}mn====================================================================== }}mn| }}ybConfirm Credential Parameters }}mn| }}mn| }}ynSMC URL: }}cn<smc_url>}}mn| }}mn| }}ynAdmin User: }}cn<admin_user>}}mn| }}mn| }}ynAdmin Password: }}cn<admin_pass>}}mn| }}mn| }}ynStudent Username: }}cn<student_user>}}mn| }}mn======================================================================}}xx """ txt = txt.replace("<smc_url>", smc_url.ljust(47)) txt = txt.replace("<admin_user>", admin_user.ljust(47)) txt = txt.replace("<admin_pass>", "******".ljust(47)) student_text = student_user + " (" + student_full_name + ")" txt = txt.replace("<student_user>", student_text.ljust(47)) p(txt) tmp = raw_input( term.translate_color_codes("}}ybPress Y to continue: }}xx")) tmp = tmp.strip().lower() if tmp != "y": p("}}cnCanceled / Not credentialing....}}xx") return False api_url = smc_url if not api_url.endswith("/"): api_url += "/" key = base64.b64encode(admin_user + ':' + admin_pass) headers = {'Authorization': 'Basic ' + key} # password_manager = urllib3.HTTPPasswordMgrWithDefaultRealm() # password_manager.add_password(None, api_url, admin_user, admin_pass) # handler = urllib3.HTTPBasicAuthHandler(password_manager) # opener = urllib3.build_opener(handler) # ssl_context = ssl._create_unverified_context() p("\n}}gnStarting Credential Process...}}xx\n") url = api_url + "lms/credential_student.json/" + student_user try: resp = requests.get( url, headers=headers, verify=False) # urllib3.Request(url, None, headers) except requests.ConnectionError as error_message: p("}}rbConnection error trying to connect to SMC server}}xx") p("}}yn" + str(error_message) + "}}xx") return False if resp is None: # Unable to get a response? p("}}rbInvalid response from SMC server!}}xx") return False if resp.status_code == requests.codes.forbidden: p("}}rbError authenticating with SMC server - check password and try again.}}xx" ) return False try: resp.raise_for_status() except Exception as error_message: p("}}rbGeneral error trying to connect to SMC server}}xx") p("}}yn" + str(error_message) + "}}xx") return False smc_response = None try: smc_response = resp.json() except ValueError as error_message: p("}}rbInvalid JSON response from SMC}}xx") p("}}yn" + str(error_message) + "}}xx") return False except Exception as error_message: p("}}rbUNKNOWN ERROR}}xx") p("}}yn" + str(error_message) + "}}xx") return False # Interpret response from SMC try: # p("RESP: " + str(smc_response)) msg = smc_response["msg"] if msg == "Invalid User!": p("\n}}rbInvalid User!}}xx") p("}}mnUser doesn't exit in system, please import this student in the SMC first!}}xx" ) return False if msg == "No username specified!": p("\n}}rbInvalid User!}}xx") p("}}mnNo user with this name exists, please import this student in the SMC first!}}xx" ) return False if "unable to connect to canvas db" in msg: p("\n}}rbSMC Unable to connect to Canvas DB - make sure canvas app is running and\n" + "the SMC tool is configured to talk to Canvas}}xx") p("}}yn" + str(msg) + "}}xx") return False if "Unable to find user in canvas:" in msg: p("\n}}rbInvalid User!}}xx") p("}}mnUser exists in SMC but not in Canvas, please rerun import this student in the SMC to correct the issue!}}xx" ) full_name = smc_response["full_name"] canvas_access_token = str(smc_response["key"]) hash = str(smc_response["hash"]) student_full_name = str(smc_response["full_name"]) canvas_url = str(smc_response['canvas_url']) except Exception as error_message: p("}}rbUnable to interpret response from SMC - no msg parameter returned}}xx" ) p("}}mn" + str(ex) + "}}xx") return False # p("Response: " + canvas_access_token + " ---- " + hash) pw = win_util.decrypt(hash, canvas_access_token) p("}}gnCreating local student windows account...") win_util.create_local_student_account(student_user, student_full_name, pw) p("}}gnCreating local admin windows account...") try: win_util.create_local_admin_account(laptop_admin_user, "OPE Laptop Admin", laptop_admin_password) except Exception as ex: p("}}rbError setting up OPE Laptop Admin Account " + str(ex)) laptop_admin_password = "" # Store the access token in the registry where the LMS app can pick it up p("}}gn\nSaving canvas credentials for student...") # key = win_util.create_reg_key(r"HKLM\Software\OPE\OPELMS", student_user) # key = win_util.create_reg_key(r"HKLM\Software\OPE\OPELMS\student") # key.canvas_access_token = canvas_access_token # key.user_name = student_user win_util.set_registry_value('canvas_access_token', canvas_access_token) win_util.set_registry_value('user_name', student_user) win_util.set_registry_value('canvas_url', canvas_url) win_util.set_registry_value('smc_url', smc_url) win_util.set_registry_value('admin_user', admin_user) win_util.set_registry_permissions(student_user) # p("}}gnCanvas access granted for student.}}xx") p("\n}}gnSetting up LMS App...}}xx") # Create shortcut lnk_path = "c:\\users\\public\\desktop\\OPE LMS.lnk" # Modify so that desktop shortcut point to where the app really is, not the hard coded dir # exe_path = "c:\\programdata\\ope\\ope_laptop_binaries\\lms\\ope_lms.exe" LMS_FOLDER = os.path.join(os.path.dirname(APP_FOLDER), "lms") exe_path = os.path.join(LMS_FOLDER, "ope_lms.exe") # ico_path = "c:\\programdata\\ope\\ope_laptop_binaries\\lms\\logo_icon.ico" ico_path = os.path.join(LMS_FOLDER, "logo_icon.ico") shortcut = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) shortcut.SetPath(exe_path) shortcut.SetDescription( "Offline LMS app for Open Prison Education project") shortcut.SetIconLocation(ico_path, 0) persist_file = shortcut.QueryInterface(pythoncom.IID_IPersistFile) persist_file.Save(lnk_path, 0) # If current user is not the laptop_admin_user - ask if we should disable this account? me = accounts.me() if laptop_admin_user != me.name: p("}}rb!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" ) p("}}rbYou are currently logged in as " + str(me.name) + " but the Laptop Admin user is " + str(laptop_admin_user) + ".") p("}}rb---> Please make sure to set a password and/or disable accounts that aren't needed on this laptop.}}xx" ) p("}}rb!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" ) countdown = 8 while countdown > 0: p("\r}}mb" + str(countdown) + "}}xx", end="") time.sleep(1) countdown -= 1 p("\n}}gbCanvas token saved.}}xx") p("") p("}}zn --------------> !!!!!CONFIRM BIOS!!!!! <-------------- }}xx" ) p("}}zn --------------> VERIFY BIOS PASSWORD/SETTINGS BEFORE HANDING OUT LAPTOP! <-------------- }}xx" ) countdown = 8 while countdown > 0: p("\r}}mb" + str(countdown) + "}}xx", end="") time.sleep(1) countdown -= 1 return True
def __init__(self): message_map = { win32con.WM_DESTROY: self.OnDestroy, win32con.WM_COMMAND: self.OnCommand, win32con.WM_SIZE: self.OnSize, } # Register the Window class. wc = win32gui.WNDCLASS() hinst = wc.hInstance = win32api.GetModuleHandle(None) wc.lpszClassName = "test_explorer_browser" wc.lpfnWndProc = message_map # could also specify a wndproc. classAtom = win32gui.RegisterClass(wc) # Create the Window. style = win32con.WS_OVERLAPPEDWINDOW | win32con.WS_VISIBLE self.hwnd = win32gui.CreateWindow(classAtom, "Python IExplorerBrowser demo", style, 0, 0, win32con.CW_USEDEFAULT, win32con.CW_USEDEFAULT, 0, 0, hinst, None) eb = pythoncom.CoCreateInstance(shellcon.CLSID_ExplorerBrowser, None, pythoncom.CLSCTX_ALL, shell.IID_IExplorerBrowser) # as per MSDN docs, hook up events early self.event_cookie = eb.Advise(wrap(EventHandler())) eb.SetOptions(shellcon.EBO_SHOWFRAMES) rect = win32gui.GetClientRect(self.hwnd) # Set the flags such that the folders autoarrange and non web view is # presented flags = (shellcon.FVM_LIST, shellcon.FWF_AUTOARRANGE | shellcon.FWF_NOWEBVIEW) eb.Initialize(self.hwnd, rect, (0, shellcon.FVM_DETAILS)) if len(sys.argv) == 2: # If an arg was specified, ask the desktop parse it. # You can pass anything explorer accepts as its '/e' argument - # eg, "::{guid}\::{guid}" etc. # "::{20D04FE0-3AEA-1069-A2D8-08002B30309D}" is "My Computer" pidl = shell.SHGetDesktopFolder().ParseDisplayName( 0, None, sys.argv[1])[1] else: # And start browsing at the root of the namespace. pidl = [] eb.BrowseToIDList(pidl, shellcon.SBSP_ABSOLUTE) # and for some reason the "Folder" view in the navigator pane doesn't # magically synchronize itself - so let's do that ourself. # Get the tree control. sp = eb.QueryInterface(pythoncom.IID_IServiceProvider) try: tree = sp.QueryService(shell.IID_INameSpaceTreeControl, shell.IID_INameSpaceTreeControl) except pythoncom.com_error as exc: # this should really only fail if no "nav" frame exists... print("Strange - failed to get the tree control even though " "we asked for a EBO_SHOWFRAMES") print(exc) else: # get the IShellItem for the selection. si = shell.SHCreateItemFromIDList(pidl, shell.IID_IShellItem) # set it to selected. tree.SetItemState(si, shellcon.NSTCIS_SELECTED, shellcon.NSTCIS_SELECTED) #eb.FillFromObject(None, shellcon.EBF_NODROPTARGET); #eb.SetEmptyText("No known folders yet..."); self.eb = eb
def send2trash(paths): paths = preprocess_paths(paths) # convert data type paths = [ text_type(path, "mbcs") if not isinstance(path, text_type) else path for path in paths ] # convert to full paths paths = [ op.abspath(path) if not op.isabs(path) else path for path in paths ] # remove the leading \\?\ if present paths = [ path[4:] if path.startswith("\\\\?\\") else path for path in paths ] # Need to initialize the com before using pythoncom.CoInitialize() # create instance of file operation object fileop = pythoncom.CoCreateInstance( shell.CLSID_FileOperation, None, pythoncom.CLSCTX_ALL, shell.IID_IFileOperation, ) # default flags to use flags = (shellcon.FOF_NOCONFIRMATION | shellcon.FOF_NOERRORUI | shellcon.FOF_SILENT | shellcon.FOFX_EARLYFAILURE) # determine rest of the flags based on OS version # use newer recommended flags if available if int(version().split(".", 1)[0]) >= 8: flags |= ( 0x20000000 # FOFX_ADDUNDORECORD win 8+ | 0x00080000 # FOFX_RECYCLEONDELETE win 8+ ) else: flags |= shellcon.FOF_ALLOWUNDO # set the flags fileop.SetOperationFlags(flags) # actually try to perform the operation, this section may throw a # pywintypes.com_error which does not seem to create as nice of an # error as OSError so wrapping with try to convert sink = CreateSink() try: for path in paths: item = shell.SHCreateItemFromParsingName(path, None, shell.IID_IShellItem) fileop.DeleteItem(item, sink) result = fileop.PerformOperations() aborted = fileop.GetAnyOperationsAborted() # if non-zero result or aborted throw an exception if result or aborted: raise OSError(None, None, paths, result) except pywintypes.com_error as error: # convert to standard OS error, allows other code to get a # normal errno raise OSError(None, error.strerror, path, error.hresult) finally: # Need to make sure we call this once fore every init pythoncom.CoUninitialize()
from win32com.shell import shell, shellcon import pythoncom import time website='http://sourceforge.net/projects/pywin32/' iad=pythoncom.CoCreateInstance(shell.CLSID_ActiveDesktop, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IActiveDesktop) opts=iad.GetDesktopItemOptions() if not (opts['ActiveDesktop'] and opts['EnableComponents']): print('Warning: Enabling Active Desktop') opts['ActiveDesktop']=True opts['EnableComponents']=True iad.SetDesktopItemOptions(opts) iad.ApplyChanges(0xffff) iad=None ## apparently takes a short while for it to become active time.sleep(2) iad=pythoncom.CoCreateInstance(shell.CLSID_ActiveDesktop, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IActiveDesktop) cnt=iad.GetDesktopItemCount() print('Count:', cnt) for i in range(cnt): print(iad.GetDesktopItem(i)) component={ 'ID': cnt+1, 'ComponentType': shellcon.COMP_TYPE_WEBSITE, 'CurItemState': shellcon.IS_NORMAL, 'SubscribedURL': website, 'Source' : website, 'FriendlyName' : 'Pywin32 on SF', 'Checked' : True, ## this controls whether item is currently displayed 'NoScroll' : False,
from win32com.server.util import wrap import pythoncom, sys, os, time, win32api, win32event, tempfile from win32com.bits import bits TIMEOUT = 200 # ms StopEvent = win32event.CreateEvent(None, 0, 0, None) job_name = 'bits-pywin32-test' states = dict([(val, (name[13:])) for name, val in vars(bits).iteritems() if name.startswith('BG_JOB_STATE_')]) bcm = pythoncom.CoCreateInstance(bits.CLSID_BackgroundCopyManager, None, pythoncom.CLSCTX_LOCAL_SERVER, bits.IID_IBackgroundCopyManager) class BackgroundJobCallback: _com_interfaces_ = [bits.IID_IBackgroundCopyCallback] _public_methods_ = ["JobTransferred", "JobError", "JobModification"] def JobTransferred(self, job): print 'Job Transferred', job job.Complete() win32event.SetEvent(StopEvent) # exit msg pump def JobError(self, job, error): print 'Job Error', job, error f = error.GetFile() print 'While downloading', f.GetRemoteName()
def tasksList(self): tasks_list = [] # manage tasks for windows XP if platform.release() == 'XP' or platform.release() == '2003': try: from win32com.taskscheduler import taskscheduler ts = pythoncom.CoCreateInstance( taskscheduler.CLSID_CTaskScheduler, None, pythoncom.CLSCTX_INPROC_SERVER, taskscheduler.IID_ITaskScheduler) except: return False # Loop through all scheduled task tasks = ts.Enum() for job in tasks: task = ts.Activate(job) t = Taskscheduler() t.name = job # check if the tasks file has write access taskpath = '%s%s%s%s%s' % (os.environ['systemroot'], os.sep, 'Tasks', os.sep, job) # TO DO # if os.path.exists(taskpath): # if checkPermissions(taskpath): # results = results + '<strong><font color=ff0000>Write access on: ' + taskpath + '</font></strong><br/>\n' # run as try: t.runas = task.GetCreator() except: pass # path of the exe file # try: # task.GetApplicationName() # except: # pass # check the permission of the executable # try: # test = checkPermissions(task.GetApplicationName()) # except: # pass # manage task for windows 7 else: if os.path.exists(self.task_directory): for root, dirs, files in os.walk(self.task_directory): for f in files: xml_file = os.path.join(root, f) try: tree = ET.ElementTree(file=xml_file) except: continue command = '' arguments = '' userid = '' groupid = '' runlevel = '' xmlroot = tree.getroot() for xml in xmlroot: # get task information (date, author) # in RegistrationInfo tag # get triggers information (launch at boot, etc.) # in Triggers tag # get user information if 'principals' in xml.tag.lower(): for child in xml.getchildren(): if 'principal' in child.tag.lower(): for principal in child.getchildren(): if 'userid' in principal.tag.lower( ): userid = principal.text elif 'groupid' in principal.tag.lower( ): groupid = principal.text elif 'runlevel' in principal.tag.lower( ): runlevel = principal.text # get all execution information (executable and arguments) if 'actions' in xml.tag.lower(): for child in xml.getchildren(): if 'exec' in child.tag.lower(): for execution in child.getchildren(): if 'command' in execution.tag.lower( ): command = os.path.expandvars( execution.text) elif 'arguments' in execution.tag.lower( ): arguments = os.path.expandvars( execution.text) full_path = '%s %s' % (str(command), str(arguments)) full_path = full_path.strip() if full_path: #and runlevel != 'LeastPrivilege': t = Taskscheduler() t.name = f t.full_path = full_path t.paths = get_path_info(t.full_path) if userid == 'S-1-5-18': t.userid = 'LocalSystem' else: t.userid = userid t.groupid = groupid t.runlevel = runlevel # append the tasks to the main tasklist tasks_list.append(t) return tasks_list