How to input the password while executing cmd through java - java

I want to write a java program to retrieve the status of all the services running on different servers (approx 20). For this i am using SC command, i am able to do so using the java program. But now i am stuck in a situation where i want to run the SC command as a different user by using RUNAS, the problem that i am facing is that i am not able to input the password once the command has been executed for the first time. Following is the code that i am using :-
String[] command = new String[3];
command[0] = "cmd";
command[1] = "/c";
command[2] = "runas /noprofile /user:domain\\admin \"sc \\\\serverName queryex type= service state= all\"";
Process p = Runtime.getRuntime().exec(command);
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new BufferedOutputStream(p.getOutputStream())), true);
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = reader.readLine();
while (line != null) {
new PrintWriter(p.getOutputStream(),true).println("AdminPassword");
System.out.println(line);
line = reader.readLine();
}
BufferedReader stdInput = new BufferedReader(newInputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String Input;
while ((Input = stdInput.readLine()) != null) {
System.out.println(Input);
}
String Error;
while ((Error = stdError.readLine()) != null) {
System.out.println(Error);
}
But i am not been able to print the states of all the services. I am not not sure after providing the password whether i need to capture some other stream or else??
Any help on this?
Thanks

In your while (line != null) loop you open a new PrintWriter for each line you read. You print the admin password to these writers, but never close or flush them.
Try the PrintWriter writer you created above, and flush() it after writing the password, otherwise it will still be in the buffer.
You also create several BufferedReader on the inputStream of the Process, which might interfere with each other.
So: create only one reader resp. writer for the inputStream, errorStream and outputStream of the Process.

Related

How to handle interactive commands using runtime.getRuntime?

I have to execute a command from Java program on Unix platform.
I am using Runtime.getRuntime() for it.
However, the problem is that my command is interactive and asks for certain parameters at runtime. For e.g., the command is createUser. It asks for userName as the runtime.
bash-4.1$ createUser
Enter the UserName:
How can I handle such scenario so that the user name is entered at runtime from Java program?
try {
Process proc;
proc = Runtime.getRuntime().exec(cmd, envp);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// read the output from the command
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
sb.append(s);
}
// read any errors from the attempted command
while ((s = stdError.readLine()) != null) {
System.out.println(s);
sb.append(s);
}
} catch (Exception e) {
e.printStackTrace();
sb = null;
}
I heard that it can be done through expect. But How can I do it in Java?
Get also the standardOutput from proc. All you write in that standardOutput goes to the command
Send the username to standardOutput and don't forget to send the \n too.
You can check what was the last line of input steam and when you detect the prompt for user input input write to the output steam your value.
try {
Process proc;
proc = Runtime.getRuntime().exec(cmd, envp);
final BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
final PrintWriter stdOutput = new PrintWriter(proc.getOutputStream());
// read the output from the command
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
if (s.equals("Enter your username")) {
stdOutput.println("MyUsername");
stdOutput.flush();
}
sb.append(s);
}
} catch (final Exception e) {
e.printStackTrace();
sb = null;
}
(removed the error stream for simplicity)
Note that this works only if the prompt ends with a new line.
If the prompt has no new line (eg. Username: <cursor here>) you can try just writing the value at the start:
...
final PrintWriter stdOutput = new PrintWriter(proc.getOutputStream());
stdOutput.println("MyUsername");
stdOutput.flush();
...
But if the the command clears the buffer this will no work, in that case (rare case) you have to change the way you read from the stream (eg. instead of lines, read bytes)

BufferedReader seems to infinitely read the first line

I'm trying to run Handbrake through a Java app I'm writing, and am having trouble waiting for Handbrake to finish.
When I try this :
ProcessBuilder builder = new ProcessBuilder(
"cmd.exe", "/c", command);
Process p = builder.start();
BufferedReader inputreader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while((line = inputreader.readLine()) != null)
{
System.out.println(line);
}
The output I get is :
Encoding: task 1 of 1, 0.00 %
Over and over, and the file never gets converted.
When I change it to the following:
BufferedReader inputreader = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedReader errorreader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
String line = null;
String line2 = null;
while((line = inputreader.readLine()) != null && (line2 = errorreader.readLine()) != null)
{
System.out.println(line);
System.out.println(line2);
}
It works on my test files, however it gets hung-up when the errorreader runs out of lines to read and the readLine() locks the thread infinitely. On full length files the file gets converted but this portion of code gets locked so it never continues with the application.
Any suggestions?
Call builder.redirectErrorStream(true); before creating the process (this will merge the input and the error stream into one: the input stream), and only read from the InputStream.
That should solve the problem of the error stream running out of data before the input stream.
If you do want to keep them separate, then you can start two threads, on to read from the input stream and one from the error stream.

Why does BufferedReader fail if BufferedWriter is still open?

I am trying to run a .exe file from a java application and would like to be able to use it (for now) like a terminal where i can write to the .exe then read back from it before writing it again.
My issue is that the code only works when the writer is closed before the reader attempts to read from the inputstream.
String line = "", prev = "";
Scanner scan = new Scanner(System.in);
ProcessBuilder b = new ProcessBuilder("myexe");
b.redirectErrorStream(true);
Process p = b.start();
OutputStream stdin = p.getOutputStream();
InputStream stdout = p.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stdout));
System.out.println ("->");
while (scan.hasNext()) {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin));
String input = scan.nextLine();
if (input.trim().equals("exit")) {
writer.write("C");
} else {
writer.write(input);
}
writer.flush();
//writer.close();
while ((line = reader.readLine ()) != null) {
System.out.println ("[Stdout] " + line);
if (line.equals(prev)){
break;
}
prev = line;
}
reader.close();
}
So my question is, am i doing something wrong with the ProcessBuilder? I have read about not reading the output correctly can cause the system to hang. But this doesnt explain why it hangs when the writer is still open?
The issue was actually with my C compiled .exe. When it was running, the application was printing an output, therefore working in cmd terminal however i had not flushed the buffer after each command sent. Once i had done this, the java application would recognise each command as they were sent.

Running an interactive shellscript using java

I am writing a javacode to call a interactive shellscript and using process builder for calling shellscript. I know that to pass parameters to this shell script i have to take its inputstream to check it's output and need to use output stream to pass command to it. My question is that how would I know using Input Stream that it's prompting for entering values ?
My code :
ProcessBuilder pb2=new ProcessBuilder("/home/abhijeet/sample1.sh","--ip="+formobj.getUpFile().getFileName(),"--seqs="+seqs);
script_exec = pb2.start();
OutputStream in = script_exec.getOutputStream();
InputStreamReader rd=new InputStreamReader(script_exec.getInputStream());
pb2.redirectError();
BufferedReader reader1 =new BufferedReader(new InputStreamReader(script_exec.getInputStream()));
StringBuffer out=new StringBuffer();
String output_line = "";
while ((output_line = reader1.readLine())!= null)
{
out=out.append(output_line+"/n");
System.out.println("val of output_line"+output_line);
//---> i need code here to check that whether script is prompting for taking input ,so i can pass it values using output stream
}
Is there any way to know directly that script is waiting for an input from user?
Read the process output stream and check for the input prompt, if you know the input prompt, then put the values to process inupt stream.
Otherwise you have no way to check.
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
BufferedReader b1 = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedWriter w1 = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
String line = "";
String outp = "";
while ((line = b1.readLine()) != null) {
if (line.equals("PLEASE INPUT THE VALUE:")) {
// output to stream
w1.write("42");
}
outp += line + "\n";
}
...
UPD: for your code it should be something like that
ProcessBuilder pb2=new ProcessBuilder("/home/ahijeet/sample1.sh","--ip="+formobj.getUpFile().getFileName(),"--seqs="+seqs);
script_exec = pb2.start();
OutputStream in = script_exec.getOutputStream();
InputStreamReader rd=new InputStreamReader(script_exec.getInputStream());
pb2.redirectError();
BufferedReader reader1 =new BufferedReader(new InputStreamReader(script_exec.getInputStream()));
StringBuffer out=new StringBuffer();
String output_line = "";
while ((output_line = reader1.readLine())!= null)
{
out=out.append(output_line+"/n");
System.out.println("val of output_line"+output_line);
//---> i need code here to check that whether script is prompting for taking input ,so i can pass it values using output stream
if (output_line.equals("PLEASE INPUT THE VALUE:")) {
// output to stream
in.write("42");
}
}

Executing Shell Scripts from Java, Shell scripts having read operation

I have a Shell Scripts that read the Input
#!/bin/bash
echo "Type the year that you want to check (4 digits), followed by [ENTER]:"
read year
echo $year
I'm executing this shell scripts using JAVA APi
ProcessBuilder pb = new ProcessBuilder("/bin/bash", "/junk/leaptest.sh");
final Process process = pb.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
System.out.println("Program terminated!");
In the Java Console I can see the Output
Type the year that you want to check (4 digits), followed by [ENTER]:
Now the Actual Problem in How to pass the values to the Shell Scripts in my scripts how the varialble "year" can be read
I have edited the code as per the suggestion but doesn't work where we correct it
ProcessBuilder pb = new ProcessBuilder("/bin/bash", "-c", "/junk/leaptest.sh");
final Process process = pb.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
/*
* OutputStream os = process.getOutputStream(); PrintWriter pw = new
* PrintWriter(os);
*/
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
while ((line = br.readLine()) != null) {
System.out.println(line);
// pw.println("8999");
bw.write("2012");
}
System.out.println("Program terminated!");
You can use the OutputStream of the Process class:
OutputStream os = process.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.println("1997");
What you write to this output stream will become the input stream of the shell script. So read year will read 1987 to the year variable.
EDIT:
I also tried it out and I've managed to find the problem. The 1997 string hasn't reached the script, beacuse PrintWriter buffers the data that was written to it. You either have to flush the PrintWriter stream after the println() with pw.flush() or you have to set the auto-flush property to true upon creation:
PrintWriter pw = new PrintWriter(os, true);
Here is the complete code that was working fine for me:
leaptest.sh:
#!/bin/bash
echo "Type the year that you want to check (4 digits), followed by [ENTER]:"
read year
echo $year
Test.java:
import java.io.*;
class Test {
public static void main(String[] args) {
try {
ProcessBuilder pb = new ProcessBuilder("/bin/bash", "leaptest.sh");
final Process process = pb.start();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
PrintWriter pw = new PrintWriter(process.getOutputStream());
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
pw.println("1997");
pw.flush();
}
System.out.println("Program terminated!");
} catch(Exception e) {
e.printStackTrace();
}
}
}
Output:
$ java Test
Type the year that you want to check (4 digits), followed by [ENTER]:
1997
Program terminated!
To pass values from java program that executes script to the script use command line arguments. If you want to send information back from script to java program print the value in script, read the script's STDOUT in java program and parse it.
You really almost there. Now you are reading the script output (into while loop) but you are just printing it. Parse the output and do what you need with it.
Think you should parse input stream is to extract your values. Parse it by lines.
You want to set up an OutputStream using getOutputStream aswell, to be able to write data from your Java program into the process.
public abstract OutputStream getOutputStream()
Gets the output stream of the subprocess. Output to the stream is piped into the standard input stream of the process represented by
this Process object.
I think this should work. You need to handle your subprocess' output stream. Read the docs.
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
bw.write("2012");

Categories

Resources