I am using below code to run SFTP command through Jsch:
public void putfile(){
try {
String command="winscp /script=D:\\command.txt" ;
System.out.println(command);
Runtime rt=Runtime.getRuntime();
rt.exec(command);
}
catch(Exception e) {
System.out.println("Exception in index.jsp:"+e.getMessage());
}
}
I am putting sample.zip from local machine to Unix Server,
The command.txt contains:
option confirm off
open sftp:User:password#IP
get G:\sample.zip /MyFolderLocation/
exit
Its working fine but i am not getting any exception whenever the SFTP process fails.Is there any way to handle it?
There are two common ways to detect whether a subprocess you ran encountered an error:
check its exit code,
see if it writes any error messages to standard output or standard error.
I don't know whether WinSCP sets an exit code in the event of an error, or writes a message to standard output or standard error, but it should do at least one of them. (It may even do both, which is what I'd expect all well-behaved processes to do.) You'll just have to try out WinSCP and see what happens.
I'd also recommend using a ProcessBuilder instead of Runtime.getRuntime().exec(...) to run the command. If nothing else, this allows you to redirect standard error into standard output so you only have one stream to read from.
Here's what your code looks like after I've modified it to use a ProcessBuilder, get the process's exit code and read the output from the command into a string:
public void putfile() {
try {
ProcessBuilder builder = new ProcessBuilder("winscp", "/script=D:\\command.txt");
builder.redirectErrorStream(true);
Process process = builder.start();
// read output from the process
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder outputBuilder = new StringBuilder();
String line;
do {
line = reader.readLine();
if (line != null) { outputBuilder.append(line).append('\n'); }
} while (line != null);
reader.close();
String output = outputBuilder.toString();
// inspect output for error messages.
int exitCode = process.waitFor();
// see if exit code is 0 (success) or != 0 (error)
}
catch(Exception e) {
System.out.println("Exception in index.jsp:"+e.getMessage());
}
}
Of course, reader should be closed in a finally block. For clarity I haven't bothered doing this in the code above.
Note that when running a subprocess in Java you should always read the subprocess's output, even if you don't care about its contents. If you don't, the buffer that the output gets written into may fill up, which will cause the subprocess to hang if it wants to write any more.
See WinSCP FAQ How do I know that script completed successfully?
You can tell the result of script by WinSCP exit code. Code 0
indicates success, while 1 indicates an error. For more details refer
to scripting documentation.
Batch script (specified using /script or /command command-line switches) terminates with code 1 immediately once any error occurs.
To find out why the script failed, inspect session log.
For an example see guide to transfer automation.
Related
I'm trying to kill off a already running java process using the Name of the .jar file.
It works completely fine when running the command
pkill -9 -f myapp.jar
from terminal but it doesn't work when you run that same command in a ProcessBuilder.
BufferedReader killStream;
String line;
try{
String[] args = new String[] {"pkill", "-9", "-f", " myapp.jar"};
Process proc = new ProcessBuilder(args).start();
killStream = new BufferedReader(new InputStreamReader(proc.getInputStream()));
line = killStream.readLine();
System.out.println(line);
return true;
}catch(Exception e){
e.printStackTrace();
return false;
}
killStream always return 'null'
What am i doing wrong here?
There are a few missing points here, aside from what is mentioned above regarding the passing in of the arguments your code could do with some more refining.
First of all why not use a try with resources clause to make sure that your resources are managed automatically and get always closed correctly?
With this in mind your code would look like:
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
// code to parse the command's output.
} catch (IOException e) {
// code to handle exceptions
}
Secondly, with the current code your method will always return true even if the pkill command has not run correctly.
Ideally would should wait for the process to terminate using Process#waitFor and then invoke Process#exitValue to retrieve the exit status of the command. Then you should return true or false based on whether the exit code is 0 or anything else.
Finally in order to be a bit more efficient, I would suggest using a StringBuilder to collect and append all of the process's output lines and just printing out that String.
Note that there are even better methods to encapsulate all this procedures making it more generic and re-usable while also using Java 8+ API (like streams, consumers etc etc).
I'm trying to execute a script from Java program:
public class TestCommandLine
{
public static void main (String[] args)
{
String PATH = "/path/programs/";
String command = PATH + "name_programs param1 param2";
executeCommand (command);
}
private static String executeCommand (String command)
{
StringBuffer output = new StringBuffer();
String line = "";
Process p;
try {
p = Runtime.getRuntime ().exec (command);
p.waitFor ();
BufferedReader reader = new BufferedReader (new InputStreamReader (p.getInputStream ()));
while ((line = reader.readLine ()) != null) {
output.append (line + "\n");
}
}
catch (Exception e) {
e.printStackTrace ();
}
return output.toString ();
}
}
there is not error, but the program does not run. I also try others solutions from stackoverflow but all of them didn't work
If you'd given your actual command to start with, this would have been much quicker.
You cannot use Process.exec to run shell-interpreted commands. Instead it executes programs directly. Thus input/output redirection (|, >, etc.) is not possible.
If you actually read the stderr (getErrorStream()) output it would probably be along the lines of "invalid argument: >".
You will either have to:
Redirect the output in Java. Read from the process's stdout (getInputStream()) and write to a FileOutputStream of some kind.
Execute a shell instead of your command directly. For example /bin/sh -c "command arg > file". The quoted section must be passed to sh as a single argument. In this case you wouldn't be able to see anything in stdout, and would have to open and read the file you just wrote to. The first option is probably more sensible.
And as pointed out elsewhere, unless your expecting a very small amount of output, you shouldn't wait for the command to exit before consuming the streams.
The only time I've done it I've used something like this:
Process p = Runtime.getRuntime().exec("foo.exe");
Have you tried that? If so, what was the error you got back?
Your command is producing output that you want to read, but you refuse to read any of it until the command has finished producing it all and has exited (not calling getInputStream() until after waitFor()).
If your command doesn't produce much output, this is OK, Java can buffer it. But if your command produces a lot of output, Java can't buffer it all, and the command gets blocked.
The operating system won't let the command write any more output because Java's buffer is full and you haven't instructed Java to empty it. So the program is blocked, and Java's waitFor() will never come back.
To solve your problem, you should call getInputStream() immediately after getting the Process object back from exec(), and you should create a new Thread that is responsible for reading the command output into your StringBuffer.
You should then waitFor() the process to finish, to see if it exited successfully, and then you can wait for the thread to get to the end of the inputstream and finish - at that point, it is safe to read through the StringBuffer with the full output from your command.
I'm trying to get a list of running processes and their file paths on a Windows Server 2003 machine. I'm using the following code to try and do that:
protected Map<String,String> getProcesses() {
Map<String,String> processes = new HashMap<String,String>();
try {
String line;
Process p = null;
// Windows
if (OS.indexOf("win") >= 0) {
p = Runtime.getRuntime().exec("wmic process get description,executablepath");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
LOG.info("Entering while loop");
while ((line = input.readLine()) != null) {
LOG.info("blah");
String[] array = line.split("\\s+");
if (array.length > 1) {
processes.put(array[0], array[1]);
}
}
LOG.info("Exited while loop");
input.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return processes;
}
The program gets stuck in an infinite loop at the while condition. "blah" and "Exited while loop" never output to the log. I've ran the command in command prompt on both my win7 local machine and the server which outputs the information just fine. I've also ran the above code on my local machine which also works fine. It looks like it's some issue between Java and Windows Server 2003 that I haven't been able to find in the past 3 hours of googling. Any help would be much appreciated.
You will need to get and close your OutputStream before getting and using your InputStream. That will confirm to the process that you've started that you have finished sending input (in this case, no input) to the process.
p.getOutputStream().close();
Remember that on the Process object, getInputStream() input comes from the output stream of the process, and getOutputStream() output goes to the input stream of the process.
Remember the BufferedReader.readLine() operation will block if there the end of input has not been reached, see here.
I think what you are experiencing is explained in the API for Process:
The methods that create processes may not work well for special processes on certain native platforms, such as native windowing processes, daemon processes, Win16/DOS processes on Microsoft Windows, or shell scripts. The created subprocess does not have its own terminal or console. All its standard io (i.e. stdin, stdout, stderr) operations will be redirected to the parent process through three streams (getOutputStream(), getInputStream(), getErrorStream()). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.
I need to run the Oracle EXP command through a Java program and print somewhere the command output.
The EXP command is correct, the dump file is created correctly when I execute my Java code, but I'm experiencing some issues to get the output.
This is an snippet very similar to the one I'm using to read the output:
String line;
String output = "";
try {
Process p = Runtime.getRuntime().exec(myCommand);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
output += (line + '\n');
}
input.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(output);
As I said, the command is correctly executed (verified through the generated dump file), but nothing appears on my console and my Java programs doesn't terminate either.
The same code works perfectly if I use another command, as "ls -l" instead of "exp ...".
Maybe exp is writing to standard error output rather than standard output.
Try to use p.getErrorStream() instead of getInputStream()
As a_horse_with_no_name said, it might be that the error stream buffer is full and thus is blocking the programm execution.
Either try to start a Thread to also read the error stream or use the ProcessBuilder class to redirect the error stream to stdout (which you already read).
I have an execute(String cmd) in a jsp script that calls the exec method from the Runtime class.
It works when I call a local command, like a php script stored on the server. for example: /usr/bin/php /path/to/php/script arg1 arg2
So I guess my execute command is ok, since it is working with that.
Now when I try to call lynx, the text-based web browser, it does not work.
If I call it in a terminal, it works fine:
/usr/bin/lynx -dump -accept_all_cookies 'http://www.someurl.net/?arg1=1&arg2=2'
But when I call this from my execute command, nothing happens...
Any idea why?
This is my execute method:
public String execute(String cmd){
Runtime r = Runtime.getRuntime();
Process p = null;
String res = "";
try {
p = r.exec(cmd);
InputStreamReader isr = new InputStreamReader(p.getInputStream());
BufferedReader br = new BufferedReader(isr);
String line = null;
//out.println(res);
while ((line = br.readLine()) != null) {
res += line;
}
p.waitFor();
} catch (Exception e) {
res += e;
}
System.out.println(p.exitValue());
return res;
}
You need to read from the Process' output stream.
Since you're not, the underlying lynx process is likely blocking while writing output, waiting for someone to empty the output stream's buffer. Even if you're going to ignore the output, you need to read it anyway for the process to execute as you'd expect.
As the javadocs of Process say, "Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock."
See http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html for some examples of how to handle this.
Edit: in case you are wondering, chances are that when you invoked the PHP script it didn't produce a great deal of output, and so was able to terminate before filling the output buffer and blocking. The lynx command is presumably producing more output and hence hitting this issue.
I solved it.... by calling lynx into a php script, php script that I called from the Jsp script...
It's a shitty solution but at least it works... I still do not really understand why the exec command from Java works that way...
Thanks for your help anyway Andrzej (Czech I guess from the name..? ^_^), somehow you put me on the way!