source: ogAgent-Git/src/opengnsys/macos/operations.py @ 909a626

configure-ptt-chedecorare-oglive-methodsejecutarscript-b64fix-cfg2objfixes-winlgromero-filebeatmainmodulesnew-browserno-ptt-paramogadmcliogadmclient-statusogagent-jobsogagent-macosogcore1oglogoglog2override-moduleping1ping2ping3ping4py3-winpython3report-progresstlsunification2unification3versionswindows-fixes
Last change on this file since 909a626 was 53e7d45, checked in by Ramón M. Gómez <ramongomez@…>, 5 years ago

#940: Run 2to3 on OGAgent source code

Result after running the command: 2to3 -w ogagent/src

  • Property mode set to 100644
File size: 7.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'''
32
33
34import socket
35import platform
36import fcntl
37import os
38import locale
39import ctypes  # @UnusedImport
40import ctypes.util
41import subprocess
42import struct
43import array
44import six
45from opengnsys import utils
46import netifaces
47
48
49def _getMacAddr(ifname):
50    '''
51    Returns the mac address of an interface
52    Mac is returned as unicode utf-8 encoded
53    '''
54    if isinstance(ifname, list):
55        return dict([(name, _getMacAddr(name)) for name in ifname])
56    if isinstance(ifname, six.text_type):
57        ifname = ifname.encode('utf-8')  # If unicode, convert to bytes (or str in python 2.7)
58    try:
59        return netifaces.ifaddresses(ifname)[18][0]['addr']
60    except Exception:
61        return None
62
63
64def _getIpAddr(ifname):
65    '''
66    Returns the IP address of an interface
67    IP is returned as unicode utf-8 encoded
68    '''
69    if isinstance(ifname, list):
70        return dict([(name, _getIpAddr(name)) for name in ifname])
71    if isinstance(ifname, six.text_type):
72        ifname = ifname.encode('utf-8')  # If unicode, convert to bytes (or str in python 2.7)
73    try:
74        return netifaces.ifaddresses(ifname)[2][0]['addr']
75    except Exception:
76        return None
77
78
79def _getInterfaces():
80    '''
81    Returns a list of interfaces names
82    '''
83    return netifaces.interfaces()
84
85
86def _getIpAndMac(ifname):
87    ip, mac = _getIpAddr(ifname), _getMacAddr(ifname)
88    return (ip, mac)
89
90
91def getComputerName():
92    '''
93    Returns computer name, with no domain
94    '''
95    return socket.gethostname().split('.')[0]
96
97
98def getNetworkInfo():
99    '''
100    Obtains a list of network interfaces
101    @return: A "generator" of elements, that are dict-as-object, with this elements:
102      name: Name of the interface
103      mac: mac of the interface
104      ip: ip of the interface
105    '''
106    for ifname in _getInterfaces():
107        ip, mac = _getIpAndMac(ifname)
108        if mac != None and ip != None:  # Skips local interfaces
109            yield utils.Bunch(name=ifname, mac=mac, ip=ip)
110
111
112def getDomainName():
113    return ''
114
115
116def getMacosVersion():
117    return 'macOS {}'.format(platform.mac_ver()[0])
118
119
120def reboot(flags=0):
121    '''
122    Simple reboot command
123    '''
124    # Workaround for dummy thread
125    if six.PY3 is False:
126        import threading
127        threading._DummyThread._Thread__stop = lambda x: 42
128
129    # Exec reboot command
130    subprocess.call('/sbin/shutdown -r now', shell=True)
131
132
133def poweroff(flags=0):
134    '''
135    Simple poweroff command
136    '''
137    # Workaround for dummy thread
138    if six.PY3 is False:
139        import threading
140        threading._DummyThread._Thread__stop = lambda x: 42
141
142    # Exec shutdown command
143    subprocess.call('/sbin/shutdown -h now', shell=True)
144
145
146def logoff():
147    '''
148    Simple logout using AppleScript
149    '''
150    # Workaround for dummy thread
151    if six.PY3 is False:
152        import threading
153        threading._DummyThread._Thread__stop = lambda x: 42
154
155    # Exec logout using AppleSctipt
156    subprocess.call('/usr/bin/osascript -e \'tell app "System Events" to «event aevtrlgo»\'', shell=True)
157
158
159def renameComputer(newName):
160    rename(newName)
161
162
163def joinDomain(domain, ou, account, password, executeInOneStep=False):
164    pass
165
166
167def changeUserPassword(user, oldPassword, newPassword):
168    '''
169    Simple password change for user using command line
170    '''
171    os.system('echo "{1}\n{1}" | /usr/bin/passwd {0} 2> /dev/null'.format(user, newPassword))
172
173
174class XScreenSaverInfo(ctypes.Structure):
175    _fields_ = [('window', ctypes.c_long),
176                ('state', ctypes.c_int),
177                ('kind', ctypes.c_int),
178                ('til_or_since', ctypes.c_ulong),
179                ('idle', ctypes.c_ulong),
180                ('eventMask', ctypes.c_ulong)]
181
182# Initialize xlib & xss
183try:
184    xlibPath = ctypes.util.find_library('X11')
185    xssPath = ctypes.util.find_library('Xss')
186    xlib = ctypes.cdll.LoadLibrary(xlibPath)
187    xss = ctypes.cdll.LoadLibrary(xssPath)
188
189    # Fix result type to XScreenSaverInfo Structure
190    xss.XScreenSaverQueryExtension.restype = ctypes.c_int
191    xss.XScreenSaverAllocInfo.restype = ctypes.POINTER(XScreenSaverInfo)  # Result in a XScreenSaverInfo structure
192except Exception:  # Libraries not accesible, not found or whatever..
193    xlib = xss = None
194
195
196def initIdleDuration(atLeastSeconds):
197    '''
198    On linux we set the screensaver to at least required seconds, or we never will get "idle"
199    '''
200    # Workaround for dummy thread
201    if six.PY3 is False:
202        import threading
203        threading._DummyThread._Thread__stop = lambda x: 42
204
205    subprocess.call(['/usr/bin/xset', 's', '{}'.format(atLeastSeconds + 30)])
206    # And now reset it
207    subprocess.call(['/usr/bin/xset', 's', 'reset'])
208
209
210def getIdleDuration():
211    '''
212    Returns idle duration, in seconds
213    '''
214    if xlib is None or xss is None:
215        return 0  # Libraries not available
216
217    # production code might want to not hardcode the offset 16...
218    display = xlib.XOpenDisplay(None)
219
220    event_base = ctypes.c_int()
221    error_base = ctypes.c_int()
222
223    available = xss.XScreenSaverQueryExtension(display, ctypes.byref(event_base), ctypes.byref(error_base))
224    if available != 1:
225        return 0  # No screen saver is available, no way of getting idle
226
227    info = xss.XScreenSaverAllocInfo()
228    xss.XScreenSaverQueryInfo(display, xlib.XDefaultRootWindow(display), info)
229
230    if info.contents.state != 0:
231        return 3600 * 100 * 1000  # If screen saver is active, return a high enough value
232
233    return info.contents.idle / 1000.0
234
235
236def getCurrentUser():
237    '''
238    Returns current logged in user
239    '''
240    return os.environ['USER']
241
242
243def getSessionLanguage():
244    '''
245    Returns the user's session language
246    '''
247    return locale.getdefaultlocale()[0]
248
249
250def showPopup(title, message):
251    '''
252    Displays a message box on user's session (during 1 min).
253    '''
254    # Show a dialog using AppleSctipt
255    return subprocess.call('/usr/bin/osascript -e \'display notification "{}" with title "{}"\''.format(message, title), shell=True)
256
257
258def get_etc_path():
259    """
260    :return:
261    Returns etc directory path.
262    """
263    return os.sep + 'etc'
Note: See TracBrowser for help on using the repository browser.