source: admin/Sources/Clients/ogagent/src/opengnsys/windows/operations.py @ 1985678

918-git-images-111dconfigfileconfigure-oglivegit-imageslgromero-new-oglivemainmaint-cronmount-efivarfsmultivmmultivm-ogboot-installerogClonningEngineogboot-installer-jenkinsoglive-ipv6test-python-scriptsticket-301ticket-50ticket-50-oldticket-577ticket-585ticket-611ticket-612ticket-693ticket-700ubu24tplunification2use-local-agent-oglivevarios-instalacionwebconsole3
Last change on this file since 1985678 was 703551b3, checked in by Ramón M. Gómez <ramongomez@…>, 6 years ago

#877: Copy hosts file on OGAgent activation, and some code cleanup.

  • Property mode set to 100644
File size: 9.6 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    '''
103    Returns Windows version.
104    '''
105    import _winreg
106    reg = _winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion')
107    try:
108        data = '{} {}'.format(_winreg.QueryValueEx(reg, 'ProductName')[0], _winreg.QueryValueEx(reg, 'ReleaseId')[0])
109    except Exception:
110        data = '{} {}'.format(_winreg.QueryValueEx(reg, 'ProductName')[0], _winreg.QueryValueEx(reg, 'CurrentBuildNumber')[0])
111    reg.Close()
112    return data
113
114
115EWX_LOGOFF = 0x00000000
116EWX_SHUTDOWN = 0x00000001
117EWX_REBOOT = 0x00000002
118EWX_FORCE = 0x00000004
119EWX_POWEROFF = 0x00000008
120EWX_FORCEIFHUNG = 0x00000010
121
122
123def reboot(flags=EWX_FORCEIFHUNG | EWX_REBOOT):
124    hproc = win32api.GetCurrentProcess()
125    htok = win32security.OpenProcessToken(hproc, win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY)
126    privs = ((win32security.LookupPrivilegeValue(None, win32security.SE_SHUTDOWN_NAME), win32security.SE_PRIVILEGE_ENABLED),)
127    win32security.AdjustTokenPrivileges(htok, 0, privs)
128    win32api.ExitWindowsEx(flags, 0)
129
130def poweroff(flags=0):
131    '''
132    Simple poweroff command.
133    '''
134    reboot(flags=EWX_FORCEIFHUNG | EWX_SHUTDOWN)
135
136def logoff():
137    win32api.ExitWindowsEx(EWX_LOGOFF)
138
139
140def renameComputer(newName):
141    # Needs admin privileges to work
142    if ctypes.windll.kernel32.SetComputerNameExW(DWORD(win32con.ComputerNamePhysicalDnsHostname), LPCWSTR(newName)) == 0:  # @UndefinedVariable
143        # win32api.FormatMessage -> returns error string
144        # win32api.GetLastError -> returns error code
145        # (just put this comment here to remember to log this when logger is available)
146        error = getErrorMessage()
147        computerName = win32api.GetComputerNameEx(win32con.ComputerNamePhysicalDnsHostname)
148        raise Exception('Error renaming computer from {} to {}: {}'.format(computerName, newName, error))
149
150
151NETSETUP_JOIN_DOMAIN = 0x00000001
152NETSETUP_ACCT_CREATE = 0x00000002
153NETSETUP_ACCT_DELETE = 0x00000004
154NETSETUP_WIN9X_UPGRADE = 0x00000010
155NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x00000020
156NETSETUP_JOIN_UNSECURE = 0x00000040
157NETSETUP_MACHINE_PWD_PASSED = 0x00000080
158NETSETUP_JOIN_WITH_NEW_NAME = 0x00000400
159NETSETUP_DEFER_SPN_SET = 0x1000000
160
161
162def joinDomain(domain, ou, account, password, executeInOneStep=False):
163    '''
164    Joins machine to a windows domain
165    :param domain: Domain to join to
166    :param ou: Ou that will hold machine
167    :param account: Account used to join domain
168    :param password: Password of account used to join domain
169    :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.
170    '''
171    # If account do not have domain, include it
172    if '@' not in account and '\\' not in account:
173        if '.' in domain:
174            account = account + '@' + domain
175        else:
176            account = domain + '\\' + account
177
178    # Do log
179    flags = NETSETUP_ACCT_CREATE | NETSETUP_DOMAIN_JOIN_IF_JOINED | NETSETUP_JOIN_DOMAIN
180
181    if executeInOneStep:
182        flags |= NETSETUP_JOIN_WITH_NEW_NAME
183
184    flags = DWORD(flags)
185
186    domain = LPCWSTR(domain)
187
188    # Must be in format "ou=.., ..., dc=...,"
189    ou = LPCWSTR(ou) if ou is not None and ou != '' else None
190    account = LPCWSTR(account)
191    password = LPCWSTR(password)
192
193    res = ctypes.windll.netapi32.NetJoinDomain(None, domain, ou, account, password, flags)
194    # Machine found in another ou, use it and warn this on log
195    if res == 2224:
196        flags = DWORD(NETSETUP_DOMAIN_JOIN_IF_JOINED | NETSETUP_JOIN_DOMAIN)
197        res = ctypes.windll.netapi32.NetJoinDomain(None, domain, None, account, password, flags)
198    if res != 0:
199        # Log the error
200        error = getErrorMessage(res)
201        if res == 1355:
202            error = "DC Is not reachable"
203        print('{} {}'.format(res, error))
204        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))
205
206
207def changeUserPassword(user, oldPassword, newPassword):
208    computerName = LPCWSTR(getComputerName())
209    user = LPCWSTR(user)
210    oldPassword = LPCWSTR(oldPassword)
211    newPassword = LPCWSTR(newPassword)
212
213    res = ctypes.windll.netapi32.NetUserChangePassword(computerName, user, oldPassword, newPassword)
214
215    if res != 0:
216        # Log the error, and raise exception to parent
217        error = getErrorMessage()
218        raise Exception('Error changing password for user {}: {}'.format(user.value, error))
219
220
221class LASTINPUTINFO(ctypes.Structure):
222    _fields_ = [
223        ('cbSize', ctypes.c_uint),
224        ('dwTime', ctypes.c_uint),
225    ]
226
227
228def initIdleDuration(atLeastSeconds):
229    '''
230    In windows, there is no need to set screensaver
231    '''
232    pass
233
234
235def getIdleDuration():
236    lastInputInfo = LASTINPUTINFO()
237    lastInputInfo.cbSize = ctypes.sizeof(lastInputInfo)
238    ctypes.windll.user32.GetLastInputInfo(ctypes.byref(lastInputInfo))
239    millis = ctypes.windll.kernel32.GetTickCount() - lastInputInfo.dwTime  # @UndefinedVariable
240    return millis / 1000.0
241
242
243def getCurrentUser():
244    '''
245    Returns current logged in username
246    '''
247    return os.environ['USERNAME']
248
249
250def getSessionLanguage():
251    '''
252    Returns the user's session language
253    '''
254    return locale.getdefaultlocale()[0]
255
256
257def showPopup(title, message):
258    '''
259    Displays a message box on user's session (during 1 min).
260    '''
261    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)
262
263
264def get_etc_path():
265    """
266    :return:
267    Returns etc directory path.
268    """
269    return os.path.join('C:', os.sep, 'Windows', 'System32', 'drivers', 'etc')
Note: See TracBrowser for help on using the repository browser.