WMIC in Linux return [wmi/wmic.c:212:main()] ERROR: Retrieve result data - wmic

I try to use wmic in java to get device info, and it works success when I use CLI with command wmic -U user%password //192.168.xxx.xx "select name,status from Win32_service" | grep WinRM directly,
I have ask my colleague,and he said the error must be cause by the Cmd String array because String result get a value [wmi/wmic.c:212:main()] ERROR: Retrieve result data, but I just can't find what's wrong.
Here is my code:
String[] Cmd = new String[]{"wmic", "-U", "user%password", "//192.168.xxx.xx", "\"select name,status from Win32_service\" | grep WinRM"};
try {
for (String s : Cmd) {
System.out.println("Cmmand String:" + s);
}
Process proc = null;
proc = Runtime.getRuntime().exec(linuxCmd);
proc.getOutputStream().close();
InputStreamReader ir = new InputStreamReader(proc.getInputStream(), Charset.forName("x-windows-950")); //Using charset "x-windows-950" For the decode of the Traditional Chinese Windows.!!!
LineNumberReader input = new LineNumberReader(ir);
String line;
StringBuilder sb = new StringBuilder();
// System.out.println("Column Name: " + line);
while ((line = input.readLine()) != null) {
// logger.debug("Result" + input.getLineNumber() + ":" + line);
sb.append(line.trim()).append("\n");
}
String result = sb.toString().trim();
System.out.println("Result: " + result);
} catch (Exception ex) {
}

The ERROR occur because it seem grep as part of wmi query,It works after using where instead of grep.

Related

AWS S3 Reading a file: Java 8 Stream giving java.io.IOException: Attempted read on closed stream

I am trying to read a file from S3 bucket using the following logic.
public String readInputFile(String inputFileName) {
String result = null;
try (S3Object object = s3.getObject(new GetObjectRequest(bucketName, inputFileName))) {
Stream<String> stream = new BufferedReader(new InputStreamReader(object.getObjectContent())).lines();
LOG.info("Getting headers");
LOG.info("S3 Object" + object.getObjectContent());
LOG.info("Lines from the Input File"+stream.toString());
if(object!=null){
String[] headers = headers(object);
LOG.info("Headers are: "+ headers);
result = stream.skip(1) // skip headers
.map(line -> line.split(",")).map(data -> {
Map<String, String> map = new HashMap<>();
LOG.info("Info in each line" + data);
for (int i = 0; i < data.length; i++) {
map.put(headers[i], data[i]);
}
LOG.info("Map of the input"+map);
return map;
***}).collect(Collectors.toList()).toString().replaceAll("[\\[\\{\\}\\]]", "");***
LOG.info("Result of converting to map"+ result);
}
} catch (IOException e) {
FileProcessorAlerts.addAlert("IOException caught while reading " + inputFileName + " file " + e.getMessage());
LOG.error("IOException caught while reading " + inputFileName + " file " + e);
}
return result;
}
When I run this code it is giving me an error saying
Java.IOException: Attempted read on closed stream
near the highlighted with stars in the above code.Can someone please help me resolve this error.

Creating Trigger to auto-increment id by sequence in JDBC

I am writing methods through JDBC to create a table and a sequence to recall in a Trigger, I want to set up an id column which auto-increments before every insert on the table. I succeeded in building both the createTable method and the createSequence method in the DAO, but when I run the method to create the Trigger I got the java.sql.SQLException: Missing IN or OUT parameter at index:: 1
public void createTrigger() {
PreparedStatement ps;
StringBuilder queryTrigger = new StringBuilder();
queryTrigger.append("CREATE OR REPLACE TRIGGER ");
queryTrigger.append(Tables.getInstance().getName() + "_INSERTED\n");
queryTrigger.append("BEFORE INSERT ON " + Tabelle.getInstance().getName());
queryTrigger.append("\nFOR EACH ROW\n");
queryTrigger.append("BEGIN\n");
queryTrigger.append("SELECT " + Tables.getInstance().getName() + "SEQ.NEXTVAL\n");
queryTrigger.append("INTO :new.id\n");
queryTrigger.append("FROM dual;\n ");
queryTrigger.append("END;\n");
queryTrigger.append("/\n");
queryTrigger.append("ALTER TRIGGER " +Tabelle.getInstance().getName() + "_INSERTED ENABLE\n");
queryTrigger.append("/\n");
String stringQueryTrigger = queryTrigger.toString();
Connection conn = JDBCUtility.openConnection();
try {
ps = (PreparedStatement) conn.prepareStatement(stringQueryTrigger);
ps.executeUpdate();
ps.close();
} catch(SQLException e) {
e.printStackTrace();
}
JDBCUtility.closeConnection(conn);}
Here instead the creation of the table does actually work even if I don't
write the classic lines with parametrized "?" for the preparedStatement.setString(index, String)
public void createTable(Columns c) {
PreparedStatement ps;
StringBuilder query = new StringBuilder();
query.append("CREATE TABLE " + Tabelle.getInstance().getName() + "(");
query.append(Columns.getInstance().getColumnName() + " ");
query.append(Columns.getInstance().getDataType());
if(Columns.getInstance().isNullOrNot() == true) {
query.append(" NOT NULL");
}
else {
query.append("");
}
if(Columns.getInstance().isPrimaryKeyOrNot() == true) {
query.append(" PRIMARY KEY)");
}
else {
query.append(")");
}
String queryToString = query.toString();
Connection conn = JDBCUtility.openConnection();
try {
ps = (PreparedStatement) conn.prepareStatement(queryToString);
ps.executeUpdate();
ps.close();
} catch(SQLException e) {
e.printStackTrace();
}
JDBCUtility.closeConnection(conn);
}
//EDIT
turns out that is enough to substitute the PreparedStatement with a simple Statement, to get rid of the indexes mechanism and get the DB to accept the query
I would suggest creating an auto-increment sequnce in oracle that can be used for all ids and just add the string id.NextVal to the string query
What I mean is:
Rem in oracle create sequence
CREATE SEQUENCE ID
START BY 1
INCREMENT 1
// in java to execute query
String query = "INSERT INTO TABLE VALUES(ID.NEXTVAL);" ;
//rest of code

PsExec and Java to connect to a remote Windows Server

I have a requirement where I need to connect to a Windows Server from another personal windows machine. I also need to be able to CD into a particular folder on the remote machine, get a list of files in that folder and check for the existence of a file in that folder. When I started researching about this, I could understand that there are two options:
Have OpenSSH installed on the windows server and use clients like JSch to connect - my infra team may or may not approve this request.
Use PsExec to connect and do a similar thing - here is where I am able to connect but not able to figure out how to CD to a directory and get a list of files in any folder there.
Here is what I have in terms of code:
private static void authenticateAndExecute() {
String psCommand = PATH_TO_PSEXEC + "\\PsExec.exe \\\\" + "testdev19" + " -u " + "userName"
+ " -p " + "password";
psCommand = psCommand + " " + "cmd cd c:\\destdir" + " dir ";
String[] cmd = new String[5];
cmd[0] = "cmd.exe";
cmd[1] = "/C";
cmd[2] = psCommand;
cmd[3] = "";
cmd[4] = "";
// Run remote command
Process p = null;
try {
p = Runtime.getRuntime().exec(cmd, null);
System.out.println("Connected..." + p.getOutputStream());
InputStream is = p.getInputStream();
OutputStream os = p.getOutputStream();
InputStream es = p.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
BufferedReader errReader = new BufferedReader(new InputStreamReader(es));
String line;
// Read STDOUT into a buffer.
while ((line = errReader.readLine()) != null) {
System.out.println(line);
}
// If no STDOUT check STDERR.
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// Wait for the process to end.
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (p != null) {
p.destroy();
}
}
}
All I see after this is run is that the process has ended with a return code of 0. I want to see the list of files in the destination directory. Is this even possible using PsExec or am I going in the wrong path ?
Any help is appreciated...
Please have a look at:
https://www.ibm.com/developerworks/community/blogs/738b7897-cd38-4f24-9f05-48dd69116837/entry/programmatically_connecting_to_remote_systems2?lang=en
that might solve your problem
String psCommand = "<path_of_psexec>/psexec.exe \\\\"+currentServerHostname + " -u " + currentServerUser + " -p " + currentServerPass;
psCommand = psCommand + " " + commandToRunOnRemoteMachine + " " + parameters;
String[] cmd = new String[5];
cmd[0]="cmd.exe";
cmd[1]="/C";
cmd[2]=psCommand;
cmd[3]="";
cmd[4]="";
// Run remote command
File f = new File(getCurrentWorkingDirectory() + "\\lib");
Process p = Runtime.getRuntime().exec(cmd,null,f);

Can anyone see why this SQL insert will not work? (Exception to String and Date to String Inserted) - JDBC

Im trying to basically make a log of errors generated from a Java program and save them in an SQL table with 2 colums( Error and Date )
Try and catch sends the error to the method which should hopefully insert into database but its failing somewhere. Im new enough to Java so im not sure how to debug it properly or get more details on wahts going wrong and where
Heres the method.
public void createErrorLog(Exception error) throws SQLException{
// Error as String
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
error.printStackTrace(pw);
sw.toString(); // stack trace as a string
String errorOne = sw.toString();
System.out.println(errorOne);
// Date
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
String dateString = dateFormat.format(date);
Connection conn = null;
try {
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
System.out.println("Connected to database.");
String insertSaleProperty = "INSERT INTO ErrorLogs"
+ "(Error, "
+ "Time, "
+ "(?,?)";
PreparedStatement preparedStatement = conn.prepareStatement(insertSaleProperty);
preparedStatement.setString(1, errorOne);
preparedStatement.setString(2, dateString);
// execute insert SQL statement
preparedStatement.executeUpdate();
} catch (SQLException e) {
System.err.println("Cannot write to database.");
} finally {
if(conn != null){
conn.close();
}
}
}
Try the following.
String insertSaleProperty = "INSERT INTO ErrorLogs"
+ "(Error,Time) values "
+ "(?,?)";
String insertSaleProperty = "INSERT INTO ErrorLogs"
+ "(Error, "
+ "Time, "
+ "(?,?)";
Should probably be:
String insertSaleProperty = "INSERT INTO ErrorLogs "
+ "(Error, Time) "
+ "VALUES (?,?)";

BCP / sqlcmd / osql with encapsulated text fields?

Can any of these command line tools export to .csv like:
"int_field", "varchar_field", "another_int_field"
10, "some text", 10
5, "more text", 1
etc?
i don't want to use a view or stored procedure to hack the double quotes in :)
The built-in tool that does this is SSIS, although I appreciate that it might be a "heavier" solution than you want and it's not fully supported in Express Edition (you haven't mentioned either the version or edition that you're using). You can define a text qualifier in the flat file connection manager in the package.
Alternatively, write a small script in your preferred scripting language.
Somthing that I've quickly done. If you know c# you can add to it, otherwise it probably will be useless. Not my best code, but it is doing the job. All the field types is not added here, so it needs to be done.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.IO;
namespace SQLCSVExport
{
class Program
{
static void Main(string[] args)
{
bool trustedConn = false;
string Servername = "";
string Username = "";
string Password = "";
bool quotestring = false;
string fieldterminater = ",";
string tablename = "";
string operation = "";
string datafile = "";
bool includeheadings = false;
if (args.Length < 3)
{
ShowOptions();
return;
}
else
{
tablename = args[0];
operation = args[1];
datafile = args[2];
for (int i = 3; i < args.Length; i++)
{
switch (args[i].Substring(0, 2))
{
case "-Q":
quotestring = true;
break;
case "-T":
trustedConn = true;
break;
case "-S":
Servername = args[i].Substring(2);
break;
case "-U":
Username = args[i].Substring(2);
break;
case "-P":
Password = args[i].Substring(2);
break;
case "-t":
fieldterminater = args[i].Substring(2);
break;
case "-H":
includeheadings = true;
break;
}
}
}
SqlConnection conn;
if(File.Exists(datafile))
{
try
{
File.Delete(datafile);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
ShowOptions();
return;
}
}
if (trustedConn)
conn = new SqlConnection("Integrated Security=True;Initial Catalog=master;Data Source=" + Servername);
else
conn = new SqlConnection("Password=" + Password + ";Persist Security Info=True;User ID=" + Username + ";Initial Catalog=master;Data Source=" + Servername);
try
{
conn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
ShowOptions();
return;
}
SqlCommand cmd = new SqlCommand();
SqlDataReader read = null;
cmd.Connection = conn;
if (operation == "out")
cmd.CommandText = "Select * from " + tablename;
else
cmd.CommandText = tablename;
try
{
read = cmd.ExecuteReader();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
ShowOptions();
return;
}
string Dummy = "";
if (read.HasRows)
{
if(includeheadings)
{
for (int i = 0; i < read.FieldCount; i++)
{
if (quotestring)
Dummy += "\"" + read.GetName(i) + "\"" + fieldterminater;
else
Dummy += read.GetName(i) + fieldterminater;
}
WriteStrToFile(datafile, Dummy, fieldterminater);
}
while (read.Read())
{
Dummy = "";
for (int i = 0; i < read.FieldCount; i++)
{
switch (read[i].GetType().ToString())
{
case "System.Int32":
Dummy += read[i].ToString() + fieldterminater;
break;
case "System.String":
if (quotestring)
Dummy += "\"" + read[i].ToString() + "\"" + fieldterminater;
else
Dummy += read[i].ToString() + fieldterminater;
break;
case "System.DBNull":
Dummy += fieldterminater;
break;
default:
break;
}
}
WriteStrToFile(datafile, Dummy, fieldterminater);
}
}
}
static void WriteStrToFile(string datafile, string dummy, string fieldterminator)
{
FileStream fs = new FileStream(datafile, FileMode.Append, FileAccess.Write);
StreamWriter sr = new StreamWriter(fs);
if (dummy.Trim().Substring(dummy.Trim().Length - 1) == fieldterminator)
dummy = dummy.Substring(0, dummy.Trim().Length - 1);
sr.WriteLine(dummy);
sr.Close();
fs.Close();
sr.Dispose();
fs.Dispose();
}
static void ShowOptions()
{
Console.WriteLine("usage: SQLCSVExport {dbtable | query} {out | queryout} datafile");
Console.WriteLine("[-q quote string fields] [-S Server Name] [-U User Name]");
Console.WriteLine("[-P Password] [-T Trusted Connection] [-t field terminator]");
Console.WriteLine("[-H Add Headings]");
}
}
}
Looks like this confirms my suspicions that the answer is:
No.
Thanks for the alternative suggestions.