def install_service_windows(): logger.notice("Installing windows service") from opsiclientd.windows.service import handle_commandline # pylint: disable=import-outside-toplevel handle_commandline( argv=["opsiclientd.exe", "--startup", "auto", "install"]) # pyright: reportMissingImports=false import winreg # pylint: disable=import-outside-toplevel,import-error import win32process # pylint: disable=import-outside-toplevel,import-error key_handle = winreg.CreateKey( winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Services\opsiclientd") if win32process.IsWow64Process(): winreg.DisableReflectionKey(key_handle) winreg.SetValueEx(key_handle, 'DependOnService', 0, winreg.REG_MULTI_SZ, ["Dhcp"]) #winreg.SetValueEx(key_handle, 'DependOnService', 0, winreg.REG_MULTI_SZ, ["Dhcp", "Dnscache"]) winreg.CloseKey(key_handle) key_handle = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Control") if win32process.IsWow64Process(): winreg.DisableReflectionKey(key_handle) winreg.SetValueEx(key_handle, 'ServicesPipeTimeout', 0, winreg.REG_DWORD, 120000) winreg.CloseKey(key_handle)
def is64bit(self): if hasattr(self, "_bit64"): return self._bit64 ARCH = GetOption("arch") if ARCH == "x64": self._bit64 = True elif ARCH == "x86": self._bit64 = False else: if ARCH not in [None, "detect"]: import warnings warnings.warn("Unknown arch value. Using 'detect'") if self.iswin32(): # Work around for 32bit Windows executables try: import win32process self._bit64 = win32process.IsWow64Process() except: import ctypes, sys i = ctypes.c_int() kernel32 = ctypes.windll.kernel32 process = kernel32.GetCurrentProcess() kernel32.IsWow64Process(process, ctypes.byref(i)) self._bit64 = (i.value != 0) else: import platform self._bit64 = platform.architecture()[0] == "64bit" if not self.omero_quiet: print "64-Bit build: %s (%s)" % (self._bit64, ARCH) return self._bit64
def print_basic_debug_info(out=None): if out is None: out = sys.stdout out = functools.partial(prints, file=out) import platform from calibre.constants import (__appname__, get_version, isportable, isosx, isfrozen, is64bit) out(__appname__, get_version(), 'Portable' if isportable else '', 'isfrozen:', isfrozen, 'is64bit:', is64bit) out(platform.platform(), platform.system(), platform.architecture()) if iswindows and not is64bit: try: import win32process if win32process.IsWow64Process(): out('32bit process running on 64bit windows') except: pass out(platform.system_alias(platform.system(), platform.release(), platform.version())) out('Python', platform.python_version()) try: if iswindows: out('Windows:', platform.win32_ver()) elif isosx: out('OSX:', platform.mac_ver()) else: out('Linux:', platform.linux_distribution()) except: pass from calibre.customize.ui import has_external_plugins, initialized_plugins if has_external_plugins(): names = (p.name for p in initialized_plugins() if getattr(p, 'plugin_path', None) is not None) out('Successfully initialized third party plugins:', ' && '.join(names))
def __init__(self): # Store handler for function self.pckt_handler = None self.num_packets = 0 # Set Max recursion limit for parse_file # sys.setrecursionlimit(10) # Process os if 'win32' in sys.platform: import win32process if win32process.IsWow64Process () == True: self.capinfos_file = 'c:\\Program Files (x86)\\Wireshark\\capinfos.exe' self.tsharks_file = 'c:\\Program Files (x86)\\Wireshark\\tshark.exe' else: self.capinfos_file = 'c:\\Program Files\\Wireshark\\capinfos.exe' self.tsharks_file = 'c:\\Program Files\\Wireshark\\tshark.exe' elif 'linux' in sys.platform: self.capinfos_file = "./capinfos" self.tsharks_file = "./tshark" else: raise globals.Error("Unknown os type, where is capinfos.exe") if not( os.path.exists(self.capinfos_file) or os.path.exists(self.tsharks_file) ): raise globals.Error("Tshark or capinfos file not found, please make sure you have a full WireShark full installtion")
def print_basic_debug_info(out=None): if out is None: out = sys.stdout out = functools.partial(prints, file=out) import platform from calibre.constants import (__appname__, get_version, isportable, isosx, isfrozen, is64bit) out(__appname__, get_version(), 'Portable' if isportable else '', 'isfrozen:', isfrozen, 'is64bit:', is64bit) out(platform.platform(), platform.system(), platform.architecture()) if iswindows and not is64bit: try: import win32process if win32process.IsWow64Process(): out('32bit process running on 64bit windows') except: pass out(platform.system_alias(platform.system(), platform.release(), platform.version())) out('Python', platform.python_version()) try: if iswindows: out('Windows:', platform.win32_ver()) elif isosx: out('OSX:', platform.mac_ver()) else: out('Linux:', platform.linux_distribution()) except: pass
def _add_platform_profile(): # Platform info import platform from calibre.constants import (__appname__, get_version, isportable, isosx, isfrozen, is64bit, iswindows) calibre_profile = "{0} {1}{2} isfrozen:{3} is64bit:{4}".format( __appname__, get_version(), ' Portable' if isportable else '', isfrozen, is64bit) device_profile['CalibreProfile'] = calibre_profile platform_profile = "{0} {1} {2}".format( platform.platform(), platform.system(), platform.architecture()) device_profile['PlatformProfile'] = platform_profile try: if iswindows: os_profile = "Windows {0}".format(platform.win32_ver()) if not is64bit: try: import win32process if win32process.IsWow64Process(): os_profile += " 32bit process running on 64bit windows" except: pass elif isosx: os_profile = "OS X {0}".format(platform.mac_ver()[0]) else: os_profile = "Linux {0}".format(platform.linux_distribution()) except: import traceback self._log(traceback.format_exc()) os_profile = "unknown" device_profile['OSProfile'] = os_profile
def get(self): applications = {} (_, encoding) = locale.getdefaultlocale() if encoding is None: encoding = "utf8" files = self.find_lnk() for filename in files: shortcut = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) shortcut.QueryInterface( pythoncom.IID_IPersistFile ).Load(filename) name = os.path.basename(filename)[:-4] if self.isBan(name): continue try: local_id = hashlib.md5(filename.encode(encoding)).hexdigest() except UnicodeEncodeError, err: local_id = hashlib.md5(filename.encode('utf-8')).hexdigest() application = {} application["local_id"] = local_id application["name"] = name application["command"] = unicode(shortcut.GetPath(0)[0], encoding) application["filename"] = filename if len(shortcut.GetIconLocation()[0])>0: application["icon"] = unicode(shortcut.GetIconLocation()[0], encoding) if self.msi is not None: buf = self.msi.getTargetFromShortcut(filename) if buf is not None: application["command"] = buf if not application["command"].lower().endswith(".exe") and ".exe " not in application["command"].lower(): continue if win32process.IsWow64Process() and not os.path.exists(application["command"]): application["command"] = Util.clean_wow64_path(application["command"]) if " " in application["command"]: application["command"] = '"%s"'%(application["command"]) if len(shortcut.GetArguments())>0: application["command"]+= " "+unicode(shortcut.GetArguments(), encoding) try: if len(shortcut.GetDescription())>0: application["description"] = unicode(shortcut.GetDescription(), encoding) except pywintypes.com_error: Logger.debug("ApplicationsDetection::get unable to get description for %s"%(application["filename"])) application["mimetypes"] = self.mimetypes.get_mime_types_from_command(application["command"]) applications[application["local_id"]] = application
def GetWindowsRegistryKeyName(name): import win32process # Check if python process is 64-bit or if it's 32-bit running in 64-bit OS. # We need to know whether host is 64-bit so that we are looking in right # registry for Visual Studio path. if sys.maxsize > 2**32 or win32process.IsWow64Process(): wow6432Node = 'Wow6432Node\\' else: wow6432Node = '' return r'SOFTWARE\%s%s' % (wow6432Node, name)
def isWin64(): myhandle = pywintypes.HANDLE(win32api.GetCurrentProcess()) ret = win32process.IsWow64Process(myhandle) if ret: return True else: sysInfo = win32api.GetNativeSystemInfo() if sysInfo and (sysInfo[0] == 9 or sysInfo[0] == 6): return True return False
def beforeStartApp(self): if sys.platform != "win32": return if not win32process.IsWow64Process(): return k32 = ctypes.windll.kernel32 wow64 = ctypes.c_long(0) k32.Wow64DisableWow64FsRedirection(ctypes.byref(wow64))
def get_system_dir(): import win32api # we assume this exists. try: import pythoncom import win32process from win32com.shell import shell, shellcon try: if win32process.IsWow64Process(): return shell.SHGetSpecialFolderPath(0,shellcon.CSIDL_SYSTEMX86) return shell.SHGetSpecialFolderPath(0,shellcon.CSIDL_SYSTEM) except (pythoncom.com_error, win32process.error): return win32api.GetSystemDirectory() except ImportError: return win32api.GetSystemDirectory()
def is64bitprocess(process_id): """Return True if the specified process is a 64-bit process on x64 Return False if it is only a 32-bit process running under Wow64. Always return False for x86. """ from .sysinfo import is_x64_OS is32 = True if is_x64_OS(): phndl = win32api.OpenProcess(win32con.MAXIMUM_ALLOWED, 0, process_id) if phndl: is32 = win32process.IsWow64Process(phndl) #print("is64bitprocess, is32: %d, procid: %d" % (is32, process_id)) return (not is32)
def is64bitprocess(process_id): """Return True if the specified process is a 64-bit process on x64 and False if it is only a 32-bit process running under Wow64. Always return False for x86""" from pywinauto.sysinfo import is_x64_OS is32 = True if is_x64_OS(): import win32process, win32api phndl = win32api.OpenProcess(0x400, 0, process_id) if phndl: is32 = win32process.IsWow64Process(phndl) #print("is64bitprocess, is32: %d, procid: %d" % (is32, process_id)) return (not is32)
def __init__(self): """ Locate the SSH binaries on various systems. On Windows we bundle a Cygwin build of OpenSSH. """ sixty_four_bit_python = struct.calcsize("P") * 8 == 64 sixty_four_bit_operating_system = sixty_four_bit_python or ( sys.platform.startswith("win") and win32process.IsWow64Process() # pylint: disable=c-extension-no-member ) if "HOME" not in os.environ: os.environ["HOME"] = os.path.expanduser("~") if sixty_four_bit_operating_system: win_openssh_dir = r"win64\openssh-8.5p1-cygwin-3.2.0" else: win_openssh_dir = r"win32\openssh-7.3p1-cygwin-2.8.0" if hasattr(sys, "frozen"): base_dir = os.path.dirname(sys.executable) else: base_dir = os.path.realpath( os.path.join(os.path.dirname(__file__), "..", "..") ) win_openssh_dir = os.path.join("resources", win_openssh_dir) if sys.platform.startswith("win"): base_dir = os.path.join(base_dir, win_openssh_dir) binary_suffix = ".exe" dot_ssh_dir = os.path.join(base_dir, "home", getpass.getuser(), ".ssh") if not os.path.exists(dot_ssh_dir): os.makedirs(dot_ssh_dir) else: base_dir = "/usr/" binary_suffix = "" bin_base_dir = os.path.join(base_dir, "bin") self.ssh = os.path.join(bin_base_dir, "ssh" + binary_suffix) self.scp = os.path.join(bin_base_dir, "scp" + binary_suffix) self.ssh_keygen = os.path.join(bin_base_dir, "ssh-keygen" + binary_suffix) self.mkdir = os.path.join(bin_base_dir, "mkdir" + binary_suffix) self.cat = os.path.join(bin_base_dir, "cat" + binary_suffix)
def __init__(self): """ Locate the SSH binaries on various systems. On Windows we bundle a Cygwin build of OpenSSH. """ sixtyFourBitPython = (struct.calcsize('P') * 8 == 64) sixtyFourBitOperatingSystem = sixtyFourBitPython or \ (sys.platform.startswith("win") and win32process.IsWow64Process()) if "HOME" not in os.environ: os.environ["HOME"] = os.path.expanduser('~') if sixtyFourBitOperatingSystem: winOpensshDir = r"win64\openssh-7.3p1-cygwin-2.6.0" else: winOpensshDir = r"win32\openssh-7.3p1-cygwin-2.8.0" if hasattr(sys, "frozen"): baseDir = os.path.dirname(sys.executable) else: baseDir = os.path.dirname(pkgutil.get_loader("mydata").filename) winOpensshDir = os.path.join("resources", winOpensshDir) if sys.platform.startswith("win"): baseDir = os.path.join(baseDir, winOpensshDir) binarySuffix = ".exe" dotSshDir = os.path.join(baseDir, "home", getpass.getuser(), ".ssh") if not os.path.exists(dotSshDir): os.makedirs(dotSshDir) else: baseDir = "/usr/" binarySuffix = "" binBaseDir = os.path.join(baseDir, "bin") self.ssh = os.path.join(binBaseDir, "ssh" + binarySuffix) self.scp = os.path.join(binBaseDir, "scp" + binarySuffix) self.sshKeyGen = os.path.join(binBaseDir, "ssh-keygen" + binarySuffix) self.mkdir = os.path.join(binBaseDir, "mkdir" + binarySuffix) self.cat = os.path.join(binBaseDir, "cat" + binarySuffix)
def _CheckForWow64(): """Checks to ensure we are not running on a Wow64 system.""" if win32process.IsWow64Process(): raise RuntimeError( "Will not install a 32 bit client on a 64 bit system. " "Please use the correct client.")
# but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. import ctypes import ctypes.wintypes import sys import win32con import win32process # Detect if running in wow64 mode or not if win32process.IsWow64Process(): PTR = ctypes.c_uint64 ULONG = ctypes.c_ulonglong NT_QUERY_INFORMATION_PROCESS = ctypes.windll.ntdll.NtWow64QueryInformationProcess64 NT_READ_VIRTUAL_MEMORY = ctypes.windll.ntdll.NtWow64ReadVirtualMemory64 else: PTR = ctypes.c_size_t ULONG = ctypes.c_ulong NT_QUERY_INFORMATION_PROCESS = ctypes.windll.ntdll.NtQueryInformationProcess NT_READ_VIRTUAL_MEMORY = ctypes.windll.ntdll.NtReadVirtualMemory class PROCESS_BASIC_INFORMATION(ctypes.Structure): _fields_ = [ ("ExitStatus", PTR),
def RunOnce(self): if win32process.IsWow64Process(): raise RuntimeError( "Will not install a 32 bit client on a 64 bit system. " "Please use the correct client.")
def getTarget(filename): cmd = None try: msi = Msi() cmd = msi.getTargetFromShortcut(filename) except WindowsError, e: Logger.warn("LnkFile::getTarget: Unable to init Msi") msi = None if cmd is None: pythoncom.CoInitialize() shortcut = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) try: shortcut.QueryInterface(pythoncom.IID_IPersistFile).Load(filename) except pythoncom.com_error: Logger.exception("LnkFile::getTarget: Unable to load file '%s'" % filename) return None command = shortcut.GetPath(0)[0] if not os.path.exists(command) and win32process.IsWow64Process(): command = Util.clean_wow64_path(command) cmd = "%s %s" % (command, shortcut.GetArguments()) return cmd
def setup_on_shutdown(): if not RUNNING_ON_WINDOWS: return None logger.notice("Creating opsi shutdown install policy") # pyright: reportMissingImports=false import winreg # pylint: disable=import-outside-toplevel,import-error import win32process # pylint: disable=import-outside-toplevel,import-error GPO_NAME = "opsi shutdown install policy" BASE_KEYS = [ r"SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\State\Machine\Scripts\Shutdown", r"SOFTWARE\Microsoft\Windows\CurrentVersion\Group Policy\Scripts\Shutdown" ] opsiclientd_rpc = os.path.realpath( config.get('opsiclientd_rpc', 'command').split('"')[1].strip('"')) if not opsiclientd_rpc: opsiclientd_rpc = os.path.join( os.path.dirname(os.path.realpath(__file__)), "opsiclientd_rpc.exe") # Windows does not execute binaries directly, using cmd script script_path = opsiclientd_rpc[:-3] + "cmd" with codecs.open(script_path, "w", "windows-1252") as file: file.write(f'"%~dp0\\{os.path.basename(opsiclientd_rpc)}" %*\r\n') script_params = "--timeout=18000 runOnShutdown()" for base_key in BASE_KEYS: base_key_handle = winreg.CreateKey(winreg.HKEY_LOCAL_MACHINE, base_key) if win32process.IsWow64Process(): winreg.DisableReflectionKey(base_key_handle) num = -1 while True: num += 1 try: key_handle = winreg.OpenKey(base_key_handle, str(num)) (value, _type) = winreg.QueryValueEx(key_handle, "GPOName") winreg.CloseKey(key_handle) if value == GPO_NAME: break except OSError: # Key does not exist break key_handle = winreg.CreateKey(base_key_handle, str(num)) winreg.SetValueEx(key_handle, "GPO-ID", 0, winreg.REG_SZ, "LocalGPO") winreg.SetValueEx(key_handle, "SOM-ID", 0, winreg.REG_SZ, "Local") winreg.SetValueEx( key_handle, "FileSysPath", 0, winreg.REG_SZ, rf"{os.environ['SystemRoot']}\System32\GroupPolicy\Machine") winreg.SetValueEx(key_handle, "DisplayName", 0, winreg.REG_SZ, GPO_NAME) winreg.SetValueEx(key_handle, "GPOName", 0, winreg.REG_SZ, GPO_NAME) winreg.SetValueEx(key_handle, "PSScriptOrder", 0, winreg.REG_DWORD, 1) key_handle2 = winreg.CreateKey(key_handle, "0") winreg.SetValueEx(key_handle2, "Script", 0, winreg.REG_SZ, script_path) winreg.SetValueEx(key_handle2, "Parameters", 0, winreg.REG_SZ, script_params) winreg.SetValueEx(key_handle2, "ErrorCode", 0, winreg.REG_DWORD, 0) winreg.SetValueEx(key_handle2, "IsPowershell", 0, winreg.REG_DWORD, 0) winreg.SetValueEx( key_handle2, "ExecTime", 0, winreg.REG_BINARY, b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" ) winreg.CloseKey(key_handle2) winreg.CloseKey(key_handle) winreg.CloseKey(base_key_handle) key_handle = winreg.CreateKey( winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System") if win32process.IsWow64Process(): winreg.DisableReflectionKey(key_handle) winreg.SetValueEx(key_handle, "MaxGPOScriptWait", 0, winreg.REG_DWORD, 0) #winreg.SetValueEx(key_handle, "ShutdownWithoutLogon", 0, winreg.REG_DWORD, 1) winreg.CloseKey(key_handle)
def getIcon(self, filename): Logger.debug("ApplicationsDetection::getIcon %s" % (filename)) if not os.path.exists(filename): Logger.warn("ApplicationsDetection::getIcon no such file") return None pythoncom.CoInitialize() if win32process.IsWow64Process(): wow64_value = Util.Wow64DisableWow64FsRedirection() shortcut = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) shortcut.QueryInterface(pythoncom.IID_IPersistFile).Load(filename) (iconLocation_src, iconId) = shortcut.GetIconLocation() iconLocation = win32api.ExpandEnvironmentStrings(iconLocation_src) if not os.path.exists(iconLocation) and win32process.IsWow64Process(): iconLocation = Util.clean_wow64_path(iconLocation) if len(iconLocation) == 0 or not os.path.exists(iconLocation): Logger.debug( "ApplicationsDetection::getIcon No IconLocation, use shortcut target" ) iconLocation = win32api.ExpandEnvironmentStrings( shortcut.GetPath(shell.SLGP_RAWPATH)[0]) if not os.path.exists( iconLocation) and win32process.IsWow64Process(): iconLocation = Util.clean_wow64_path(iconLocation) if len(iconLocation) == 0 or not os.path.exists(iconLocation): Logger.warn( "ApplicationsDetection::getIcon Neither IconLocation nor shortcut target on %s (%s)" % (filename, iconLocation)) if win32process.IsWow64Process(): Util.Revert64DisableWow64FsRedirection(wow64_value) return None if win32process.IsWow64Process(): Util.Revert64DisableWow64FsRedirection(wow64_value) path_tmp = tempfile.mktemp() path_bmp = path_tmp + ".bmp" path_png = path_tmp + ".png" cmd = """"%s" "%s,%d" "%s" """ % ("exeIcon2png.exe", iconLocation, iconId, path_png) status = self.execute(cmd, True) if status != 0: Logger.warn("Unable to extract icon, use alternative method") Logger.debug( "ApplicationsDetection::getIcon following command returned %d: %s" % (status, cmd)) if os.path.exists(path_png): os.remove(path_png) cmd = """"%s" "%s" "%s" """ % ("extract_icon.exe", iconLocation, path_bmp) status = self.execute(cmd, True) if status != 0: Logger.warn( "Unable to extract icon with the alternative method") Logger.debug( "ApplicationsDetection::getIcon following command returned %d: %s" % (status, cmd)) if os.path.exists(path_bmp): os.remove(path_bmp) return None if not os.path.exists(path_bmp): Logger.debug( "ApplicationsDetection::getIcon No bmp file returned") return None cmd = """"%s" -Q -O "%s" "%s" """ % ("bmp2png.exe", path_png, path_bmp) status = self.execute(cmd, True) if status != 0: Logger.warn( "Unable to extract icon with the alternative method") Logger.debug( "ApplicationsDetection::getIcon following command returned %d: %s" % (status, cmd)) os.remove(path_bmp) if os.path.exists(path_png): os.remove(path_png) return None os.remove(path_bmp) if not os.path.exists(path_png): Logger.debug("ApplicationsDetection::getIcon No png file returned") return None f = open(path_png, 'rb') buffer = f.read() f.close() os.remove(path_png) return buffer
def is_wow64(self): if not self.wow64 and self.get_ph(): self.wow64 = win32process.IsWow64Process(self.get_ph()) return self.wow64
def is_wow64(self): return win32process.IsWow64Process()