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

configure-ptt-chedecorare-oglive-methodsejecutarscript-b64fix-cfg2objfixes-winlgromero-filebeatmainnew-browserno-ptt-paramogadmclient-statusogcore1oglogoglog2override-moduleping1ping2ping3ping4report-progresstlsunification2unification3
Last change on this file since 9d65966 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: 6.9 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
45import distro
46from opengnsys import utils
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        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
60        info = bytearray(fcntl.ioctl(s.fileno(), 0x8927, struct.pack(str('256s'), ifname[:15])))
61        return six.text_type(''.join(['%02x:' % char for char in info[18:24]])[:-1])
62    except Exception:
63        return None
64
65
66def _getIpAddr(ifname):
67    '''
68    Returns the ip address of an interface
69    Ip is returned as unicode utf-8 encoded
70    '''
71    if isinstance(ifname, list):
72        return dict([(name, _getIpAddr(name)) for name in ifname])
73    if isinstance(ifname, six.text_type):
74        ifname = ifname.encode('utf-8')  # If unicode, convert to bytes (or str in python 2.7)
75    try:
76        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
77        return six.text_type(socket.inet_ntoa(fcntl.ioctl(
78            s.fileno(),
79            0x8915,  # SIOCGIFADDR
80            struct.pack(str('256s'), ifname[:15])
81        )[20:24]))
82    except Exception:
83        return None
84
85
86def _getInterfaces():
87    '''
88    Returns a list of interfaces names coded in utf-8
89    '''
90    max_possible = 128  # arbitrary. raise if needed.
91    space = max_possible * 16
92    if platform.architecture()[0] == '32bit':
93        offset, length = 32, 32
94    elif platform.architecture()[0] == '64bit':
95        offset, length = 16, 40
96    else:
97        raise OSError('Unknown arquitecture {0}'.format(platform.architecture()[0]))
98
99    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
100    names = array.array(str('B'), b'\0' * space)
101    outbytes = struct.unpack(str('iL'), fcntl.ioctl(
102        s.fileno(),
103        0x8912,  # SIOCGIFCONF
104        struct.pack(str('iL'), space, names.buffer_info()[0])
105    ))[0]
106    namestr = names.tobytes()
107    # return namestr, outbytes
108    return [namestr[i:i + offset].split(b'\0', 1)[0].decode('utf-8') for i in range(0, outbytes, length)]
109
110
111def _getIpAndMac(ifname):
112    ip, mac = _getIpAddr(ifname), _getMacAddr(ifname)
113    return (ip, mac)
114
115
116def getNetworkInfo():
117    '''
118    Obtains a list of network interfaces
119    @return: A "generator" of elements, that are dict-as-object, with this elements:
120      name: Name of the interface
121      mac: mac of the interface
122      ip: ip of the interface
123    '''
124    for ifname in _getInterfaces():
125        ip, mac = _getIpAndMac(ifname)
126        if mac != '00:00:00:00:00:00':  # Skips local interfaces
127            yield utils.Bunch(name=ifname, mac=mac, ip=ip)
128
129
130def getLinuxVersion():
131    """
132    Returns the version of the Linux distribution
133    """
134    return distro.os_release_attr('pretty_name')
135
136
137def reboot(flags=0):
138    '''
139    Simple reboot using os command
140    '''
141    # Workaround for dummy thread
142    if six.PY3 is False:
143        import threading
144        threading._DummyThread._Thread__stop = lambda x: 42
145
146    # Check for OpenGnsys Client or GNU/Linux distribution.
147    if os.path.exists('/scripts/oginit'):
148        subprocess.call('source /opt/opengnsys/etc/preinit/loadenviron.sh; /opt/opengnsys/scripts/reboot', shell=True)
149    else:
150        subprocess.call(['/sbin/reboot'])
151
152
153def poweroff(flags=0):
154    '''
155    Simple poweroff using os command
156    '''
157    # Workaround for dummy thread
158    if six.PY3 is False:
159        import threading
160        threading._DummyThread._Thread__stop = lambda x: 42
161
162    # Check for OpenGnsys Client or GNU/Linux distribution.
163    if os.path.exists('/scripts/oginit'):
164        subprocess.call('source /opt/opengnsys/etc/preinit/loadenviron.sh; /opt/opengnsys/scripts/poweroff', shell=True)
165    else:
166        subprocess.call(['/sbin/poweroff'])
167
168
169def logoff():
170    '''
171    Kills all curent user processes, which must send a logogof
172    caveat: If the user has other sessions, will also disconnect from them
173    '''
174    # Workaround for dummy thread
175    if six.PY3 is False:
176        import threading
177        threading._DummyThread._Thread__stop = lambda x: 42
178
179    subprocess.call(['/usr/bin/pkill', '-u', os.environ['USER']])
180
181
182def getCurrentUser():
183    '''
184    Returns current logged in user
185    '''
186    return os.environ['USER']
187
188
189def getSessionLanguage():
190    '''
191    Returns the user's session language
192    '''
193    return locale.getdefaultlocale()[0]
194
195
196def get_session_type():
197    """
198    Returns the user's session type (xrdp, wayland, x11, tty,...)
199    :return: string
200    """
201    return 'xrdp' if 'XRDP_SESSION' in os.environ else os.environ.get('XDG_SESSION_TYPE', 'unknown').lower()
202
203
204def showPopup(title, message):
205    '''
206    Displays a message box on user's session (during 1 min).
207    '''
208    return subprocess.call('zenity --info --timeout 60 --title "{}" --text "{}"'.format(title, message), shell=True)
209
210
211def get_etc_path():
212    """
213    :return:
214    Returns etc directory path.
215    """
216    return os.sep + 'etc'
217
218
219def build_popen_args(script):
220    return ['/bin/sh', '-c', script]
Note: See TracBrowser for help on using the repository browser.