PsExec and Java to connect to a remote Windows Server - windows-server-2008

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);

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.

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

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.

Saved Docusign Document PDF's come out corrupted

I created a listener page that receives the Docusign webhooks. Everything is working as far as pulling data from the webhook, but when I cycle through the DocumentPDF's, it creates the PDF files but they are corrupted and cannot be opened (when I try to open it in Acrobat, I receive the following message: Acrobat could not open ... because it is either not a supported file type or because the file has been damaged.")
Can anybody help me figure out why the created pdf files are corrupted?
My code for the page is as follows:
protected void Page_Load(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(Request.InputStream);
string xml = sr.ReadToEnd();
string fileName = HttpContext.Current.Server.MapPath("") + "\\Results\\" + DateTime.Now.Ticks + ".xml";
File.WriteAllText(fileName, xml);
try
{
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(xml);
var mgr = new XmlNamespaceManager(xmldoc.NameTable);
mgr.AddNamespace("a", "http://www.docusign.net/API/3.0");
XmlNode envelopeStatus = xmldoc.SelectSingleNode("//a:EnvelopeStatus", mgr);
XmlNode envelopeId = envelopeStatus.SelectSingleNode("//a:EnvelopeID", mgr);
XmlNode status = envelopeStatus.SelectSingleNode("//a:Status", mgr);
if (status.InnerText == "Completed")
{
LogException("Looking for DocPDF's_" + DateTime.Now.Ticks + ";");
// Loop through the DocumentPDFs element, storing each document.
XmlNode docs = xmldoc.SelectSingleNode("//a:DocumentPDFs", mgr);
foreach (XmlNode doc in docs.ChildNodes)
{
string documentName = doc.ChildNodes[0].InnerText; // pdf.SelectSingleNode("//a:Name", mgr).InnerText;
string documentId = doc.ChildNodes[2].InnerText; // pdf.SelectSingleNode("//a:DocumentID", mgr).InnerText;
string byteStr = doc.ChildNodes[1].InnerText; // pdf.SelectSingleNode("//a:PDFBytes", mgr).InnerText;
LogException("Writing Out PDF_" + HttpContext.Current.Server.MapPath("") + "\\Documents\\" + envelopeId.InnerText + "_" + documentId + "_" + documentName + "_" + DateTime.Now.Ticks + ";");
File.WriteAllText(HttpContext.Current.Server.MapPath("") + "\\Documents\\" + envelopeId.InnerText + "_" + documentId + "_" + documentName, byteStr);
LogException("Successfully wrote out PDF_" + DateTime.Now.Ticks + ";");
}
}
}
catch (Exception ex)
{
LogException("Exception: " + ex.Message + "; InnerException: " + ex.InnerException.ToString() + "_" + DateTime.Now.Ticks + ";");
}
}
#mkl is correct. The Webhook (Connect) notification message's PDF content is base64 encoded. Decode it to obtain the PDF file.
An example: see line 402 of the recipe example webhook listener --
pdf_file.write(base64.b64decode(pdf.PDFBytes.string))
I am using an Azure Function and using a Blob storage to save it.
This worked for me:
var byteStr = doc.ChildNodes[1].InnerText;
outputBlob.Write(System.Convert.FromBase64String(byteStr));

Running SSIS from remote with WCF

I have a web service calling a ssis with no problem on localhost. But when i deploy it, it doesn't run and doesn't give any error. Where should i change to allow request from remote? I beleive that there is someting prevents requesting... This is my code.
public class blaService : IblaService
{
[WebMethod]
[WebGet(UriTemplate = "runSSISPackage/{Id}")]
public string runSSISPackage(string Id)
{
try
{
string pkgLocation = ConfigurationManager.AppSettings["dtsxPath"].ToString();
Package pkg;
Application app;
DTSExecResult pkgResults;
Variables vars;
string databaseName, tableName, minId, maxId, sCreatedDateTime, filePathTemplate, folderName;
Int64 fileRowAmount, fileCount;
using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString.SQL Server (SqlClient)"].ConnectionString.ToString()))
{
sqlConnection.Open();
SqlCommand sqlCommand = new SqlCommand("select * from dbo.Table where Id=" + Convert.ToInt32(Id), sqlConnection);
sqlCommand.CommandTimeout = 0;
SqlDataReader reader = sqlCommand.ExecuteReader();
if (reader.Read())
{
databaseName = reader["DatabaseName"].ToString();
tableName = reader["TableName"].ToString();
minId = reader["MinimumId"].ToString();
maxId = reader["MaximumId"].ToString();
fileRowAmount = Int64.Parse(reader["FileRowAmount"].ToString());
fileCount = Int64.Parse(reader["FileCount"].ToString());
sCreatedDateTime = Convert.ToDateTime(reader["CreatedDateTime"]).ToString("yyyyMMddHHmmss");
filePathTemplate = ConfigurationManager.AppSettings["outputFilePath"].ToString();
folderName = "bla_" + sCreatedDateTime;
if (!Directory.Exists(string.Format(filePathTemplate + "\\{0}", folderName)))
{
Directory.CreateDirectory(string.Format(filePathTemplate + "\\{0}", folderName));
}
app = new Application();
pkg = app.LoadPackage(pkgLocation, null);
vars = pkg.Variables;
vars["DBName"].Value = "bla_PasswordPool";
vars["FileCount"].Value = fileCount;
vars["FileName"].Value = "bla_" + sCreatedDateTime + "_1of1.txt";
vars["FileNamePrefix"].Value = "bla_" + sCreatedDateTime + "_";
vars["FileRowAmount"].Value = fileRowAmount;
vars["i"].Value = 0;
//vars["OutputFolder"].Value = #"C:\SSIS\blaSifreTakip\";
vars["OutputFolder"].Value = string.Format(filePathTemplate + "\\{0}", folderName);
vars["SelectSQLQuery"].Value = "select sifre from " + tableName + " where Id>" + minId + " And Id<=" + maxId + " order by Id";
vars["StartRowIndex"].Value = minId;
vars["TableName"].Value = tableName;
pkgResults = pkg.Execute(null, vars, null, null, null);
if (pkgResults == DTSExecResult.Success)
{
PasswordPackDataInfoEntity pp = new PasswordPackDataInfoEntity(Convert.ToInt32(Id));
pp.Status = 2;
pp.Save();
return "Success";
}
}
else
{
return "Empty";
}
}
return "";
}
catch (DtsException e)
{
return e.Message.ToString();
}
}
This is usually a permission issue between IIS and SQL Server (SSIS engine).
In IIS, look at the app pool that your WCF app (IIS folder) is using. If it is in the default pool, create a new pool and assign a utility account (to make things easier & isolated). That account needs permission to read files from your (configured) SSIS package folder and it needs admin permissions on the target database.
Here is a discussion thread that explains several pieces to the puzzle. It is a little wordy, but very thorough: http://social.msdn.microsoft.com/forums/en-US/sqlintegrationservices/thread/ff441dc3-b43b-486b-8be1-00126cf53812/

javax.script package: How to import JavaScript files?

I'm using javax.script package for running external JavaScript files within Java application.
How can I import one JavaScript file into another JavaScript file, without using Java code?
When you say without using java code, I am not completely sure what you mean, but this is a pure javascript that works (although it is calling java):
importPackage(java.io);
function loadJs(name, user) {
println("Loading " + name);
var f = new File(name);
var br = new BufferedReader(new FileReader(f));
var line = null;
var script = "";
while((line = br.readLine())!=null) {
script += line;
}
println(script);
eval(script);
hello(user);
}
...proivided, of course, that I have the file named (say c:/temp/hellouser.js) with something like:
function hello(name) { print('Hello, ' + name); }
I tested the script using a groovy script:
import javax.script.*;
sem = new ScriptEngineManager();
engine = sem.getEngineByExtension("js");
script1 = """
importPackage(java.io);
function loadJs(name, user) {
println("Loading " + name);
var f = new File(name);
var br = new BufferedReader(new FileReader(f));
var line = null;
var script = "";
while((line = br.readLine())!=null) {
script += line;
}
println(script);
eval(script);
hello(user);
}
""";
engine.eval(script1);
Object obj = engine.get("obj");
Invocable inv = (Invocable) engine;
inv.invokeFunction("loadJs", "c:/temp/hellouser.js", "Nicholas");
and the output was:
Loading c:/temp/hellouser.js
function hello(name) { print('Hello, ' + name); }
Hello, Nicholas
I hope this is approximately what you were looking for....
=========================== UPDATE ===========================
Here's a cleaned up version that extends the Rhino script engine factory (because the engine itself is final):
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import com.sun.script.javascript.RhinoScriptEngineFactory;
/**
* <p>Title: LoadEnabledRhinoEngineFactory</p>
* <p>Description: Adding a loadJs function to the standard JS engine</p>
* <p>Company: Helios Development Group LLC</p>
* #author Whitehead (nwhitehead AT heliosdev DOT org)
* <p><code>org.helios.apmrouter.js.LoadEnabledRhinoEngineFactory</code></p>
*/
public class LoadEnabledRhinoEngineFactory extends RhinoScriptEngineFactory {
/** The load script source */
public static final String LOAD_JS =
"importPackage(java.io); " +
"var script = ''; " +
"var ctx = null; " +
"function loadScript(name) { " +
"var f = new File(name); " +
"var br = new BufferedReader(new FileReader(f)); " +
"var line = null; " +
"while((line = br.readLine())!=null) { " +
" script += line; " +
"} " +
"_e_ngine.eval(script);" +
"} ";
/**
* {#inheritDoc}
* #see com.sun.script.javascript.RhinoScriptEngineFactory#getScriptEngine()
*/
#Override
public ScriptEngine getScriptEngine() {
ScriptEngine se = super.getScriptEngine();
Bindings b = se.createBindings();
b.put("_e_ngine", se);
se.setBindings(b, ScriptContext.GLOBAL_SCOPE);
try {
se.eval(LOAD_JS);
} catch (ScriptException e) {
throw new RuntimeException(e);
}
return se;
}
Now, loadScript(fileName) is part of the engine and you can cleanly call it with JS like:
loadScript('c:/temp/hellouser.js');
hello('Nicholas');"
or as I tested in Java:
ScriptEngine se = new LoadEnabledRhinoEngineFactory().getScriptEngine();
try {
se.eval("loadScript('c:/temp/hellouser.js'); hello('Nicholas');");
} catch (Exception e) {
e.printStackTrace(System.err);
}
Cheers.