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 | |
---|
34 | import os |
---|
35 | import locale |
---|
36 | import subprocess |
---|
37 | import ctypes |
---|
38 | import base64 |
---|
39 | from ctypes.wintypes import DWORD, LPCWSTR |
---|
40 | import win32com.client # @UnresolvedImport, pylint: disable=import-error |
---|
41 | import win32net # @UnresolvedImport, pylint: disable=import-error |
---|
42 | import win32security # @UnresolvedImport, pylint: disable=import-error |
---|
43 | import win32api # @UnresolvedImport, pylint: disable=import-error |
---|
44 | import win32con # @UnresolvedImport, pylint: disable=import-error |
---|
45 | |
---|
46 | from opengnsys import utils |
---|
47 | from opengnsys.log import logger |
---|
48 | |
---|
49 | |
---|
50 | def getErrorMessage(res=0): |
---|
51 | msg = win32api.FormatMessage(res) |
---|
52 | return msg.decode('windows-1250', 'ignore') |
---|
53 | |
---|
54 | |
---|
55 | def getComputerName(): |
---|
56 | return win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname) |
---|
57 | |
---|
58 | |
---|
59 | def getNetworkInfo(): |
---|
60 | ''' |
---|
61 | Obtains a list of network interfaces |
---|
62 | @return: A "generator" of elements, that are dict-as-object, with this elements: |
---|
63 | name: Name of the interface |
---|
64 | mac: mac of the interface |
---|
65 | ip: ip of the interface |
---|
66 | ''' |
---|
67 | obj = win32com.client.Dispatch("WbemScripting.SWbemLocator") |
---|
68 | wmobj = obj.ConnectServer("localhost", "root\\cimv2") |
---|
69 | adapters = wmobj.ExecQuery("Select * from Win32_NetworkAdapterConfiguration where IpEnabled=True") |
---|
70 | try: |
---|
71 | for obj in adapters: |
---|
72 | if obj.DefaultIPGateway is None: # Skip adapters without default router |
---|
73 | continue |
---|
74 | for ip in obj.IPAddress: |
---|
75 | if ':' in ip: # Is IPV6, skip this |
---|
76 | continue |
---|
77 | if ip is None or ip == '' or ip.startswith('169.254') or ip.startswith('0.'): # If single link ip, or no ip |
---|
78 | continue |
---|
79 | logger.debug('Net config found: {}=({}, {})'.format(obj.Caption, obj.MACAddress, ip)) |
---|
80 | yield utils.Bunch(name=obj.Caption, mac=obj.MACAddress, ip=ip) |
---|
81 | except Exception: |
---|
82 | return |
---|
83 | |
---|
84 | |
---|
85 | def getDomainName(): |
---|
86 | ''' |
---|
87 | Will return the domain name if we belong a domain, else None |
---|
88 | (if part of a network group, will also return None) |
---|
89 | ''' |
---|
90 | # Status: |
---|
91 | # 0 = Unknown |
---|
92 | # 1 = Unjoined |
---|
93 | # 2 = Workgroup |
---|
94 | # 3 = Domain |
---|
95 | domain, status = win32net.NetGetJoinInformation() |
---|
96 | if status != 3: |
---|
97 | domain = None |
---|
98 | |
---|
99 | return domain |
---|
100 | |
---|
101 | |
---|
102 | def getWindowsVersion(): |
---|
103 | ''' |
---|
104 | Returns Windows version. |
---|
105 | ''' |
---|
106 | import winreg |
---|
107 | reg = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion') |
---|
108 | try: |
---|
109 | data = '{} {}'.format(winreg.QueryValueEx(reg, 'ProductName')[0], winreg.QueryValueEx(reg, 'ReleaseId')[0]) |
---|
110 | except Exception: |
---|
111 | data = '{} {}'.format(winreg.QueryValueEx(reg, 'ProductName')[0], winreg.QueryValueEx(reg, 'CurrentBuildNumber')[0]) |
---|
112 | reg.Close() |
---|
113 | return data |
---|
114 | |
---|
115 | |
---|
116 | EWX_LOGOFF = 0x00000000 |
---|
117 | EWX_SHUTDOWN = 0x00000001 |
---|
118 | EWX_REBOOT = 0x00000002 |
---|
119 | EWX_FORCE = 0x00000004 |
---|
120 | EWX_POWEROFF = 0x00000008 |
---|
121 | EWX_FORCEIFHUNG = 0x00000010 |
---|
122 | |
---|
123 | |
---|
124 | def reboot(flags=EWX_FORCEIFHUNG | EWX_REBOOT): |
---|
125 | hproc = win32api.GetCurrentProcess() |
---|
126 | htok = win32security.OpenProcessToken(hproc, win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY) |
---|
127 | privs = ((win32security.LookupPrivilegeValue(None, win32security.SE_SHUTDOWN_NAME), win32security.SE_PRIVILEGE_ENABLED),) |
---|
128 | win32security.AdjustTokenPrivileges(htok, 0, privs) |
---|
129 | win32api.ExitWindowsEx(flags, 0) |
---|
130 | |
---|
131 | def poweroff(flags=0): |
---|
132 | ''' |
---|
133 | Simple poweroff command. |
---|
134 | ''' |
---|
135 | reboot(flags=EWX_FORCEIFHUNG | EWX_SHUTDOWN) |
---|
136 | |
---|
137 | def logoff(): |
---|
138 | win32api.ExitWindowsEx(EWX_LOGOFF) |
---|
139 | |
---|
140 | |
---|
141 | def renameComputer(newName): |
---|
142 | # Needs admin privileges to work |
---|
143 | if ctypes.windll.kernel32.SetComputerNameExW(DWORD(win32con.ComputerNamePhysicalDnsHostname), LPCWSTR(newName)) == 0: # @UndefinedVariable |
---|
144 | # win32api.FormatMessage -> returns error string |
---|
145 | # win32api.GetLastError -> returns error code |
---|
146 | # (just put this comment here to remember to log this when logger is available) |
---|
147 | error = getErrorMessage() |
---|
148 | computerName = win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname) |
---|
149 | raise Exception('Error renaming computer from {} to {}: {}'.format(computerName, newName, error)) |
---|
150 | |
---|
151 | |
---|
152 | NETSETUP_JOIN_DOMAIN = 0x00000001 |
---|
153 | NETSETUP_ACCT_CREATE = 0x00000002 |
---|
154 | NETSETUP_ACCT_DELETE = 0x00000004 |
---|
155 | NETSETUP_WIN9X_UPGRADE = 0x00000010 |
---|
156 | NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x00000020 |
---|
157 | NETSETUP_JOIN_UNSECURE = 0x00000040 |
---|
158 | NETSETUP_MACHINE_PWD_PASSED = 0x00000080 |
---|
159 | NETSETUP_JOIN_WITH_NEW_NAME = 0x00000400 |
---|
160 | NETSETUP_DEFER_SPN_SET = 0x1000000 |
---|
161 | |
---|
162 | |
---|
163 | def joinDomain(domain, ou, account, password, executeInOneStep=False): |
---|
164 | ''' |
---|
165 | Joins machine to a windows domain |
---|
166 | :param domain: Domain to join to |
---|
167 | :param ou: Ou that will hold machine |
---|
168 | :param account: Account used to join domain |
---|
169 | :param password: Password of account used to join domain |
---|
170 | :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. |
---|
171 | ''' |
---|
172 | # If account do not have domain, include it |
---|
173 | if '@' not in account and '\\' not in account: |
---|
174 | if '.' in domain: |
---|
175 | account = account + '@' + domain |
---|
176 | else: |
---|
177 | account = domain + '\\' + account |
---|
178 | |
---|
179 | # Do log |
---|
180 | flags = NETSETUP_ACCT_CREATE | NETSETUP_DOMAIN_JOIN_IF_JOINED | NETSETUP_JOIN_DOMAIN |
---|
181 | |
---|
182 | if executeInOneStep: |
---|
183 | flags |= NETSETUP_JOIN_WITH_NEW_NAME |
---|
184 | |
---|
185 | flags = DWORD(flags) |
---|
186 | |
---|
187 | domain = LPCWSTR(domain) |
---|
188 | |
---|
189 | # Must be in format "ou=.., ..., dc=...," |
---|
190 | ou = LPCWSTR(ou) if ou is not None and ou != '' else None |
---|
191 | account = LPCWSTR(account) |
---|
192 | password = LPCWSTR(password) |
---|
193 | |
---|
194 | res = ctypes.windll.netapi32.NetJoinDomain(None, domain, ou, account, password, flags) |
---|
195 | # Machine found in another ou, use it and warn this on log |
---|
196 | if res == 2224: |
---|
197 | flags = DWORD(NETSETUP_DOMAIN_JOIN_IF_JOINED | NETSETUP_JOIN_DOMAIN) |
---|
198 | res = ctypes.windll.netapi32.NetJoinDomain(None, domain, None, account, password, flags) |
---|
199 | if res != 0: |
---|
200 | # Log the error |
---|
201 | error = getErrorMessage(res) |
---|
202 | if res == 1355: |
---|
203 | error = "DC Is not reachable" |
---|
204 | print('{} {}'.format(res, error)) |
---|
205 | 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)) |
---|
206 | |
---|
207 | |
---|
208 | def changeUserPassword(user, oldPassword, newPassword): |
---|
209 | computerName = LPCWSTR(getComputerName()) |
---|
210 | user = LPCWSTR(user) |
---|
211 | oldPassword = LPCWSTR(oldPassword) |
---|
212 | newPassword = LPCWSTR(newPassword) |
---|
213 | |
---|
214 | res = ctypes.windll.netapi32.NetUserChangePassword(computerName, user, oldPassword, newPassword) |
---|
215 | |
---|
216 | if res != 0: |
---|
217 | # Log the error, and raise exception to parent |
---|
218 | error = getErrorMessage() |
---|
219 | raise Exception('Error changing password for user {}: {}'.format(user.value, error)) |
---|
220 | |
---|
221 | |
---|
222 | class LASTINPUTINFO(ctypes.Structure): |
---|
223 | _fields_ = [ |
---|
224 | ('cbSize', ctypes.c_uint), |
---|
225 | ('dwTime', ctypes.c_uint), |
---|
226 | ] |
---|
227 | |
---|
228 | |
---|
229 | def initIdleDuration(atLeastSeconds): |
---|
230 | ''' |
---|
231 | In windows, there is no need to set screensaver |
---|
232 | ''' |
---|
233 | pass |
---|
234 | |
---|
235 | |
---|
236 | def getIdleDuration(): |
---|
237 | lastInputInfo = LASTINPUTINFO() |
---|
238 | lastInputInfo.cbSize = ctypes.sizeof(lastInputInfo) |
---|
239 | ctypes.windll.user32.GetLastInputInfo(ctypes.byref(lastInputInfo)) |
---|
240 | millis = ctypes.windll.kernel32.GetTickCount() - lastInputInfo.dwTime # @UndefinedVariable |
---|
241 | return millis / 1000.0 |
---|
242 | |
---|
243 | |
---|
244 | def getCurrentUser(): |
---|
245 | ''' |
---|
246 | Returns current logged in username |
---|
247 | ''' |
---|
248 | return os.environ['USERNAME'] |
---|
249 | |
---|
250 | |
---|
251 | def getSessionLanguage(): |
---|
252 | ''' |
---|
253 | Returns the user's session language |
---|
254 | ''' |
---|
255 | return locale.getdefaultlocale()[0] |
---|
256 | |
---|
257 | |
---|
258 | def get_session_type(): |
---|
259 | """ |
---|
260 | returns the user's session type (Local session, RDP,...) |
---|
261 | :return: string |
---|
262 | """ |
---|
263 | return os.environ.get('SESSIONNAME').lower() |
---|
264 | |
---|
265 | |
---|
266 | def showPopup(title, message): |
---|
267 | ''' |
---|
268 | Displays a message box on user's session (during 1 min). |
---|
269 | ''' |
---|
270 | 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) |
---|
271 | |
---|
272 | |
---|
273 | def get_etc_path(): |
---|
274 | """ |
---|
275 | :return: |
---|
276 | Returns etc directory path. |
---|
277 | """ |
---|
278 | return os.path.join('C:', os.sep, 'Windows', 'System32', 'drivers', 'etc') |
---|
279 | |
---|
280 | |
---|
281 | def build_popen_args(script): |
---|
282 | ## turn the script into utf16le, then to b64 again, and feed the blob to powershell |
---|
283 | u16 = script.encode ('utf-16le') ## utf16 |
---|
284 | b64 = base64.b64encode (u16).decode ('utf-8') ## b64 (which returns bytes, so we need an additional decode(utf8)) |
---|
285 | return ['powershell', '-WindowStyle', 'Hidden', '-EncodedCommand', b64] |
---|