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

decorare-oglive-methodsfix-urlfixes-winlgromero-filebeatmainmodulesnew-browserno-ptt-paramogadmcliogadmclient-statusogagent-jobsogagent-macosogcore1ogliveoglogoglog2override-moduleping1ping2ping3ping4py3-winpython3qndtestreport-progresssched-tasktlsunification2unification3versionswindows-fixes
Last change on this file since e21cba1 was e21cba1, checked in by ramon <ramongomez@…>, 8 years ago

#718: Corregir errata en servicio de usuario de OGAgent; usar flag EWX_SHUTDOWN en vez de EWX_POWEROFF al apagar Windows para compatibilidad con Wake-on-Lan.

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

  • Property mode set to 100644
File size: 8.8 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 subprocess
36import ctypes
37from ctypes.wintypes import DWORD, LPCWSTR
38import win32com.client  # @UnresolvedImport, pylint: disable=import-error
39import win32net  # @UnresolvedImport, pylint: disable=import-error
40import win32security  # @UnresolvedImport, pylint: disable=import-error
41import win32api  # @UnresolvedImport, pylint: disable=import-error
42import win32con  # @UnresolvedImport, pylint: disable=import-error
43
44from opengnsys import utils
45from opengnsys.log import logger
46
47
48def getErrorMessage(res=0):
49    msg = win32api.FormatMessage(res)
50    return msg.decode('windows-1250', 'ignore')
51
52
53def getComputerName():
54    return win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname)
55
56
57def getNetworkInfo():
58    '''
59    Obtains a list of network interfaces
60    @return: A "generator" of elements, that are dict-as-object, with this elements:
61      name: Name of the interface
62      mac: mac of the interface
63      ip: ip of the interface
64    '''
65    obj = win32com.client.Dispatch("WbemScripting.SWbemLocator")
66    wmobj = obj.ConnectServer("localhost", "root\cimv2")
67    adapters = wmobj.ExecQuery("Select * from Win32_NetworkAdapterConfiguration where IpEnabled=True")
68    try:
69        for obj in adapters:
70            if obj.DefaultIPGateway is None:   # Skip adapters without default router
71                continue
72            for ip in obj.IPAddress:
73                if ':' in ip:  # Is IPV6, skip this
74                    continue
75                if ip is None or ip == '' or ip.startswith('169.254') or ip.startswith('0.'):  # If single link ip, or no ip
76                    continue
77                logger.debug('Net config found: {}=({}, {})'.format(obj.Caption, obj.MACAddress, ip))
78                yield utils.Bunch(name=obj.Caption, mac=obj.MACAddress, ip=ip)
79    except Exception:
80        return
81
82
83def getDomainName():
84    '''
85    Will return the domain name if we belong a domain, else None
86    (if part of a network group, will also return None)
87    '''
88    # Status:
89    # 0 = Unknown
90    # 1 = Unjoined
91    # 2 = Workgroup
92    # 3 = Domain
93    domain, status = win32net.NetGetJoinInformation()
94    if status != 3:
95        domain = None
96
97    return domain
98
99
100def getWindowsVersion():
101    return win32api.GetVersionEx()
102
103EWX_LOGOFF = 0x00000000
104EWX_SHUTDOWN = 0x00000001
105EWX_REBOOT = 0x00000002
106EWX_FORCE = 0x00000004
107EWX_POWEROFF = 0x00000008
108EWX_FORCEIFHUNG = 0x00000010
109
110
111def reboot(flags=EWX_FORCEIFHUNG | EWX_REBOOT):
112    hproc = win32api.GetCurrentProcess()
113    htok = win32security.OpenProcessToken(hproc, win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY)
114    privs = ((win32security.LookupPrivilegeValue(None, win32security.SE_SHUTDOWN_NAME), win32security.SE_PRIVILEGE_ENABLED),)
115    win32security.AdjustTokenPrivileges(htok, 0, privs)
116    win32api.ExitWindowsEx(flags, 0)
117
118def poweroff(flags=0):
119    '''
120    Simple poweroff command.
121    '''
122    reboot(flags=EWX_FORCEIFHUNG | EWX_SHUTDOWN)
123
124def logoff():
125    win32api.ExitWindowsEx(EWX_LOGOFF)
126
127
128def renameComputer(newName):
129    # Needs admin privileges to work
130    if ctypes.windll.kernel32.SetComputerNameExW(DWORD(win32con.ComputerNamePhysicalDnsHostname), LPCWSTR(newName)) == 0:  # @UndefinedVariable
131        # win32api.FormatMessage -> returns error string
132        # win32api.GetLastError -> returns error code
133        # (just put this comment here to remember to log this when logger is available)
134        error = getErrorMessage()
135        computerName = win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname)
136        raise Exception('Error renaming computer from {} to {}: {}'.format(computerName, newName, error))
137
138NETSETUP_JOIN_DOMAIN = 0x00000001
139NETSETUP_ACCT_CREATE = 0x00000002
140NETSETUP_ACCT_DELETE = 0x00000004
141NETSETUP_WIN9X_UPGRADE = 0x00000010
142NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x00000020
143NETSETUP_JOIN_UNSECURE = 0x00000040
144NETSETUP_MACHINE_PWD_PASSED = 0x00000080
145NETSETUP_JOIN_WITH_NEW_NAME = 0x00000400
146NETSETUP_DEFER_SPN_SET = 0x1000000
147
148
149def joinDomain(domain, ou, account, password, executeInOneStep=False):
150    '''
151    Joins machine to a windows domain
152    :param domain: Domain to join to
153    :param ou: Ou that will hold machine
154    :param account: Account used to join domain
155    :param password: Password of account used to join domain
156    :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.
157    '''
158    # If account do not have domain, include it
159    if '@' not in account and '\\' not in account:
160        if '.' in domain:
161            account = account + '@' + domain
162        else:
163            account = domain + '\\' + account
164
165    # Do log
166    flags = NETSETUP_ACCT_CREATE | NETSETUP_DOMAIN_JOIN_IF_JOINED | NETSETUP_JOIN_DOMAIN
167
168    if executeInOneStep:
169        flags |= NETSETUP_JOIN_WITH_NEW_NAME
170
171    flags = DWORD(flags)
172
173    domain = LPCWSTR(domain)
174
175    # Must be in format "ou=.., ..., dc=...,"
176    ou = LPCWSTR(ou) if ou is not None and ou != '' else None
177    account = LPCWSTR(account)
178    password = LPCWSTR(password)
179
180    res = ctypes.windll.netapi32.NetJoinDomain(None, domain, ou, account, password, flags)
181    # Machine found in another ou, use it and warn this on log
182    if res == 2224:
183        flags = DWORD(NETSETUP_DOMAIN_JOIN_IF_JOINED | NETSETUP_JOIN_DOMAIN)
184        res = ctypes.windll.netapi32.NetJoinDomain(None, domain, None, account, password, flags)
185    if res != 0:
186        # Log the error
187        error = getErrorMessage(res)
188        if res == 1355:
189            error = "DC Is not reachable"
190        print('{} {}'.format(res, error))
191        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))
192
193
194def changeUserPassword(user, oldPassword, newPassword):
195    computerName = LPCWSTR(getComputerName())
196    user = LPCWSTR(user)
197    oldPassword = LPCWSTR(oldPassword)
198    newPassword = LPCWSTR(newPassword)
199
200    res = ctypes.windll.netapi32.NetUserChangePassword(computerName, user, oldPassword, newPassword)
201
202    if res != 0:
203        # Log the error, and raise exception to parent
204        error = getErrorMessage()
205        raise Exception('Error changing password for user {}: {}'.format(user.value, error))
206
207
208class LASTINPUTINFO(ctypes.Structure):
209    _fields_ = [
210        ('cbSize', ctypes.c_uint),
211        ('dwTime', ctypes.c_uint),
212    ]
213
214
215def initIdleDuration(atLeastSeconds):
216    '''
217    In windows, there is no need to set screensaver
218    '''
219    pass
220
221
222def getIdleDuration():
223    lastInputInfo = LASTINPUTINFO()
224    lastInputInfo.cbSize = ctypes.sizeof(lastInputInfo)
225    ctypes.windll.user32.GetLastInputInfo(ctypes.byref(lastInputInfo))
226    millis = ctypes.windll.kernel32.GetTickCount() - lastInputInfo.dwTime  # @UndefinedVariable
227    return millis / 1000.0
228
229
230def getCurrentUser():
231    '''
232    Returns current logged in username
233    '''
234    return os.environ['USERNAME']
235
236def showPopup(title, message):
237    '''
238    Displays a message box on user's session (during 1 min).
239    '''
240    return subprocess.call('mshta "javascript:var sh=new ActiveXObject(\'WScript.Shell\'); sh.Popup( \'{}\', 60, \'{}\', 64); close()"'.format(message, title), shell=True)
241
Note: See TracBrowser for help on using the repository browser.