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

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

#718: Corregir errata de revisión r5029.

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

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