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

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 4e12ae6 was c3e7c06, checked in by ramon <ramongomez@…>, 9 years ago

#718: Integrar código fuente de agente OGAgent en rama de desarrollo.

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

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