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

时间:2016-02-21 20:46:13

标签: java sql-server powershell windows-server-2012-r2 event-viewer

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

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是否能正确地将其导入数据库或更好的方法。我遇到的主要问题是事件的消息部分是多行

感谢您的提前帮助

1 个答案:

答案 0 :(得分:0)

我无法测试,但我看到输出线存在问题

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

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

+ " |  ConvertTo-Csv -NoTypeInformation

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