source: admin/Sources/Clients/ogagent/src/opengnsys/macos/operations.py @ 744d192

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 744d192 was 744d192, checked in by ramon <ramongomez@…>, 8 years ago

#718: Preparar OGAgent para macOS a partir del código de Linux.

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

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