source: ogAgent-Git/src/opengnsys/linux/operations.py @ a3f2b23

oglive
Last change on this file since a3f2b23 was 983213c, checked in by Ramón M. Gómez <ramongomez@…>, 5 years ago

#750: Process to build OGAgent for ogLive package.

  • Property mode set to 100644
File size: 8.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 socket
35import platform
36import fcntl
37import os
38import locale
39import ctypes  # @UnusedImport
40import ctypes.util
41import subprocess
42import struct
43import array
44import six
45import distro
46from opengnsys import utils
47from .renamer import rename
48
49
50def _getMacAddr(ifname):
51    '''
52    Returns the mac address of an interface
53    Mac is returned as unicode utf-8 encoded
54    '''
55    if isinstance(ifname, list):
56        return dict([(name, _getMacAddr(name)) for name in ifname])
57    if isinstance(ifname, six.text_type):
58        ifname = ifname.encode('utf-8')  # If unicode, convert to bytes (or str in python 2.7)
59    try:
60        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
61        info = bytearray(fcntl.ioctl(s.fileno(), 0x8927, struct.pack(str('256s'), ifname[:15])))
62        return six.text_type(''.join(['%02x:' % char for char in info[18:24]])[:-1])
63    except Exception:
64        return None
65
66
67def _getIpAddr(ifname):
68    '''
69    Returns the ip address of an interface
70    Ip is returned as unicode utf-8 encoded
71    '''
72    if isinstance(ifname, list):
73        return dict([(name, _getIpAddr(name)) for name in ifname])
74    if isinstance(ifname, six.text_type):
75        ifname = ifname.encode('utf-8')  # If unicode, convert to bytes (or str in python 2.7)
76    try:
77        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
78        return six.text_type(socket.inet_ntoa(fcntl.ioctl(
79            s.fileno(),
80            0x8915,  # SIOCGIFADDR
81            struct.pack(str('256s'), ifname[:15])
82        )[20:24]))
83    except Exception:
84        return None
85
86
87def _getInterfaces():
88    '''
89    Returns a list of interfaces names coded in utf-8
90    '''
91    max_possible = 128  # arbitrary. raise if needed.
92    space = max_possible * 16
93    if platform.architecture()[0] == '32bit':
94        offset, length = 32, 32
95    elif platform.architecture()[0] == '64bit':
96        offset, length = 16, 40
97    else:
98        raise OSError('Unknown arquitecture {0}'.format(platform.architecture()[0]))
99
100    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
101    names = array.array(str('B'), b'\0' * space)
102    outbytes = struct.unpack(str('iL'), fcntl.ioctl(
103        s.fileno(),
104        0x8912,  # SIOCGIFCONF
105        struct.pack(str('iL'), space, names.buffer_info()[0])
106    ))[0]
107    namestr = names.tostring()
108    # return namestr, outbytes
109    return [namestr[i:i + offset].split(b'\0', 1)[0].decode('utf-8') for i in range(0, outbytes, length)]
110
111
112def _getIpAndMac(ifname):
113    ip, mac = _getIpAddr(ifname), _getMacAddr(ifname)
114    return (ip, mac)
115
116
117def getComputerName():
118    '''
119    Returns computer name, with no domain
120    '''
121    return socket.gethostname().split('.')[0]
122
123
124def getNetworkInfo():
125    '''
126    Obtains a list of network interfaces
127    @return: A "generator" of elements, that are dict-as-object, with this elements:
128      name: Name of the interface
129      mac: mac of the interface
130      ip: ip of the interface
131    '''
132    for ifname in _getInterfaces():
133        ip, mac = _getIpAndMac(ifname)
134        if mac != '00:00:00:00:00:00':  # Skips local interfaces
135            yield utils.Bunch(name=ifname, mac=mac, ip=ip)
136
137
138def getDomainName():
139    return ''
140
141
142def getLinuxVersion():
143    """
144    Returns the version of the Linux distribution
145    """
146    return distro.os_release_attr('pretty_name')
147
148
149def reboot(flags=0):
150    '''
151    Simple reboot using os command
152    '''
153    # Workaround for dummy thread
154    if six.PY3 is False:
155        import threading
156        threading._DummyThread._Thread__stop = lambda x: 42
157
158    subprocess.call(['/sbin/reboot'])
159
160
161def poweroff(flags=0):
162    '''
163    Simple poweroff using os command
164    '''
165    # Workaround for dummy thread
166    if six.PY3 is False:
167        import threading
168        threading._DummyThread._Thread__stop = lambda x: 42
169
170    subprocess.call(['/sbin/poweroff'])
171
172
173def logoff():
174    '''
175    Kills all curent user processes, which must send a logogof
176    caveat: If the user has other sessions, will also disconnect from them
177    '''
178    # Workaround for dummy thread
179    if six.PY3 is False:
180        import threading
181        threading._DummyThread._Thread__stop = lambda x: 42
182
183    subprocess.call(['/usr/bin/pkill', '-u', os.environ['USER']])
184
185
186def renameComputer(newName):
187    rename(newName)
188
189
190def joinDomain(domain, ou, account, password, executeInOneStep=False):
191    pass
192
193
194def changeUserPassword(user, oldPassword, newPassword):
195    '''
196    Simple password change for user using command line
197    '''
198    os.system('echo "{1}\n{1}" | /usr/bin/passwd {0} 2> /dev/null'.format(user, newPassword))
199
200
201class XScreenSaverInfo(ctypes.Structure):
202    _fields_ = [('window', ctypes.c_long),
203                ('state', ctypes.c_int),
204                ('kind', ctypes.c_int),
205                ('til_or_since', ctypes.c_ulong),
206                ('idle', ctypes.c_ulong),
207                ('eventMask', ctypes.c_ulong)]
208
209# Initialize xlib & xss
210try:
211    xlibPath = ctypes.util.find_library('X11')
212    xssPath = ctypes.util.find_library('Xss')
213    xlib = ctypes.cdll.LoadLibrary(xlibPath)
214    xss = ctypes.cdll.LoadLibrary(xssPath)
215
216    # Fix result type to XScreenSaverInfo Structure
217    xss.XScreenSaverQueryExtension.restype = ctypes.c_int
218    xss.XScreenSaverAllocInfo.restype = ctypes.POINTER(XScreenSaverInfo)  # Result in a XScreenSaverInfo structure
219except Exception:  # Libraries not accesible, not found or whatever..
220    xlib = xss = None
221
222
223def initIdleDuration(atLeastSeconds):
224    '''
225    On linux we set the screensaver to at least required seconds, or we never will get "idle"
226    '''
227    # Workaround for dummy thread
228    if six.PY3 is False:
229        import threading
230        threading._DummyThread._Thread__stop = lambda x: 42
231
232    subprocess.call(['/usr/bin/xset', 's', '{}'.format(atLeastSeconds + 30)])
233    # And now reset it
234    subprocess.call(['/usr/bin/xset', 's', 'reset'])
235
236
237def getIdleDuration():
238    '''
239    Returns idle duration, in seconds
240    '''
241    if xlib is None or xss is None:
242        return 0  # Libraries not available
243
244    # production code might want to not hardcode the offset 16...
245    display = xlib.XOpenDisplay(None)
246
247    event_base = ctypes.c_int()
248    error_base = ctypes.c_int()
249
250    available = xss.XScreenSaverQueryExtension(display, ctypes.byref(event_base), ctypes.byref(error_base))
251    if available != 1:
252        return 0  # No screen saver is available, no way of getting idle
253
254    info = xss.XScreenSaverAllocInfo()
255    xss.XScreenSaverQueryInfo(display, xlib.XDefaultRootWindow(display), info)
256
257    if info.contents.state != 0:
258        return 3600 * 100 * 1000  # If screen saver is active, return a high enough value
259
260    return info.contents.idle / 1000.0
261
262
263def getCurrentUser():
264    '''
265    Returns current logged in user
266    '''
267    return os.environ['USER']
268
269
270def getSessionLanguage():
271    '''
272    Returns the user's session language
273    '''
274    return locale.getdefaultlocale()[0]
275
276
277def showPopup(title, message):
278    '''
279    Displays a message box on user's session (during 1 min).
280    '''
281    return subprocess.call('zenity --info --timeout 60 --title "{}" --text "{}"'.format(title, message), shell=True)
282
283
284def get_etc_path():
285    """
286    :return:
287    Returns etc directory path.
288    """
289    return os.sep + 'etc'
Note: See TracBrowser for help on using the repository browser.