[f7fd5d5] | 1 | from flask import Flask, request, jsonify, render_template_string, abort |
---|
| 2 | import os |
---|
| 3 | import logging |
---|
| 4 | import json |
---|
| 5 | import subprocess |
---|
[5cf45c5] | 6 | import base64 |
---|
[f7fd5d5] | 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): |
---|
[5cf45c5] | 18 | logging.info(f'{request.get_json()}') |
---|
[f7fd5d5] | 19 | return jsonify({}) |
---|
| 20 | |
---|
| 21 | |
---|
| 22 | |
---|
[2ba25ff] | 23 | ## agente oglive: modulo ogAdmClient |
---|
[f7fd5d5] | 24 | |
---|
[2ba25ff] | 25 | @app.route('/opengnsys/rest/ogAdmClient/InclusionCliente', methods=['POST']) |
---|
[f7fd5d5] | 26 | def inclusion_cliente(): |
---|
[5cf45c5] | 27 | logging.info(f'{request.get_json()}') |
---|
[f7fd5d5] | 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 |
---|
[5cf45c5] | 32 | logging.info(f'iph ({iph}) cfg ({cfg})') |
---|
[f7fd5d5] | 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") |
---|
[5cf45c5] | 39 | nombreordenador = 'hal9000' #dbi_result_get_string(result, "nombreordenador"); |
---|
[f7fd5d5] | 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 | |
---|
[2ba25ff] | 81 | @app.route('/opengnsys/rest/ogAdmClient/AutoexecCliente', methods=['POST']) |
---|
[f7fd5d5] | 82 | def autoexec_client(): |
---|
[5cf45c5] | 83 | logging.info(f'{request.get_json()}') |
---|
[f7fd5d5] | 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 |
---|
[5cf45c5] | 87 | logging.info(f'iph ({iph}) exe ({exe})') |
---|
[f7fd5d5] | 88 | |
---|
| 89 | fileautoexec = '/tmp/Sautoexec-{}'.format(iph) |
---|
[5cf45c5] | 90 | logging.info ('fileautoexec ({})'.format (fileautoexec)); |
---|
[f7fd5d5] | 91 | try: |
---|
| 92 | fileexe = open (fileautoexec, 'w') |
---|
| 93 | except Exception as e: |
---|
[5cf45c5] | 94 | logging.error ('cannot create temporary file: {}'.format (e)) |
---|
[f7fd5d5] | 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 | |
---|
[2ba25ff] | 105 | @app.route('/opengnsys/rest/ogAdmClient/enviaArchivo', methods=['POST']) |
---|
[f7fd5d5] | 106 | def envia_archivo(): |
---|
[5cf45c5] | 107 | logging.info(f'{request.get_json()}') |
---|
[f7fd5d5] | 108 | j = request.get_json(force=True) |
---|
| 109 | nfl = j['nfl'] ## Toma nombre completo del archivo |
---|
[5cf45c5] | 110 | logging.info(f'nfl ({nfl})') |
---|
[f7fd5d5] | 111 | |
---|
[5cf45c5] | 112 | contents = subprocess.run (['cat', nfl], capture_output=True).stdout |
---|
| 113 | b64 = base64.b64encode (contents).decode ('utf-8') |
---|
| 114 | return jsonify({'contents': b64}) |
---|
[f7fd5d5] | 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 | |
---|
[2ba25ff] | 132 | @app.route('/opengnsys/rest/ogAdmClient/ComandosPendientes', methods=['POST']) |
---|
[f7fd5d5] | 133 | def comandos_pendientes(): |
---|
[5cf45c5] | 134 | logging.info(f'{request.get_json()}') |
---|
[f7fd5d5] | 135 | j = request.get_json(force=True) |
---|
| 136 | iph = j['iph'] ## Toma dirección IP |
---|
| 137 | ido = j['ido'] ## Toma identificador del ordenador |
---|
[5cf45c5] | 138 | logging.info(f'iph ({iph}) ido ({ido})') |
---|
[f7fd5d5] | 139 | |
---|
| 140 | idx = clienteExistente(iph) ## Busca índice del cliente |
---|
| 141 | if not idx: |
---|
| 142 | ## que devuelvo?? pongamos un 404... |
---|
[5cf45c5] | 143 | abort(404, 'Client does not exist') |
---|
[f7fd5d5] | 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 | |
---|
[2ba25ff] | 153 | @app.route('/opengnsys/rest/ogAdmClient/DisponibilidadComandos', methods=['POST']) |
---|
[f7fd5d5] | 154 | def disponibilidad_comandos(): |
---|
[5cf45c5] | 155 | logging.info(f'{request.get_json()}') |
---|
[f7fd5d5] | 156 | j = request.get_json(force=True) |
---|
| 157 | iph = j['iph'] |
---|
| 158 | tpc = j['tpc'] |
---|
[5cf45c5] | 159 | logging.info(f'iph ({iph}) tpc ({tpc})') |
---|
[f7fd5d5] | 160 | |
---|
| 161 | idx = clienteExistente(iph) ## Busca índice del cliente |
---|
| 162 | if not idx: |
---|
| 163 | ## que devuelvo?? pongamos un 404... |
---|
[5cf45c5] | 164 | abort(404, 'Client does not exist') |
---|
[f7fd5d5] | 165 | |
---|
| 166 | #strcpy(tbsockets[idx].estado, tpc); ## esto queda totalmente del lado del servidor, no lo implemento en python |
---|
| 167 | |
---|
| 168 | return jsonify({}) |
---|
| 169 | |
---|
[e28094e] | 170 | @app.route('/opengnsys/rest/ogAdmClient/recibeArchivo', methods=['POST']) |
---|
| 171 | def oac_recibe_archivo(): |
---|
| 172 | logging.info(f'{request.get_json()}') |
---|
[08dba6d] | 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})') |
---|
[e28094e] | 179 | return jsonify({'anything':'anything'}) ## if we return {}, then we trigger "if not {}" which happens to be true |
---|
| 180 | |
---|
[def6750] | 181 | @app.route('/opengnsys/rest/ogAdmClient/callback', methods=['POST']) |
---|
| 182 | def oac_callback(): |
---|
| 183 | logging.info(f'{request.get_json()}') |
---|
| 184 | return jsonify({'anything':'anything'}) |
---|
| 185 | |
---|
[2ba25ff] | 186 | @app.route('/opengnsys/rest/ogAdmClient/<cucu>', methods=['GET', 'POST']) |
---|
| 187 | def oac_cucu(cucu): |
---|
[5cf45c5] | 188 | #j = request.get_json(force=True) |
---|
| 189 | #logging.info(f'{request.get_json()} {j}') |
---|
| 190 | #if 'cucu' not in j: |
---|
| 191 | # abort(400, 'missing parameter 'cucu'') |
---|
| 192 | #return jsonify({'cucu': j['cucu']}) |
---|
| 193 | abort (404) |
---|
[f7fd5d5] | 194 | |
---|
[2ba25ff] | 195 | |
---|
| 196 | |
---|
| 197 | ## agente oglive: modulo CloningEngine |
---|
| 198 | |
---|
| 199 | @app.route('/opengnsys/rest/CloningEngine/recibeArchivo', methods=['POST']) |
---|
[e28094e] | 200 | def ce_recibe_archivo(): |
---|
[2ba25ff] | 201 | logging.info(f'{request.get_json()}') |
---|
[08dba6d] | 202 | j = request.get_json(force=True) |
---|
| 203 | nfl = j['nfl'] |
---|
| 204 | contents = j['contents'] |
---|
| 205 | logging.info(f'nfl ({nfl}) contents ({contents})') |
---|
| 206 | dec = base64.b64decode (contents).decode ('utf-8') |
---|
| 207 | logging.info(f'dec ({dec})') |
---|
[2ba25ff] | 208 | return jsonify({'anything':'anything'}) ## if we return {}, then we trigger "if not {}" which happens to be true |
---|
| 209 | |
---|
[def6750] | 210 | @app.route('/opengnsys/rest/CloningEngine/callback', methods=['POST']) |
---|
| 211 | def ce_callback(): |
---|
| 212 | logging.info(f'{request.get_json()}') |
---|
| 213 | return jsonify({'anything':'anything'}) |
---|
| 214 | |
---|
[2ba25ff] | 215 | @app.route('/opengnsys/rest/CloningEngine/<cucu>', methods=['GET', 'POST']) |
---|
| 216 | def ce_cucu(cucu): |
---|
| 217 | abort (404) |
---|
| 218 | |
---|
| 219 | |
---|
| 220 | |
---|
[f7fd5d5] | 221 | @app.errorhandler(404) |
---|
| 222 | def _page_not_found(e): |
---|
[5cf45c5] | 223 | if type(e.description) is dict: |
---|
| 224 | return jsonify (e.description), e.code |
---|
| 225 | else: |
---|
| 226 | return render_template_string('''<!DOCTYPE html><html>not found</html>'''), e.code |
---|
[f7fd5d5] | 227 | |
---|
| 228 | @app.errorhandler(500) |
---|
| 229 | def _internal_server_error(e): |
---|
[5cf45c5] | 230 | return render_template_string('''<!DOCTYPE html><html>err</html>'''), e.code |
---|
[f7fd5d5] | 231 | |
---|
| 232 | @app.errorhandler(Exception) |
---|
| 233 | def _exception(e): |
---|
| 234 | print(e) |
---|
[5cf45c5] | 235 | return render_template_string('''<!DOCTYPE html><html>exception</html>'''), e.code |
---|
[f7fd5d5] | 236 | |
---|
| 237 | if __name__ == '__main__': |
---|
| 238 | app.run(host = '192.168.1.249', port = 443, debug=True) |
---|