source: ogAgent-Git/src/opengnsys/windows/operations.py @ 622bc35

decorare-oglive-methodsfixes-winlgromero-filebeatmainmodulesnew-browserno-ptt-paramogadmcliogadmclient-statusogagent-jobsogagent-macosogcore1ogliveoglogoglog2override-moduleping1ping2ping3ping4py3-winpython3qndtestreport-progresstlsunification2unification3versionswindows-fixes
Last change on this file since 622bc35 was 622bc35, checked in by ramon <ramongomez@…>, 7 years ago

#708: OGAgent notifica el idioma al iniciar sesión de usuario.

git-svn-id: https://opengnsys.es/svn/branches/version1.1@5528 a21b9725-9963-47de-94b9-378ad31fedc9

  • Property mode set to 100644
File size: 9.0 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
38from ctypes.wintypes import DWORD, LPCWSTR
39import win32com.client  # @UnresolvedImport, pylint: disable=import-error
40import win32net  # @UnresolvedImport, pylint: disable=import-error
41import win32security  # @UnresolvedImport, pylint: disable=import-error
42import win32api  # @UnresolvedImport, pylint: disable=import-error
43import win32con  # @UnresolvedImport, pylint: disable=import-error
44
45from opengnsys import utils
46from opengnsys.log import logger
47
48
49def getErrorMessage(res=0):
50    msg = win32api.FormatMessage(res)
51    return msg.decode('windows-1250', 'ignore')
52
53
54def getComputerName():
55    return win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname)
56
57
58def 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
65    '''
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:
71            if obj.DefaultIPGateway is None:   # Skip adapters without default router
72                continue
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
78                logger.debug('Net config found: {}=({}, {})'.format(obj.Caption, obj.MACAddress, ip))
79                yield utils.Bunch(name=obj.Caption, mac=obj.MACAddress, ip=ip)
80    except Exception:
81        return
82
83
84def 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
101def getWindowsVersion():
102    return win32api.GetVersionEx()
103
104EWX_LOGOFF = 0x00000000
105EWX_SHUTDOWN = 0x00000001
106EWX_REBOOT = 0x00000002
107EWX_FORCE = 0x00000004
108EWX_POWEROFF = 0x00000008
109EWX_FORCEIFHUNG = 0x00000010
110
111
112def reboot(flags=EWX_FORCEIFHUNG | EWX_REBOOT):
113    hproc = win32api.GetCurrentProcess()
114    htok = win32security.OpenProcessToken(hproc, win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY)
115    privs = ((win32security.LookupPrivilegeValue(None, win32security.SE_SHUTDOWN_NAME), win32security.SE_PRIVILEGE_ENABLED),)
116    win32security.AdjustTokenPrivileges(htok, 0, privs)
117    win32api.ExitWindowsEx(flags, 0)
118
119def poweroff(flags=0):
120    '''
121    Simple poweroff command.
122    '''
123    reboot(flags=EWX_FORCEIFHUNG | EWX_SHUTDOWN)
124
125def logoff():
126    win32api.ExitWindowsEx(EWX_LOGOFF)
127
128
129def renameComputer(newName):
130    # Needs admin privileges to work
131    if ctypes.windll.kernel32.SetComputerNameExW(DWORD(win32con.ComputerNamePhysicalDnsHostname), LPCWSTR(newName)) == 0:  # @UndefinedVariable
132        # win32api.FormatMessage -> returns error string
133        # win32api.GetLastError -> returns error code
134        # (just put this comment here to remember to log this when logger is available)
135        error = getErrorMessage()
136        computerName = win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname)
137        raise Exception('Error renaming computer from {} to {}: {}'.format(computerName, newName, error))
138
139NETSETUP_JOIN_DOMAIN = 0x00000001
140NETSETUP_ACCT_CREATE = 0x00000002
141NETSETUP_ACCT_DELETE = 0x00000004
142NETSETUP_WIN9X_UPGRADE = 0x00000010
143NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x00000020
144NETSETUP_JOIN_UNSECURE = 0x00000040
145NETSETUP_MACHINE_PWD_PASSED = 0x00000080
146NETSETUP_JOIN_WITH_NEW_NAME = 0x00000400
147NETSETUP_DEFER_SPN_SET = 0x1000000
148
149
150def joinDomain(domain, ou, account, password, executeInOneStep=False):
151    '''
152    Joins machine to a windows domain
153    :param domain: Domain to join to
154    :param ou: Ou that will hold machine
155    :param account: Account used to join domain
156    :param password: Password of account used to join domain
157    :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.
158    '''
159    # If account do not have domain, include it
160    if '@' not in account and '\\' not in account:
161        if '.' in domain:
162            account = account + '@' + domain
163        else:
164            account = domain + '\\' + account
165
166    # Do log
167    flags = NETSETUP_ACCT_CREATE | NETSETUP_DOMAIN_JOIN_IF_JOINED | NETSETUP_JOIN_DOMAIN
168
169    if executeInOneStep:
170        flags |= NETSETUP_JOIN_WITH_NEW_NAME
171
172    flags = DWORD(flags)
173
174    domain = LPCWSTR(domain)
175
176    # Must be in format "ou=.., ..., dc=...,"
177    ou = LPCWSTR(ou) if ou is not None and ou != '' else None
178    account = LPCWSTR(account)
179    password = LPCWSTR(password)
180
181    res = ctypes.windll.netapi32.NetJoinDomain(None, domain, ou, account, password, flags)
182    # Machine found in another ou, use it and warn this on log
183    if res == 2224:
184        flags = DWORD(NETSETUP_DOMAIN_JOIN_IF_JOINED | NETSETUP_JOIN_DOMAIN)
185        res = ctypes.windll.netapi32.NetJoinDomain(None, domain, None, account, password, flags)
186    if res != 0:
187        # Log the error
188        error = getErrorMessage(res)
189        if res == 1355:
190            error = "DC Is not reachable"
191        print('{} {}'.format(res, error))
192        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))
193
194
195def changeUserPassword(user, oldPassword, newPassword):
196    computerName = LPCWSTR(getComputerName())
197    user = LPCWSTR(user)
198    oldPassword = LPCWSTR(oldPassword)
199    newPassword = LPCWSTR(newPassword)
200
201    res = ctypes.windll.netapi32.NetUserChangePassword(computerName, user, oldPassword, newPassword)
202
203    if res != 0:
204        # Log the error, and raise exception to parent
205        error = getErrorMessage()
206        raise Exception('Error changing password for user {}: {}'.format(user.value, error))
207
208
209class LASTINPUTINFO(ctypes.Structure):
210    _fields_ = [
211        ('cbSize', ctypes.c_uint),
212        ('dwTime', ctypes.c_uint),
213    ]
214
215
216def initIdleDuration(atLeastSeconds):
217    '''
218    In windows, there is no need to set screensaver
219    '''
220    pass
221
222
223def getIdleDuration():
224    lastInputInfo = LASTINPUTINFO()
225    lastInputInfo.cbSize = ctypes.sizeof(lastInputInfo)
226    ctypes.windll.user32.GetLastInputInfo(ctypes.byref(lastInputInfo))
227    millis = ctypes.windll.kernel32.GetTickCount() - lastInputInfo.dwTime  # @UndefinedVariable
228    return millis / 1000.0
229
230
231def getCurrentUser():
232    '''
233    Returns current logged in username
234    '''
235    return os.environ['USERNAME']
236
237
238def getSessionLanguage():
239    '''
240    Returns the user's session language
241    '''
242    return locale.getdefaultlocale()[0]
243
244
245def showPopup(title, message):
246    '''
247    Displays a message box on user's session (during 1 min).
248    '''
249    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)
Note: See TracBrowser for help on using the repository browser.