1 | from flask import Flask, request, jsonify, render_template_string, abort |
---|
2 | import os |
---|
3 | import logging |
---|
4 | import json |
---|
5 | import subprocess |
---|
6 | import base64 |
---|
7 | |
---|
8 | ## FLASK_APP=/path/to/ogcore-mock.py FLASK_ENV=development FLASK_RUN_CERT=adhoc sudo --preserve-env flask run --host 192.168.1.249 --port 443 |
---|
9 | |
---|
10 | |
---|
11 | app = Flask(__name__) |
---|
12 | logging.basicConfig(level=logging.INFO) |
---|
13 | |
---|
14 | ## agente lin/win/mac |
---|
15 | |
---|
16 | @app.route('/opengnsys/rest/ogagent/<cucu>', methods=['POST']) |
---|
17 | def og_agent(cucu): |
---|
18 | logging.info(f'{request.get_json()}') |
---|
19 | return jsonify({}) |
---|
20 | |
---|
21 | |
---|
22 | |
---|
23 | ## agente oglive: modulo ogAdmClient |
---|
24 | |
---|
25 | @app.route('/opengnsys/rest/ogAdmClient/InclusionCliente', methods=['POST']) |
---|
26 | def inclusion_cliente(): |
---|
27 | logging.info(f'{request.get_json()}') |
---|
28 | #procesoInclusionCliente() or { return (jsonify { 'res': 0 }) } |
---|
29 | j = request.get_json(force=True) |
---|
30 | iph = j['iph'] ## Toma ip |
---|
31 | cfg = j['cfg'] ## Toma configuracion |
---|
32 | logging.info(f'iph ({iph}) cfg ({cfg})') |
---|
33 | |
---|
34 | # dbi->query (sprintf "SELECT ordenadores.*,aulas.idaula,centros.idcentro FROM ordenadores INNER JOIN aulas ON aulas.idaula=ordenadores.idaula INNER JOIN centros ON centros.idcentro=aulas.idcentro WHERE ordenadores.ip = '%s'", iph); |
---|
35 | # if (!dbi_result_next_row(result)) { log_error ('client does not exist in database') } |
---|
36 | # log_debug (sprintf 'Client %s requesting inclusion', iph); |
---|
37 | |
---|
38 | idordenador = 42 #dbi_result_get_uint(result, "idordenador") |
---|
39 | nombreordenador = 'hal9000' #dbi_result_get_string(result, "nombreordenador"); |
---|
40 | cache = 42 #dbi_result_get_uint(result, "cache"); |
---|
41 | idproautoexec = 42 #dbi_result_get_uint(result, "idproautoexec"); |
---|
42 | idaula = 42 #dbi_result_get_uint(result, "idaula"); |
---|
43 | idcentro = 42 #dbi_result_get_uint(result, "idcentro"); |
---|
44 | |
---|
45 | # resul = actualizaConfiguracion(dbi, cfg, idordenador); ## Actualiza la configuración del ordenador |
---|
46 | # if (!resul) { log_error ('Cannot add client to database') } |
---|
47 | # if (!registraCliente(iph)) { log_error ('client table is full') } ## Incluyendo al cliente en la tabla de sokets |
---|
48 | |
---|
49 | return jsonify({ |
---|
50 | 'res': 1, ## int, Confirmación proceso correcto |
---|
51 | 'ido': idordenador, ## int |
---|
52 | 'npc': nombreordenador, ## string |
---|
53 | 'che': cache, ## int |
---|
54 | 'exe': idproautoexec, ## int |
---|
55 | 'ida': idaula, ## int |
---|
56 | 'idc': idcentro ## int |
---|
57 | }) |
---|
58 | |
---|
59 | def _recorreProcedimientos(parametros, fileexe, idp): |
---|
60 | #char idprocedimiento[LONPRM]; |
---|
61 | #int procedimientoid, lsize; |
---|
62 | #const char *msglog, *param; |
---|
63 | #dbi_result result; |
---|
64 | |
---|
65 | #dbi->query (sprintf 'SELECT procedimientoid,parametros FROM procedimientos_acciones WHERE idprocedimiento=%s ORDER BY orden', $idp); |
---|
66 | #if (!result) { log_error ('failed to query database'); return 0; } |
---|
67 | if 1: #while (dbi_result_next_row(result)) { |
---|
68 | procedimientoid = 0 ## dbi_result_get_uint(result, "procedimientoid"); |
---|
69 | if (procedimientoid > 0): ## Procedimiento recursivo |
---|
70 | if (not _recorreProcedimientos (parametros, fileexe, procedimientoid)): |
---|
71 | return 0 |
---|
72 | else: |
---|
73 | #param = '@'.join (["nfn=EjecutarScript\rscp=uptime", "nfn=EjecutarScript\rscp=cat /proc/uptime"]) ## dbi_result_get_string(result, "parametros"); |
---|
74 | param = '@'.join (["nfn=popup\rtitle=my title\rmessage=my message"]) |
---|
75 | parametros = '{}@'.format (param) |
---|
76 | fileexe.write (parametros) |
---|
77 | #} |
---|
78 | |
---|
79 | return 1 |
---|
80 | |
---|
81 | @app.route('/opengnsys/rest/ogAdmClient/AutoexecCliente', methods=['POST']) |
---|
82 | def autoexec_client(): |
---|
83 | logging.info(f'{request.get_json()}') |
---|
84 | j = request.get_json(force=True) |
---|
85 | iph = j['iph'] ## Toma dirección IP del cliente |
---|
86 | exe = j['exe'] ## Toma identificador del procedimiento inicial |
---|
87 | logging.info(f'iph ({iph}) exe ({exe})') |
---|
88 | |
---|
89 | fileautoexec = '/tmp/Sautoexec-{}'.format(iph) |
---|
90 | logging.info ('fileautoexec ({})'.format (fileautoexec)); |
---|
91 | try: |
---|
92 | fileexe = open (fileautoexec, 'w') |
---|
93 | except Exception as e: |
---|
94 | logging.error ('cannot create temporary file: {}'.format (e)) |
---|
95 | return jsonify({}) |
---|
96 | |
---|
97 | if (_recorreProcedimientos ('', fileexe, exe)): |
---|
98 | res = jsonify ({ 'res': 1, 'nfl': fileautoexec }) |
---|
99 | else: |
---|
100 | res = jsonify ({ 'res': 0 }) |
---|
101 | |
---|
102 | fileexe.close() |
---|
103 | return res |
---|
104 | |
---|
105 | @app.route('/opengnsys/rest/ogAdmClient/enviaArchivo', methods=['POST']) |
---|
106 | def envia_archivo(): |
---|
107 | logging.info(f'{request.get_json()}') |
---|
108 | j = request.get_json(force=True) |
---|
109 | nfl = j['nfl'] ## Toma nombre completo del archivo |
---|
110 | logging.info(f'nfl ({nfl})') |
---|
111 | |
---|
112 | contents = subprocess.run (['cat', nfl], capture_output=True).stdout |
---|
113 | b64 = base64.b64encode (contents).decode ('utf-8') |
---|
114 | return jsonify({'contents': b64}) |
---|
115 | |
---|
116 | def clienteExistente(iph): |
---|
117 | ## esto queda totalmente del lado del servidor, no lo implemento en python |
---|
118 | return 42 |
---|
119 | |
---|
120 | def buscaComandos(ido): |
---|
121 | #dbi->query (sprintf "SELECT sesion, parametros FROM acciones WHERE idordenador=%s AND estado='%d' ORDER BY idaccion", ido, ACCION_INICIADA); |
---|
122 | #dbi_result_next_row(result) ## cogemos solo una fila |
---|
123 | |
---|
124 | #if not row { return; } |
---|
125 | return |
---|
126 | |
---|
127 | #ids = 42 #dbi_result_get_uint(result, "sesion"); |
---|
128 | #param = "nfn=popup\rtitle=my title\rmessage=my message" #dbi_result_get_string(result, "parametros"); |
---|
129 | ## convertirlo a json, aqui lo pongo a capon |
---|
130 | #return jsonify ({ 'nfn': 'popup', 'title': 'my title', 'message': 'my message', 'ids': ids }) |
---|
131 | |
---|
132 | @app.route('/opengnsys/rest/ogAdmClient/ComandosPendientes', methods=['POST']) |
---|
133 | def comandos_pendientes(): |
---|
134 | logging.info(f'{request.get_json()}') |
---|
135 | j = request.get_json(force=True) |
---|
136 | iph = j['iph'] ## Toma dirección IP |
---|
137 | ido = j['ido'] ## Toma identificador del ordenador |
---|
138 | logging.info(f'iph ({iph}) ido ({ido})') |
---|
139 | |
---|
140 | idx = clienteExistente(iph) ## Busca índice del cliente |
---|
141 | if not idx: |
---|
142 | ## que devuelvo?? pongamos un 404... |
---|
143 | abort(404, 'Client does not exist') |
---|
144 | |
---|
145 | param = buscaComandos(ido) ## Existen comandos pendientes, buscamos solo uno |
---|
146 | if param is None: |
---|
147 | return jsonify({'nfn': 'NoComandosPtes'}) |
---|
148 | |
---|
149 | #strcpy(tbsockets[idx].estado, CLIENTE_OCUPADO); ## esto queda totalmente del lado del servidor, no lo implemento en python |
---|
150 | |
---|
151 | return jsonify(param) |
---|
152 | |
---|
153 | @app.route('/opengnsys/rest/ogAdmClient/DisponibilidadComandos', methods=['POST']) |
---|
154 | def disponibilidad_comandos(): |
---|
155 | logging.info(f'{request.get_json()}') |
---|
156 | j = request.get_json(force=True) |
---|
157 | iph = j['iph'] |
---|
158 | tpc = j['tpc'] |
---|
159 | logging.info(f'iph ({iph}) tpc ({tpc})') |
---|
160 | |
---|
161 | idx = clienteExistente(iph) ## Busca índice del cliente |
---|
162 | if not idx: |
---|
163 | ## que devuelvo?? pongamos un 404... |
---|
164 | abort(404, 'Client does not exist') |
---|
165 | |
---|
166 | #strcpy(tbsockets[idx].estado, tpc); ## esto queda totalmente del lado del servidor, no lo implemento en python |
---|
167 | |
---|
168 | return jsonify({}) |
---|
169 | |
---|
170 | @app.route('/opengnsys/rest/ogAdmClient/recibeArchivo', methods=['POST']) |
---|
171 | def oac_recibe_archivo(): |
---|
172 | logging.info(f'{request.get_json()}') |
---|
173 | j = request.get_json(force=True) |
---|
174 | nfl = j['nfl'] |
---|
175 | contents = j['contents'] |
---|
176 | logging.info(f'nfl ({nfl}) contents ({contents})') |
---|
177 | dec = base64.b64decode (contents).decode ('utf-8') |
---|
178 | logging.info(f'dec ({dec})') |
---|
179 | return jsonify({'anything':'anything'}) ## if we return {}, then we trigger "if not {}" which happens to be true |
---|
180 | |
---|
181 | @app.route('/opengnsys/rest/ogAdmClient/<cucu>', methods=['GET', 'POST']) |
---|
182 | def oac_cucu(cucu): |
---|
183 | #j = request.get_json(force=True) |
---|
184 | #logging.info(f'{request.get_json()} {j}') |
---|
185 | #if 'cucu' not in j: |
---|
186 | # abort(400, 'missing parameter 'cucu'') |
---|
187 | #return jsonify({'cucu': j['cucu']}) |
---|
188 | abort (404) |
---|
189 | |
---|
190 | |
---|
191 | |
---|
192 | ## agente oglive: modulo CloningEngine |
---|
193 | |
---|
194 | @app.route('/opengnsys/rest/CloningEngine/recibeArchivo', methods=['POST']) |
---|
195 | def ce_recibe_archivo(): |
---|
196 | logging.info(f'{request.get_json()}') |
---|
197 | j = request.get_json(force=True) |
---|
198 | nfl = j['nfl'] |
---|
199 | contents = j['contents'] |
---|
200 | logging.info(f'nfl ({nfl}) contents ({contents})') |
---|
201 | dec = base64.b64decode (contents).decode ('utf-8') |
---|
202 | logging.info(f'dec ({dec})') |
---|
203 | return jsonify({'anything':'anything'}) ## if we return {}, then we trigger "if not {}" which happens to be true |
---|
204 | |
---|
205 | @app.route('/opengnsys/rest/CloningEngine/<cucu>', methods=['GET', 'POST']) |
---|
206 | def ce_cucu(cucu): |
---|
207 | abort (404) |
---|
208 | |
---|
209 | |
---|
210 | |
---|
211 | @app.errorhandler(404) |
---|
212 | def _page_not_found(e): |
---|
213 | if type(e.description) is dict: |
---|
214 | return jsonify (e.description), e.code |
---|
215 | else: |
---|
216 | return render_template_string('''<!DOCTYPE html><html>not found</html>'''), e.code |
---|
217 | |
---|
218 | @app.errorhandler(500) |
---|
219 | def _internal_server_error(e): |
---|
220 | return render_template_string('''<!DOCTYPE html><html>err</html>'''), e.code |
---|
221 | |
---|
222 | @app.errorhandler(Exception) |
---|
223 | def _exception(e): |
---|
224 | print(e) |
---|
225 | return render_template_string('''<!DOCTYPE html><html>exception</html>'''), e.code |
---|
226 | |
---|
227 | if __name__ == '__main__': |
---|
228 | app.run(host = '192.168.1.249', port = 443, debug=True) |
---|