source: ogAgent-Git/src/opengnsys/windows/operations.py @ 0cadbf3

configure-ptt-chedecorare-oglive-methodsejecutarscript-b64fix-cfg2objfixes-winlgromero-filebeatmainmodulesnew-browserno-ptt-paramogadmclient-statusogcore1oglogoglog2override-moduleping1ping2ping3ping4report-progresstlsunification2unification3
Last change on this file since 0cadbf3 was 8c6a652, checked in by Natalia Serrano <natalia.serrano@…>, 9 months ago

refs #500 #501 #502 implement job manager

  • Property mode set to 100644
File size: 10.1 KB
Line 
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'''
32from __future__ import unicode_literals
33
34import os
35import locale
36import subprocess
37import ctypes
38import base64
39from ctypes.wintypes import DWORD, LPCWSTR
40import win32com.client  # @UnresolvedImport, pylint: disable=import-error
41import win32net  # @UnresolvedImport, pylint: disable=import-error
42import win32security  # @UnresolvedImport, pylint: disable=import-error
43import win32api  # @UnresolvedImport, pylint: disable=import-error
44import win32con  # @UnresolvedImport, pylint: disable=import-error
45
46from opengnsys import utils
47from opengnsys.log import logger
48
49
50def getErrorMessage(res=0):
51    msg = win32api.FormatMessage(res)
52    return msg.decode('windows-1250', 'ignore')
53
54
55def getComputerName():
56    return win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname)
57
58
59def 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
85def 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
102def 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
116EWX_LOGOFF = 0x00000000
117EWX_SHUTDOWN = 0x00000001
118EWX_REBOOT = 0x00000002
119EWX_FORCE = 0x00000004
120EWX_POWEROFF = 0x00000008
121EWX_FORCEIFHUNG = 0x00000010
122
123
124def 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
131def poweroff(flags=0):
132    '''
133    Simple poweroff command.
134    '''
135    reboot(flags=EWX_FORCEIFHUNG | EWX_SHUTDOWN)
136
137def logoff():
138    win32api.ExitWindowsEx(EWX_LOGOFF)
139
140
141def 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
152NETSETUP_JOIN_DOMAIN = 0x00000001
153NETSETUP_ACCT_CREATE = 0x00000002
154NETSETUP_ACCT_DELETE = 0x00000004
155NETSETUP_WIN9X_UPGRADE = 0x00000010
156NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x00000020
157NETSETUP_JOIN_UNSECURE = 0x00000040
158NETSETUP_MACHINE_PWD_PASSED = 0x00000080
159NETSETUP_JOIN_WITH_NEW_NAME = 0x00000400
160NETSETUP_DEFER_SPN_SET = 0x1000000
161
162
163def 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
208def 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
222class LASTINPUTINFO(ctypes.Structure):
223    _fields_ = [
224        ('cbSize', ctypes.c_uint),
225        ('dwTime', ctypes.c_uint),
226    ]
227
228
229def initIdleDuration(atLeastSeconds):
230    '''
231    In windows, there is no need to set screensaver
232    '''
233    pass
234
235
236def 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
244def getCurrentUser():
245    '''
246    Returns current logged in username
247    '''
248    return os.environ['USERNAME']
249
250
251def getSessionLanguage():
252    '''
253    Returns the user's session language
254    '''
255    return locale.getdefaultlocale()[0]
256
257
258def 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
266def 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
273def 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
281def 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]
Note: See TracBrowser for help on using the repository browser.