简体   繁体   English

Nodejs从日志文件中提取所有ipAddress

[英]Nodejs extract all ipAddress from a log file

There is a log file generated in my application.need to read the file and extract all the ip address from the file.我的应用程序中生成了一个日志文件。需要读取该文件并从该文件中提取所有 ip 地址。 The programming language i am using is Nodejs.我使用的编程语言是 Nodejs。 the code is like below.代码如下。 Not sure what i am doing wrong.不知道我做错了什么。

const fs = require("fs");

fs.readFile("sample.log", null, (err, data) => {
  if (err) {
    console.log("Error reading the file");
  } else {
    const fileData = data.toString();
    const ipRegex = /^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/gm;
    var arr = fileData.match(ipRegex);
    console.log(arr);
  }
});

when the log file is like below it works fine当日志文件如下所示时,它工作正常

10.55.20.116
10.55.20.184
10.55.20.187
10.55.20.45
10.55.20.7

在此处输入图像描述

But when the input is like below it is throwing null.但是当输入如下所示时,它会抛出 null。

tcp.0: [1609172718.597749195, {"HOSTNAME":"sample-audi-lbs-1","IP":"10.55.17.231"}]
tcp.0: [1609172718.597749195, {"HOSTNAME":"sample-audi-lbs-1","IP":"10.55.17.232"}]
tcp.0: [1609172718.597749195, {"HOSTNAME":"sample-audi-lbs-1","IP":"10.55.17.233"}]
tcp.0: [1609172718.597749195, {"HOSTNAME":"sample-audi-lbs-1","IP":"10.55.17.234"}]
tcp.0: [1609172718.597749195, {"HOSTNAME":"sample-audi-lbs-1","IP":"10.55.17.235"}]

在此处输入图像描述

The ^ means beginning of line and the $ means end of line. ^表示行首, $表示行尾。 If your entire line is just the IP address, it'll work, but if you need to be able to pluck the IP out of any part of the line, remove both of those characters.如果您的整行只是 IP 地址,它会起作用,但如果您需要能够从行的任何部分中取出 IP,请删除这两个字符。 Working below:在下面工作:

 const fileData = ` tcp.0: [1609172718.597749195, {"HOSTNAME":"sample-audi-lbs-1","IP":"10.55.17.231"}] tcp.0: [1609172718.597749195, {"HOSTNAME":"sample-audi-lbs-1","IP":"10.55.17.232"}] tcp.0: [1609172718.597749195, {"HOSTNAME":"sample-audi-lbs-1","IP":"10.55.17.233"}] tcp.0: [1609172718.597749195, {"HOSTNAME":"sample-audi-lbs-1","IP":"10.55.17.234"}] tcp.0: [1609172718.597749195, {"HOSTNAME":"sample-audi-lbs-1","IP":"10.55.17.235"}]`; const ipRegex = /((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/gm; var arr = fileData.match(ipRegex); console.log(arr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM