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

configure-ptt-chedecorare-oglive-methodsejecutarscript-b64fix-cfg2objfixes-winlgromero-filebeatmainno-ptt-paramogcore1oglogoglog2override-moduleping1ping2ping3ping4report-progresstls
Last change on this file since 324ffda was 1d93de1, checked in by Natalia Serrano <natalia.serrano@…>, 8 months ago

refs #531 remove unused code, bump version

  • Property mode set to 100644
File size: 5.7 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
38import base64
39from ctypes.wintypes import DWORD, LPCWSTR
40import win32com.client  # @UnresolvedImport, pylint: disable=import-error
41import win32net  # @UnresolvedImport, pylint: disable=import-error
42import win32security  # @UnresolvedImport, pylint: disable=import-error
43import win32api  # @UnresolvedImport, pylint: disable=import-error
44import win32con  # @UnresolvedImport, pylint: disable=import-error
45
46from opengnsys import utils
47from opengnsys.log import logger
48
49
50def getNetworkInfo():
51    '''
52    Obtains a list of network interfaces
53    @return: A "generator" of elements, that are dict-as-object, with this elements:
54      name: Name of the interface
55      mac: mac of the interface
56      ip: ip of the interface
57    '''
58    obj = win32com.client.Dispatch("WbemScripting.SWbemLocator")
59    wmobj = obj.ConnectServer("localhost", "root\\cimv2")
60    adapters = wmobj.ExecQuery("Select * from Win32_NetworkAdapterConfiguration where IpEnabled=True")
61    try:
62        for obj in adapters:
63            if obj.DefaultIPGateway is None:   # Skip adapters without default router
64                continue
65            for ip in obj.IPAddress:
66                if ':' in ip:  # Is IPV6, skip this
67                    continue
68                if ip is None or ip == '' or ip.startswith('169.254') or ip.startswith('0.'):  # If single link ip, or no ip
69                    continue
70                logger.debug('Net config found: {}=({}, {})'.format(obj.Caption, obj.MACAddress, ip))
71                yield utils.Bunch(name=obj.Caption, mac=obj.MACAddress, ip=ip)
72    except Exception:
73        return
74
75
76def getWindowsVersion():
77    '''
78    Returns Windows version.
79    '''
80    import winreg
81    reg = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion')
82    try:
83        data = '{} {}'.format(winreg.QueryValueEx(reg, 'ProductName')[0], winreg.QueryValueEx(reg, 'ReleaseId')[0])
84    except Exception:
85        data = '{} {}'.format(winreg.QueryValueEx(reg, 'ProductName')[0], winreg.QueryValueEx(reg, 'CurrentBuildNumber')[0])
86    reg.Close()
87    return data
88
89
90EWX_LOGOFF = 0x00000000
91EWX_SHUTDOWN = 0x00000001
92EWX_REBOOT = 0x00000002
93#EWX_FORCE = 0x00000004
94#EWX_POWEROFF = 0x00000008
95EWX_FORCEIFHUNG = 0x00000010
96
97
98def reboot(flags=EWX_FORCEIFHUNG | EWX_REBOOT):
99    hproc = win32api.GetCurrentProcess()
100    htok = win32security.OpenProcessToken(hproc, win32security.TOKEN_ADJUST_PRIVILEGES | win32security.TOKEN_QUERY)
101    privs = ((win32security.LookupPrivilegeValue(None, win32security.SE_SHUTDOWN_NAME), win32security.SE_PRIVILEGE_ENABLED),)
102    win32security.AdjustTokenPrivileges(htok, 0, privs)
103    win32api.ExitWindowsEx(flags, 0)
104
105def poweroff(flags=0):
106    '''
107    Simple poweroff command.
108    '''
109    reboot(flags=EWX_FORCEIFHUNG | EWX_SHUTDOWN)
110
111def logoff():
112    win32api.ExitWindowsEx(EWX_LOGOFF)
113
114
115def getCurrentUser():
116    '''
117    Returns current logged in username
118    '''
119    return os.environ['USERNAME']
120
121
122def getSessionLanguage():
123    '''
124    Returns the user's session language
125    '''
126    return locale.getdefaultlocale()[0]
127
128
129def get_session_type():
130    """
131    returns the user's session type (Local session, RDP,...)
132    :return: string
133    """
134    return os.environ.get('SESSIONNAME').lower()
135
136
137def showPopup(title, message):
138    '''
139    Displays a message box on user's session (during 1 min).
140    '''
141    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)
142
143
144def get_etc_path():
145    """
146    :return:
147    Returns etc directory path.
148    """
149    return os.path.join('C:', os.sep, 'Windows', 'System32', 'drivers', 'etc')
150
151
152def build_popen_args(script):
153    ## turn the script into utf16le, then to b64 again, and feed the blob to powershell
154    u16 = script.encode ('utf-16le')                 ## utf16
155    b64 = base64.b64encode (u16).decode ('utf-8')    ## b64 (which returns bytes, so we need an additional decode(utf8))
156    return ['powershell', '-WindowStyle', 'Hidden', '-EncodedCommand', b64]
Note: See TracBrowser for help on using the repository browser.