source: client/engine/NetLib.py @ f160ff2

test-python-scriptsticket-693
Last change on this file since f160ff2 was 7260bdc2, checked in by Antonio Emmanuel Guerrero Silva <aguerrero@…>, 9 months ago

refs #585 Libraries convert to Python3

  • Property mode set to 100644
File size: 7.6 KB
Line 
1import subprocess
2import sys
3import os
4
5from engine.FileLib import *
6from engine.SystemLib import *
7
8def ogChangeRepo():
9    SRCIMG = ""
10    NEWREPO = ""
11    REPO = ""
12    OGUNIT = ""
13
14    if len(sys.argv) < 2:
15        print("Usage: ogChangeRepo IPREPO [ OgUnit ]")
16        print("Example: ogChangeRepo 10.1.120.3")
17        print("Example: ogChangeRepo 10.1.120.3 cdc")
18        return
19
20    if sys.argv[1] == "help":
21        print("Usage: ogChangeRepo IPREPO [ OgUnit ]")
22        print("Example: ogChangeRepo 10.1.120.3")
23        print("Example: ogChangeRepo 10.1.120.3 cdc")
24        return
25
26    if len(sys.argv) >= 2:
27        NEWREPO = sys.argv[1]
28
29    # Opciones de montaje: lectura o escritura
30    subprocess.run(["mount", "|", "grep", "ogimages.*rw,"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
31    RW = ",rw" if subprocess.returncode == 0 else ",ro"
32
33    # Si REPO tomamos el repositorio y la unidad organizativa actual
34    REPO = ogGetRepoIp()
35    OGUNIT = subprocess.run(["df", "|", "awk", "-F", " ", "'/ogimages/ {sub(\"//.*/ogimages\",\"\",$1); sub(\"/\",\"\",$1);  print $1}'"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode().strip()
36
37    # Parametros de entrada. Si $1 = "REPO" dejo el repositorio actual
38    if sys.argv[1].upper() == "REPO":
39        NEWREPO = REPO
40
41    # Si $1 y $2 son el repositorio y la OU actual me salgo
42    if NEWREPO == REPO and sys.argv[2] == OGUNIT:
43        return 0
44
45    subprocess.run(["source", "/scripts/functions"], shell=True)
46    subprocess.run(["source", "/scripts/ogfunctions"], shell=True)
47    subprocess.run(["umount", OGIMG])
48
49    if sys.argv[2] == "":
50        SRCIMG = "ogimages"
51    else:
52        SRCIMG = "ogimages/" + sys.argv[2]
53
54    subprocess.run(["eval", "$(grep \"OPTIONS=\" /scripts/ogfunctions)"])
55
56    ogEcho("session", "log", MSG_HELP_ogChangeRepo + " " + NEWREPO + " " + sys.argv[2].rstrip())
57    ogConnect(NEWREPO, ogprotocol, SRCIMG, OGIMG, RW)
58
59    # Si da error volvemos a montar el inicial
60    if subprocess.returncode != 0:
61        ogConnect(REPO, ogprotocol, SRCIMG, OGIMG, RW)
62        ogRaiseError("session", OG_ERR_REPO, NEWREPO)
63        return subprocess.returncode
64   
65def ogGetGroupDir():
66    REPO = ""
67    DIR = ""
68    GROUP = ""
69
70    if len(sys.argv) < 2:
71        ogHelp("ogGetGroupDir", "ogGetGroupDir str_repo", "ogGetGroupDir REPO  ==>  /opt/opengnsys/images/groups/Grupo1")
72        return
73
74    if len(sys.argv) == 1:
75        REPO = "REPO"
76    else:
77        REPO = sys.argv[1]
78
79    GROUP = ogGetGroupName()
80    if GROUP:
81        DIR = ogGetPath(REPO, "/groups/" + GROUP, stderr=subprocess.DEVNULL)
82        if os.path.isdir(DIR):
83            print(DIR)
84
85    return 0
86
87def ogGetGroupName():
88    if len(sys.argv) >= 2 and sys.argv[1] == "help":
89        ogHelp("ogGetGroupName", "ogGetGroupName", "ogGetGroupName  =>  Grupo1")
90        return
91
92    if "group" in globals() and group:
93        print(group)
94
95    return 0
96
97def ogGetHostname():
98    HOST = ""
99
100    if len(sys.argv) >= 2 and sys.argv[1] == "help":
101        ogHelp("ogGetHostname", "ogGetHostname", "ogGetHostname  =>  pc1")
102        return
103
104    # Tomar nombre de la variable HOSTNAME
105    HOST = os.getenv("HOSTNAME")
106
107    # Si no, tomar del DHCP, opción host-name
108    if not HOST:
109        with open("/var/lib/dhcp3/dhclient.leases", "r") as f:
110            for line in f:
111                if "option host-name" in line:
112                    HOST = line.split('"')[1]
113                    break
114
115    # Si no, leer el parámetro del kernel hostname
116    if not HOST:
117        with open("/proc/cmdline", "r") as f:
118            cmdline = f.read()
119            HOST = re.search(r"hostname=([^ ]+)", cmdline)
120            if HOST:
121                HOST = HOST.group(1)
122
123    if HOSTNAME != HOST:
124        os.environ["HOSTNAME"] = HOST
125
126    if HOST:
127        print(HOST)
128
129def ogGetIpAddress():
130    IP = ""
131
132    if len(sys.argv) >= 2 and sys.argv[1] == "help":
133        ogHelp("ogGetIpAddress", "ogGetIpAddress", "ogGetIpAddress  =>  192.168.0.10")
134        return
135
136    if "IPV4ADDR" in os.environ:
137        IP = os.environ["IPV4ADDR"]
138    else:
139        # Obtener direcciones IP.
140        if "DEVICE" in os.environ:
141            IP = subprocess.run(["ip", "-o", "address", "show", "up", "dev", os.environ["DEVICE"]], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode().split()
142        else:
143            IP = subprocess.run(["ip", "-o", "address", "show", "up"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode().split()
144
145        IP = [addr.split("/")[0] for addr in IP if "inet" in addr]
146
147    # Mostrar solo la primera.
148    if IP:
149        print(IP[0])
150
151    return 0
152
153def ogGetMacAddress():
154    MAC = ""
155
156    if len(sys.argv) >= 2 and sys.argv[1] == "help":
157        ogHelp("ogGetMacAddress", "ogGetMacAddress", "ogGetMacAddress  =>  00:11:22:33:44:55")
158        return
159
160    # Obtener direcciones Ethernet.
161    if "DEVICE" in os.environ:
162        MAC = subprocess.run(["ip", "-o", "link", "show", "up", "dev", os.environ["DEVICE"]], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode().split()
163        MAC = [addr.upper() for addr in MAC if "ether" in addr]
164    else:
165        MAC = subprocess.run(["ip", "-o", "link", "show", "up"], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode().split()
166        MAC = [addr.upper() for addr in MAC if "ether" in addr and "lo" not in addr]
167
168    # Mostrar solo la primera.
169    if MAC:
170        print(MAC[0])
171
172    return 0
173
174def ogGetNetInterface():
175    if len(sys.argv) >= 2 and sys.argv[1] == "help":
176        ogHelp("ogGetNetInterface", "ogGetNetInterface", "ogGetNetInterface  =>  eth0")
177        return
178
179    if "DEVICE" in os.environ:
180        print(os.environ["DEVICE"])
181
182    return 0
183
184def ogGetRepoIp():
185    # Variables locales.
186    SOURCE = ""
187    FSTYPE = ""
188
189    # Mostrar ayuda.
190    if len(sys.argv) >= 2 and sys.argv[1] == "help":
191        ogHelp("ogGetRepoIp", "ogGetRepoIp", "ogGetRepoIp  =>  192.168.0.2")
192        return
193
194    # Obtener direcciones IP, según el tipo de montaje.
195    output = subprocess.run(["findmnt", "-P", "-o", "SOURCE,FSTYPE", OGIMG], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode().strip()
196    lines = output.split("\n")
197    for line in lines:
198        fields = line.split()
199        if len(fields) == 2:
200            if fields[1] == "nfs":
201                SOURCE = fields[0].split(":")[0]
202            elif fields[1] == "cifs":
203                SOURCE = fields[0].split("/")[2]
204
205    if SOURCE:
206        print(SOURCE)
207
208    return 0
209
210def ogGetServerIp():
211    # Variables locales.
212    SOURCE = ""
213    FSTYPE = ""
214
215    # Mostrar ayuda.
216    if len(sys.argv) >= 2 and sys.argv[1] == "help":
217        ogHelp("ogGetServerIp", "ogGetServerIp", "ogGetServerIp  =>  192.168.0.2")
218        return
219
220    # Obtener direcciones IP, según el tipo de montaje.
221    output = subprocess.run(["findmnt", "-P", "-o", "SOURCE,FSTYPE", OGIMG], stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode().strip()
222    lines = output.split("\n")
223    for line in lines:
224        fields = line.split()
225        if len(fields) == 2:
226            if fields[1] == "nfs":
227                SOURCE = fields[0].split(":")[0]
228            elif fields[1] == "cifs":
229                SOURCE = fields[0].split("/")[2]
230
231    if SOURCE:
232        print(SOURCE)
233
234    return 0
235
236def ogMakeGroupDir():
237    REPO = ""
238    DIR = ""
239    GROUP = ""
240
241    if len(sys.argv) < 2:
242        ogHelp("ogMakeGroupDir", "ogMakeGroupDir str_repo", "ogMakeGroupDir", "ogMakeGroupDir REPO")
243        return
244
245    if len(sys.argv) == 1:
246        REPO = "REPO"
247    else:
248        REPO = sys.argv[1]
249
250    DIR = ogGetPath(REPO, "/groups/" + ogGetGroupName(), stderr=subprocess.DEVNULL)
251    if DIR:
252        subprocess.run(["mkdir", "-p", DIR], stderr=subprocess.DEVNULL)
253
254    return 0
Note: See TracBrowser for help on using the repository browser.