[11f7a07] | 1 | # -*- coding: utf-8 -*- |
---|
| 2 | # |
---|
| 3 | # Copyright (c) 2014 Virtual Cable S.L. |
---|
| 4 | # All rights reserved. |
---|
| 5 | # |
---|
| 6 | # Redistribution and use in source and binary forms, with or without modification, |
---|
| 7 | # are permitted provided that the following conditions are met: |
---|
| 8 | # |
---|
| 9 | # * Redistributions of source code must retain the above copyright notice, |
---|
| 10 | # this list of conditions and the following disclaimer. |
---|
| 11 | # * Redistributions in binary form must reproduce the above copyright notice, |
---|
| 12 | # this list of conditions and the following disclaimer in the documentation |
---|
| 13 | # and/or other materials provided with the distribution. |
---|
| 14 | # * Neither the name of Virtual Cable S.L. nor the names of its contributors |
---|
| 15 | # may be used to endorse or promote products derived from this software |
---|
| 16 | # without specific prior written permission. |
---|
| 17 | # |
---|
| 18 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" |
---|
| 19 | # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE |
---|
| 20 | # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE |
---|
| 21 | # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE |
---|
| 22 | # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL |
---|
| 23 | # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR |
---|
| 24 | # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
---|
| 25 | # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, |
---|
| 26 | # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
---|
| 27 | # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
---|
| 28 | |
---|
| 29 | ''' |
---|
| 30 | @author: Adolfo Gómez, dkmaster at dkmon dot com |
---|
| 31 | ''' |
---|
| 32 | from __future__ import unicode_literals |
---|
| 33 | |
---|
[e21cba1] | 34 | import os |
---|
[622bc35] | 35 | import locale |
---|
[e21cba1] | 36 | import subprocess |
---|
| 37 | import ctypes |
---|
| 38 | from ctypes.wintypes import DWORD, LPCWSTR |
---|
[11f7a07] | 39 | import win32com.client # @UnresolvedImport, pylint: disable=import-error |
---|
| 40 | import win32net # @UnresolvedImport, pylint: disable=import-error |
---|
| 41 | import win32security # @UnresolvedImport, pylint: disable=import-error |
---|
| 42 | import win32api # @UnresolvedImport, pylint: disable=import-error |
---|
| 43 | import win32con # @UnresolvedImport, pylint: disable=import-error |
---|
| 44 | |
---|
| 45 | from opengnsys import utils |
---|
| 46 | from opengnsys.log import logger |
---|
| 47 | |
---|
| 48 | |
---|
| 49 | def getErrorMessage(res=0): |
---|
| 50 | msg = win32api.FormatMessage(res) |
---|
| 51 | return msg.decode('windows-1250', 'ignore') |
---|
| 52 | |
---|
| 53 | |
---|
| 54 | def getComputerName(): |
---|
| 55 | return win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname) |
---|
| 56 | |
---|
| 57 | |
---|
| 58 | def getNetworkInfo(): |
---|
| 59 | ''' |
---|
| 60 | Obtains a list of network interfaces |
---|
| 61 | @return: A "generator" of elements, that are dict-as-object, with this elements: |
---|
| 62 | name: Name of the interface |
---|
| 63 | mac: mac of the interface |
---|
| 64 | ip: ip of the interface |
---|
[e21cba1] | 65 | ''' |
---|
[11f7a07] | 66 | obj = win32com.client.Dispatch("WbemScripting.SWbemLocator") |
---|
| 67 | wmobj = obj.ConnectServer("localhost", "root\cimv2") |
---|
| 68 | adapters = wmobj.ExecQuery("Select * from Win32_NetworkAdapterConfiguration where IpEnabled=True") |
---|
| 69 | try: |
---|
| 70 | for obj in adapters: |
---|
[f58562e] | 71 | if obj.DefaultIPGateway is None: # Skip adapters without default router |
---|
[0da2b87] | 72 | continue |
---|
[11f7a07] | 73 | for ip in obj.IPAddress: |
---|
| 74 | if ':' in ip: # Is IPV6, skip this |
---|
| 75 | continue |
---|
| 76 | if ip is None or ip == '' or ip.startswith('169.254') or ip.startswith('0.'): # If single link ip, or no ip |
---|
| 77 | continue |
---|
[0da2b87] | 78 | logger.debug('Net config found: {}=({}, {})'.format(obj.Caption, obj.MACAddress, ip)) |
---|
[11f7a07] | 79 | yield utils.Bunch(name=obj.Caption, mac=obj.MACAddress, ip=ip) |
---|
| 80 | except Exception: |
---|
| 81 | return |
---|
| 82 | |
---|
| 83 | |
---|
| 84 | def getDomainName(): |
---|
| 85 | ''' |
---|
| 86 | Will return the domain name if we belong a domain, else None |
---|
| 87 | (if part of a network group, will also return None) |
---|
| 88 | ''' |
---|
| 89 | # Status: |
---|
| 90 | # 0 = Unknown |
---|
| 91 | # 1 = Unjoined |
---|
| 92 | # 2 = Workgroup |
---|
| 93 | # 3 = Domain |
---|
| 94 | domain, status = win32net.NetGetJoinInformation() |
---|
| 95 | if status != 3: |
---|
| 96 | domain = None |
---|
| 97 | |
---|
| 98 | return domain |
---|
| 99 | |
---|
| 100 | |
---|
| 101 | def getWindowsVersion(): |
---|
[2e072d2] | 102 | ''' |
---|
| 103 | Returns Windows version. |
---|
| 104 | ''' |
---|
| 105 | import _winreg |
---|
| 106 | reg = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion') |
---|
| 107 | try: |
---|
| 108 | data = '{} {}'.format(_winreg.QueryValueEx(reg, 'ProductName')[0], _winreg.QueryValueEx(reg, 'ReleaseId')[0]) |
---|
| 109 | except Exception: |
---|
| 110 | data = '{} {}'.format(_winreg.QueryValueEx(reg, 'ProductName')[0], _winreg.QueryValueEx(reg, 'CurrentBuildNumber')[0]) |
---|
| 111 | reg.Close() |
---|
| 112 | return data |
---|
| 113 | |
---|
[11f7a07] | 114 | |
---|
| 115 | EWX_LOGOFF = 0x00000000 |
---|
| 116 | EWX_SHUTDOWN = 0x00000001 |
---|
| 117 | EWX_REBOOT = 0x00000002 |
---|
| 118 | EWX_FORCE = 0x00000004 |
---|
| 119 | EWX_POWEROFF = 0x00000008 |
---|
| 120 | EWX_FORCEIFHUNG = 0x00000010 |
---|
| 121 | |
---|
| 122 | |
---|
| 123 | def reboot(flags=EWX_FORCEIFHUNG | EWX_REBOOT): |
---|
| 124 | hproc = win32api.GetCurrentProcess() |
---|
| 125 | htok = win32security.OpenProcessToken(hproc, win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY) |
---|
| 126 | privs = ((win32security.LookupPrivilegeValue(None, win32security.SE_SHUTDOWN_NAME), win32security.SE_PRIVILEGE_ENABLED),) |
---|
| 127 | win32security.AdjustTokenPrivileges(htok, 0, privs) |
---|
| 128 | win32api.ExitWindowsEx(flags, 0) |
---|
| 129 | |
---|
| 130 | def poweroff(flags=0): |
---|
| 131 | ''' |
---|
| 132 | Simple poweroff command. |
---|
| 133 | ''' |
---|
[e21cba1] | 134 | reboot(flags=EWX_FORCEIFHUNG | EWX_SHUTDOWN) |
---|
[11f7a07] | 135 | |
---|
| 136 | def logoff(): |
---|
| 137 | win32api.ExitWindowsEx(EWX_LOGOFF) |
---|
| 138 | |
---|
| 139 | |
---|
| 140 | def renameComputer(newName): |
---|
| 141 | # Needs admin privileges to work |
---|
| 142 | if ctypes.windll.kernel32.SetComputerNameExW(DWORD(win32con.ComputerNamePhysicalDnsHostname), LPCWSTR(newName)) == 0: # @UndefinedVariable |
---|
| 143 | # win32api.FormatMessage -> returns error string |
---|
| 144 | # win32api.GetLastError -> returns error code |
---|
| 145 | # (just put this comment here to remember to log this when logger is available) |
---|
| 146 | error = getErrorMessage() |
---|
| 147 | computerName = win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname) |
---|
| 148 | raise Exception('Error renaming computer from {} to {}: {}'.format(computerName, newName, error)) |
---|
| 149 | |
---|
[2e072d2] | 150 | |
---|
[11f7a07] | 151 | NETSETUP_JOIN_DOMAIN = 0x00000001 |
---|
| 152 | NETSETUP_ACCT_CREATE = 0x00000002 |
---|
| 153 | NETSETUP_ACCT_DELETE = 0x00000004 |
---|
| 154 | NETSETUP_WIN9X_UPGRADE = 0x00000010 |
---|
| 155 | NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x00000020 |
---|
| 156 | NETSETUP_JOIN_UNSECURE = 0x00000040 |
---|
| 157 | NETSETUP_MACHINE_PWD_PASSED = 0x00000080 |
---|
| 158 | NETSETUP_JOIN_WITH_NEW_NAME = 0x00000400 |
---|
| 159 | NETSETUP_DEFER_SPN_SET = 0x1000000 |
---|
| 160 | |
---|
| 161 | |
---|
| 162 | def joinDomain(domain, ou, account, password, executeInOneStep=False): |
---|
| 163 | ''' |
---|
| 164 | Joins machine to a windows domain |
---|
| 165 | :param domain: Domain to join to |
---|
| 166 | :param ou: Ou that will hold machine |
---|
| 167 | :param account: Account used to join domain |
---|
| 168 | :param password: Password of account used to join domain |
---|
| 169 | :param executeInOneStep: If true, means that this machine has been renamed and wants to add NETSETUP_JOIN_WITH_NEW_NAME to request so we can do rename/join in one step. |
---|
| 170 | ''' |
---|
| 171 | # If account do not have domain, include it |
---|
| 172 | if '@' not in account and '\\' not in account: |
---|
| 173 | if '.' in domain: |
---|
| 174 | account = account + '@' + domain |
---|
| 175 | else: |
---|
| 176 | account = domain + '\\' + account |
---|
| 177 | |
---|
| 178 | # Do log |
---|
| 179 | flags = NETSETUP_ACCT_CREATE | NETSETUP_DOMAIN_JOIN_IF_JOINED | NETSETUP_JOIN_DOMAIN |
---|
| 180 | |
---|
| 181 | if executeInOneStep: |
---|
| 182 | flags |= NETSETUP_JOIN_WITH_NEW_NAME |
---|
| 183 | |
---|
| 184 | flags = DWORD(flags) |
---|
| 185 | |
---|
| 186 | domain = LPCWSTR(domain) |
---|
| 187 | |
---|
| 188 | # Must be in format "ou=.., ..., dc=...," |
---|
| 189 | ou = LPCWSTR(ou) if ou is not None and ou != '' else None |
---|
| 190 | account = LPCWSTR(account) |
---|
| 191 | password = LPCWSTR(password) |
---|
| 192 | |
---|
| 193 | res = ctypes.windll.netapi32.NetJoinDomain(None, domain, ou, account, password, flags) |
---|
| 194 | # Machine found in another ou, use it and warn this on log |
---|
| 195 | if res == 2224: |
---|
| 196 | flags = DWORD(NETSETUP_DOMAIN_JOIN_IF_JOINED | NETSETUP_JOIN_DOMAIN) |
---|
| 197 | res = ctypes.windll.netapi32.NetJoinDomain(None, domain, None, account, password, flags) |
---|
| 198 | if res != 0: |
---|
| 199 | # Log the error |
---|
| 200 | error = getErrorMessage(res) |
---|
| 201 | if res == 1355: |
---|
| 202 | error = "DC Is not reachable" |
---|
[e21cba1] | 203 | print('{} {}'.format(res, error)) |
---|
[11f7a07] | 204 | raise Exception('Error joining domain {}, with credentials {}/*****{}: {}, {}'.format(domain.value, account.value, ', under OU {}'.format(ou.value) if ou.value is not None else '', res, error)) |
---|
| 205 | |
---|
| 206 | |
---|
| 207 | def changeUserPassword(user, oldPassword, newPassword): |
---|
| 208 | computerName = LPCWSTR(getComputerName()) |
---|
| 209 | user = LPCWSTR(user) |
---|
| 210 | oldPassword = LPCWSTR(oldPassword) |
---|
| 211 | newPassword = LPCWSTR(newPassword) |
---|
| 212 | |
---|
| 213 | res = ctypes.windll.netapi32.NetUserChangePassword(computerName, user, oldPassword, newPassword) |
---|
| 214 | |
---|
| 215 | if res != 0: |
---|
| 216 | # Log the error, and raise exception to parent |
---|
| 217 | error = getErrorMessage() |
---|
| 218 | raise Exception('Error changing password for user {}: {}'.format(user.value, error)) |
---|
| 219 | |
---|
| 220 | |
---|
| 221 | class LASTINPUTINFO(ctypes.Structure): |
---|
| 222 | _fields_ = [ |
---|
| 223 | ('cbSize', ctypes.c_uint), |
---|
| 224 | ('dwTime', ctypes.c_uint), |
---|
| 225 | ] |
---|
| 226 | |
---|
| 227 | |
---|
| 228 | def initIdleDuration(atLeastSeconds): |
---|
| 229 | ''' |
---|
| 230 | In windows, there is no need to set screensaver |
---|
| 231 | ''' |
---|
| 232 | pass |
---|
| 233 | |
---|
| 234 | |
---|
| 235 | def getIdleDuration(): |
---|
| 236 | lastInputInfo = LASTINPUTINFO() |
---|
| 237 | lastInputInfo.cbSize = ctypes.sizeof(lastInputInfo) |
---|
| 238 | ctypes.windll.user32.GetLastInputInfo(ctypes.byref(lastInputInfo)) |
---|
| 239 | millis = ctypes.windll.kernel32.GetTickCount() - lastInputInfo.dwTime # @UndefinedVariable |
---|
| 240 | return millis / 1000.0 |
---|
| 241 | |
---|
| 242 | |
---|
| 243 | def getCurrentUser(): |
---|
| 244 | ''' |
---|
| 245 | Returns current logged in username |
---|
| 246 | ''' |
---|
| 247 | return os.environ['USERNAME'] |
---|
[1deb0d1] | 248 | |
---|
[622bc35] | 249 | |
---|
| 250 | def getSessionLanguage(): |
---|
| 251 | ''' |
---|
| 252 | Returns the user's session language |
---|
| 253 | ''' |
---|
| 254 | return locale.getdefaultlocale()[0] |
---|
| 255 | |
---|
| 256 | |
---|
[1deb0d1] | 257 | def showPopup(title, message): |
---|
| 258 | ''' |
---|
| 259 | Displays a message box on user's session (during 1 min). |
---|
| 260 | ''' |
---|
[aac3fb9] | 261 | return subprocess.call('mshta "javascript:var sh=new ActiveXObject(\'WScript.Shell\'); sh.Popup( \'{}\', 60, \'{}\', 64); close()"'.format(message.encode('unicode_escape'), title.encode('unicode_escape')), shell=True) |
---|
[bedce23] | 262 | |
---|
| 263 | |
---|
| 264 | def get_etc_path(): |
---|
| 265 | """ |
---|
| 266 | :return: |
---|
| 267 | Returns etc directory path. |
---|
| 268 | """ |
---|
| 269 | return os.path.join('C:', os.sep, 'Windows', 'System32', 'drivers', 'etc') |
---|