将自定义 Windows 事件查看器日志从 csv 导入 sql table

import custom Windows event viewer logs form csv into sql table

我有一个 powershell 命令从远程 windows 服务器获取事件查看器日志并将其放入 csv 文件,然后显示它并另外将其添加到数据库(sql 服务器)

String command = "powershell.exe cd 'Path\Output'; "
        + "$password = get-content 'Path\Output\"
        + serverClicked + "' | convertto-securestring; $username = 'administrator'; "
        + "$cred= New-Object System.Management.Automation.PSCredential($username, $password); "
        + "Invoke-Command -ComputerName " + serverClicked + " -Credential $cred -Authentication Default -ScriptBlock "
        + "{ Get-EventLog -LogName " + logName + " -EntryType " + entryType + " -Newest 50 | Select-Object -Property PSComputerName, TimeGenerated, EventID, Message, Source, EntryType}"
        + " | Out-File " + serverClicked + "." + logName + entryType + "." + curDate + ".csv; cat " + serverClicked + "." + logName + entryType + "." + curDate + ".csv";
System.out.println(command);

Process powerShellProcess;
powerShellProcess = Runtime.getRuntime().exec(command);
powerShellProcess.getOutputStream().close();
String line;
System.out.println("Output:");
BufferedReader stdout = new BufferedReader(new InputStreamReader(powerShellProcess.getInputStream()));
ShowInfoTextArea.setText("\n");

//------------------------------------
//Going to try adding the data to the database
DBConnect d = new DBConnect();
Connection con = d.getConnection();
Statement stmt = con.createStatement();
stmt.executeQuery("INSERT INTO EventViewer(TimeGenerated, EventID, Message, Source, EntryType, PSComputerName) VALUES ('" + timeGenerated + "', '" + eventID + "', '" + message + "', '" + source + "', '" + entryType2 + "', '" + pSComputerName + "');");
System.out.println("INSERT INTO EventViewer(TimeGenerated, EventID, Message, Source, EntryType, PSComputerName) VALUES ('" + timeGenerated + "', '" + eventID + "', '" + message + "', '" + source + "', '" + entryType2 + "', '" + pSComputerName + "');");
stmt.close();
stmt.close();
con.close();
//------------------------------------

此代码运行 powershell 命令并将输出放入 csv 文件,然后我需要将该输出放入数据库设置中的单独字段中,如下所示:

[TimeGenerated] [varchar](50) NOT NULL,
[EventID] [varchar](50) NOT NULL,
[Message] [varchar](500) NOT NULL,
[Source] [varchar](50) NOT NULL,
[EntryType] [varchar](50) NOT NULL,
[PSComputerName] [varchar](50) NOT NULL,
[LogName] [varchar] (50) NOT NULL

要么我需要弄清楚 Java 以将其正确输入数据库,要么找到更好的方法。我遇到的主要问题是事件的消息部分在多行上

提前感谢您的帮助

我无法对此进行测试,但我可以看到您的输出行有问题

+ " | Out-File " + serverClicked + "." + logName + entryType + "." + curDate + ".csv; cat " + serverClicked + "." + logName + entryType + "." + curDate + ".csv";

Out-File 不会制作正确的 CSV,也可能会引入编码问题。此外,您似乎正在读回文件。如果是这种情况,我们可以通过使用 ConvertTo-CSV 完全跳过该步骤,该 ConvertTo-CSV 旨在与您从 Get-EventLog 输出的对象一起使用。所以我会将 command 的最后一行改为...

+ " |  ConvertTo-Csv -NoTypeInformation

这应该可以为您提供所需内容的工作副本。如果我在正确的轨道上,而你仍然有问题,我需要你为我调试。