Node.js - Obtener la fecha con hora

 
Vista:
sin imagen de perfil
Val: 7
Ha mantenido su posición en Node.js (en relación al último mes)
Gráfica de Node.js

Obtener la fecha con hora

Publicado por José Luis (3 intervenciones) el 21/10/2016 01:07:49
Hola a todos,

He leído este interesante manual para introducirme en el mundo de NODE.js

http://www.nodebeginner.org/index-es.html

Me gustaría que la página HTML tenga un campo textarea con el valor de la fecha, hora y nombre del equipo.

Con el siguiente código solo he podido colocar la fecha pero en hora, minuto y segundo aparecen puros ceros.1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var body = '<html>'+
    '<head>'+
    '<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />'+
    '</head>'+
    '<body>'+
    '<form action="/subir" method="post">'+
    '<textarea name="text" rows="20" cols="60">'+
 
Date.today() +
 
    '</textarea>'+
    '<input type="submit" value="Enviar texto" />'+
    '</form>'+
    '</body>'+
    '</html>';
 
    response.writeHead(200, {"Content-Type": "text/html"});
    response.write(body);
    response.end();

Alguien me podría a ayudar a generar la fecha, hora e ip del equipo que se conecte.

Saludos
José Luis
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
sin imagen de perfil
Val: 7
Ha mantenido su posición en Node.js (en relación al último mes)
Gráfica de Node.js

Obtener la fecha con hora

Publicado por Jose Luis (3 intervenciones) el 21/10/2016 07:50:57
En los otros foros me dieron la idea,

Por fin pude hacer lo de mi semi "reverse ping", que funciona de la siguiente manera:

Desde mi equipo ejecuto un comando para ejecutar nodejs, en la pagina web del cliente se autorefresh cada 30 segundos y manda una señal al servidor.

En el servidor se agrega a un historial de fechas, la fecha en que se comunica la pagina web con nodejs.

Con awk ejecuto un comando maketime(fecha con hora) y obtengo una diferencia de segundos entre la hora actual y el ultimo registro del archivo historial de fechas con horas que.

Anexo los códigos así como la ruta del manual que tomé como ejemplo.

Descargué nodejs para linux de: https://nodejs.org/en/download/

El manual que leí es el siguiente: http://www.nodebeginner.org/index-es.html

Fué tan sencillo que lo único que hice fué descargar el programa irme a la ruta bin y ejecutar node. ( ./node index.js )

archivo server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
var http = require("http");
var url = require("url");
 
function iniciar(route, handle) {
  function onRequest(request, response) {
        var dataPosteada = "";
        var pathname = url.parse(request.url).pathname;
        console.log("Peticion para " + pathname + " recibida.");
 
        request.setEncoding("utf8");
 
        request.addListener("data", function(trozoPosteado) {
          dataPosteada += trozoPosteado;
          console.log("Recibido trozo POST '" + trozoPosteado + "'.");
    });
 
    request.addListener("end", function() {
      route(handle, pathname, response, dataPosteada);
    });
 
  }
 
  http.createServer(onRequest).listen(8888);
  console.log("Servidor Iniciado");
}
 
exports.iniciar = iniciar;

Archivo router.js
1
2
3
4
5
6
7
8
9
10
11
12
13
function route(handle, pathname, response, postData) {
  console.log("A punto de rutear una peticion para " + pathname);
  if (typeof handle[pathname] === 'function') {
    handle[pathname](response, postData);
  } else {
    console.log("No se ha encontrado manipulador para " + pathname);
    response.writeHead(404, {"Content-Type": "text/html"});
    response.write("404 No encontrado");
    response.end();
  }
}
 
exports.route = route;

Archivo requestHandlers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
var exec = require("child_process").exec;
 
function iniciar(response, postData) {
  console.log("Manipulador de Peticion 'iniciar' fue llamado.");
 
  var body = '<html>'+
    '<head>'+
    '<meta http-equiv="refresh" content="10" />'+
    '</head>'+
    '<body>'+
    '<h1> Reverse ping to 99.99.99.99:8888</h1>'+
 
'Date: '+
'<script type="text/javascript">'+
'var d = new Date();'+
'document.write( d );'+
'</script> '+
 
 
    '</body>'+
    '</html>';
 
    response.writeHead(200, {"Content-Type": "text/html"});
    response.write(body);
 
    // Ejecutar comando en linux en el servidor
    exec("date +'%F %T' >> ping_reverse.txt", function (error, stdout, stderr) {
    response.end();
  });
 
}
 
exports.iniciar = iniciar;

Archivo index.js
1
2
3
4
5
6
7
8
9
var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");
 
var handle = {}
handle["/"] = requestHandlers.iniciar;
handle["/iniciar"] = requestHandlers.iniciar;
 
server.iniciar(router.route, handle);

El programa en awk que me permite hacer las validaciones es

programa check_time.awk
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
BEGIN    \
{
    # Initialize table of month lengths
    _tm_months[0,1] = _tm_months[1,1] = 31
    _tm_months[0,2] = 28; _tm_months[1,2] = 29
    _tm_months[0,3] = _tm_months[1,3] = 31
    _tm_months[0,4] = _tm_months[1,4] = 30
    _tm_months[0,5] = _tm_months[1,5] = 31
    _tm_months[0,6] = _tm_months[1,6] = 30
    _tm_months[0,7] = _tm_months[1,7] = 31
    _tm_months[0,8] = _tm_months[1,8] = 31
    _tm_months[0,9] = _tm_months[1,9] = 30
    _tm_months[0,10] = _tm_months[1,10] = 31
    _tm_months[0,11] = _tm_months[1,11] = 30
    _tm_months[0,12] = _tm_months[1,12] = 31
}
 
 
# decide if a year is a leap year
function _tm_isleap(year,    ret)
{
    ret = (year % 4 == 0 && year % 100 != 0) ||
            (year % 400 == 0)
    return ret
}
# convert a date into seconds
function _tm_addup(a,    total, yearsecs, daysecs,
                         hoursecs, i, j)
{
    hoursecs = 60 * 60
    daysecs = 24 * hoursecs
    yearsecs = 365 * daysecs
 
    total = (a[1] - 1970) * yearsecs
 
    # extra day for leap years
    for (i = 1970; i < a[1]; i++)
        if (_tm_isleap(i))
            total += daysecs
 
    j = _tm_isleap(a[1])
    for (i = 1; i < a[2]; i++)
        total += _tm_months[j, i] * daysecs
 
    total += (a[3] - 1) * daysecs
 
    total += a[4] * hoursecs
    total += a[5] * 60
    total += a[6]
 
    return total
}
# Function mktime convert a date into seconds
function mktime(str,    res1, res2, a, b, i, j, t, diff)
{
    i = split(str, a, " ")    # don't rely on FS
 
    if (i != 6)
        return -1
 
    # force numeric
    for (j in a)
        a[j] += 0
 
    # validate
    if (a[1] < 1970 ||
        a[2] < 1 || a[2] > 12 ||
        a[3] < 1 || a[3] > 31 ||
        a[4] < 0 || a[4] > 23 ||
        a[5] < 0 || a[5] > 59 ||
        a[6] < 0 || a[6] > 61 )
            return -1
 
    res1 = _tm_addup(a)
 
    return res1
}
 
{
 
    last_t=$0
    getline < "checktime.txt"
    curr_t=$0
 
    # Convert last_time to seconds (epoch)
    b=last_t
    gsub(/[-:]/," ",b)
    last_s=mktime(b)
 
    # Convert curr_time to seconds (epoch)
    b=curr_t
    gsub(/[-:]/," ",b)
    curr_s=mktime(b)
 
    print ((curr_s-last_s)<=60) ? 1 : 0
 
}

Y el script con el cual hago las validaciones y se ejecuta en el crontab es el siguiente:

achivo reverse_ping.sh

1
2
3
4
5
6
7
8
9
10
11
12
#!/bin/bash
# email report when
SUBJECT="Reverse ping failed"
EMAILID="jose.luis@micompania.com"
date +'%F %T' > checktime.txt
 
count=$(tail -1 ping_reverse.txt | awk -f check_time.awk )
 
if [ $count -eq 0 ]; then
 # 100% failed
 echo "Host : VIRTUALIZACION DISEN~O  is down (reverse ping failed) at $(date)" | mail -s "$SUBJECT" $EMAILID
fi


Esta es la versión preliminar, me falta poder enviar al servidor la IP del equipo y alguna contraseña para estar seguro de monitorear al equipo requerido.

Saludos
José Luis
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar
Imágen de perfil de xve

Obtener la fecha con hora

Publicado por xve (3 intervenciones) el 21/10/2016 11:03:35
Gracias por compartirlo Jose Luis!!!
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar