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

decorare-oglive-methodsexec-ogbrowserfix-urllog-sess-lenmainoggitoglogoglog2override-moduleping1ping2ping3ping4sched-tasktls
Last change on this file since f1c3cd2 was 1d93de1, checked in by Natalia Serrano <natalia.serrano@…>, 9 months ago

refs #531 remove unused code, bump version

  • Property mode set to 100644
File size: 6.1 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 json
46from opengnsys import utils
47
48ip_a_s = None
49
50## make sure /usr/local/bin is in PATH
51## we need that to run /usr/local/bin/ip, which uses 'env' and pulls from PATH anyway
52def check_path():
53    path = os.getenv ('PATH', '')
54    usr_local_bin = '/usr/local/bin'
55
56    if usr_local_bin not in path.split (os.pathsep):
57        os.environ['PATH'] = usr_local_bin + os.pathsep + path
58
59def _getMacAddr(ifname):
60    '''
61    Returns the mac address of an interface
62    Mac is returned as unicode utf-8 encoded
63    '''
64    for interface in ip_a_s:
65        if interface.get ('ifname') != ifname: continue
66        return interface.get ('address')
67    return None
68
69
70def _getIpAddr(ifname):
71    '''
72    Returns the first IP address of an interface
73    IPv4 is preferred over IPv6
74    IP is returned as unicode utf-8 encoded
75    '''
76
77    ## loop and return the first IPv4 address found
78    for interface in ip_a_s:
79        if interface.get ('ifname') != ifname: continue
80        for addr_info in interface.get ('addr_info', []):
81            ip_address = addr_info.get ('local')
82            try:
83                ip_address.index ('.')
84                return ip_address
85            except: pass
86
87    ## if nothing found, loop again and return the first IP found, which will be an IPv6
88    for interface in ip_a_s:
89        if interface.get ('ifname') != ifname: continue
90        for addr_info in interface.get ('addr_info', []):
91            return addr_info.get ('local')
92
93    return None
94
95
96def _getInterfaces():
97    '''
98    Returns a list of interfaces names
99    '''
100    global ip_a_s
101
102    check_path()
103    result = subprocess.run (['/usr/local/bin/ip', '-json', 'address', 'show'], capture_output=True, text=True)
104
105    if result.returncode != 0: raise Exception (f'Command "ip" failed with exit code {result.returncode}')
106    ip_a_s = json.loads (result.stdout)
107    return [i.get('ifname') for i in ip_a_s]
108
109
110def _getIpAndMac(ifname):
111    ip, mac = _getIpAddr(ifname), _getMacAddr(ifname)
112    return (ip, mac)
113
114
115def getNetworkInfo():
116    '''
117    Obtains a list of network interfaces
118    @return: A "generator" of elements, that are dict-as-object, with this elements:
119      name: Name of the interface
120      mac: mac of the interface
121      ip: ip of the interface
122    '''
123    for ifname in _getInterfaces():
124        ip, mac = _getIpAndMac(ifname)
125        if mac != None and ip != None:  # Skips local interfaces
126            yield utils.Bunch(name=ifname, mac=mac, ip=ip)
127
128
129def getMacosVersion():
130    return 'macOS {}'.format(platform.mac_ver()[0])
131
132
133def reboot(flags=0):
134    '''
135    Simple reboot 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 reboot command
143    subprocess.call('/sbin/shutdown -r now', shell=True)
144
145
146def poweroff(flags=0):
147    '''
148    Simple poweroff command
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 shutdown command
156    subprocess.call('/sbin/shutdown -h now', shell=True)
157
158
159def logoff():
160    '''
161    Simple logout using AppleScript
162    '''
163    # Workaround for dummy thread
164    if six.PY3 is False:
165        import threading
166        threading._DummyThread._Thread__stop = lambda x: 42
167
168    # Exec logout using AppleScript
169    subprocess.call('/usr/bin/osascript -e \'tell app "System Events" to «event aevtrlgo»\'', shell=True)
170
171
172def getCurrentUser():
173    '''
174    Returns current logged in user
175    '''
176    return os.environ['USER']
177
178
179def getSessionLanguage():
180    '''
181    Returns the user's session language
182    '''
183    lang = locale.getdefaultlocale()[0]
184    if lang is None:
185        return 'C'
186    else:
187        return lang
188
189
190def get_session_type():
191    """
192    Minimal implementation of this required function
193    :return: string
194    """
195    return 'unknown'
196
197
198def showPopup(title, message):
199    '''
200    Displays a message box on user's session (during 1 min).
201    '''
202    # Show a dialog using AppleSctipt
203    return subprocess.call('/usr/bin/osascript -e \'display notification "{}" with title "{}"\''.format(message, title), shell=True)
204
205
206def get_etc_path():
207    """
208    :return:
209    Returns etc directory path.
210    """
211    return os.sep + 'etc'
212
213
214def build_popen_args(script):
215    return ['/bin/sh', '-c', script]
Note: See TracBrowser for help on using the repository browser.