source: admin/Sources/Clients/ogagent/src/opengnsys/macos/operations.py @ 2d39301

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 2d39301 was 029ff6d, checked in by ramon <ramongomez@…>, 8 years ago

#718: Revisar documentación y proceso de intalación de OGAgent; actualizar comandos de OGAgent para macOS.

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

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