I am new to this kind of integration of java with Unix.
what i am trying to do is
String command="passwd";
Runtime rt=Runtime.getRuntime();
try {
Process pc=rt.exec(command);
try {
pc.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader buf = new BufferedReader(new InputStreamReader(pc.getInputStream()));
String line = "";
while ((line=buf.readLine())!=null) {
System.out.println(line);
}
BufferedReader buf1 = new BufferedReader(new InputStreamReader(pc.getErrorStream()));
String line1 = "";
while ((line1=buf1.readLine())!=null) {
System.out.println("Error--"+line1);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
System.out.println("IOException---"+e1.getMessage());
}
now when i am trying to pass the "passwd" command the Unix environment goes to suspended mode.
I want to know how can i pass the old password ,new password and confirm new password to the shell using the java code.
You need to pass it in using the confusing named Process.getOutputStream(). From the doc:
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
Note that you need to capture the processes stdout/err simultaneously to avoid blocking. See this answer for more details.
There is a utility called expect. If u installed u can pass argument for any thing. So construct as string execute by
String ConstructedCommand;
Process p=Runtime.getRuntime().exec(ConstructedCommand);
This link will be deserve your need. http://linux.die.net/man/1/expect
Related
I found my command line tool gets stuck in between and needs a enter to process and I found that it’s because of "QUICKEDIT" mode in cmd and we want to disable it to avoid that. So I searched for Java options to disable quick edit mode on my app launch but I got only bat file from here quickedit.bat.
And this bat file works perfect when I run from my command prompt it disable quick edit mode in the current session itself which is the same I want. So I kept that bat file in my folder via installer and run it first on every launch but it’s not turning off the quick edit mode for current session.
I have tried using both process builder and runtime.exec.
Below is my code
ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "quickedit.bat");
File dir = new File(System.getProperty("user.home")+File.separator+"AppData"+File.separator+"Local"+File.separator);
pb.directory(dir);
Process p=null;
try {
p = pb.start();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
try {
while ((line = in.readLine()) != null) {
System.out.println(line); // ----Here i get the same output i get when i run the bat file
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedReader inerr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
try {
while ((line = inerr.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
It gives me this:
When I run my bat file directly like this:
But through Java it didn't disable quick edit in my current command prompt whereas it disables at once I run the actual bat file. So can anyone say the reason or how to fix it or any other way to disable it for ever from Java?
Try pb.inheritIO(); before you call its start method. What you seem to have is a hybrid batch/Powershell script that that relies on stderr to determine which of the two it executes so this should require correct processing of stderr.
I didn't look at your bat file the most common issue on this kind of think is that process run from java did'nt share the environnement variable of your local setup nor jvm a quick fix to verify that is :
pb.environment().putAll(System.getenv());
hoping this will work :) then you just have to found which specific environnment variable is missing :)
I'm running this java program on a raspberry pi. The program is supposed to run the script "hello_pixy" and scan what it prints out. When I run hello_pixy manually, it prints out lines normally (Via C's printf line). But when I run the program, nothing is printed out and the BufferedReader didn't read any lines.
If I substitute the script for something like "ls", then the BufferedReader reads it and prints it out. Is there a way I can change the "printf"s in C to send to the InputStream (I don't really know C, just enough from Java experience)?
Process process = null;
try {
process = Runtime.getRuntime().exec("sudo .ss/pixy/build/hello_pixy/hello_pixy");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //for Windows
try {
process.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
String print = "";
try {
while ((line = reader.readLine()) != null) {
print += line;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("\nCodescan:\n\n" + print);
The code I'm executing is here: https://github.com/De-etz/pixy/blob/master/src/host/hello_pixy/hello_pixy.cpp
You're doing this back to front. You must read all the process's output first, and then call waitFor(). Your way you will probably just deadlock, as the process can't exit until it has produced all its output, and if you're not reading it, it will eventually block.
Notes:
C is not a scripting language, and a compiled program is not a script by definition.
Code that depends on the success of code in a prior try block must be inside that try block. At present you are continuing after exceptions as though they didn't happen. Don't write code like this.
I have been researching how to run a terminal command in java. I am doing this to make a program I can use to ssh into another pc (just as a project). How could I keep continuing putting commands in this terminal? If I run this I get a message to put in my password and if I do so it will print out what the messages the terminal spits out at the :
while((line = in.readLine()) != null){
System.out.println(line + "\n");
}
line, but a few seconds after that my program will stop working.
I currently have a GUI that is just a button and if I press the button it will run this code. Could someone help me to fix the issue of it stopping and give me information on how I could continue to put commands into the terminal? Thanks.
Process p = null;
String[] command = {"/bin/sh", "-c", "ssh 192.168.2.100"};
ProcessBuilder pb = new ProcessBuilder(command);
String line = null;
try {
term = pb.start();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStream is = p.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
try {
while((line = in.readLine()) != null){
System.out.println(line + "\n");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can not pass the argument to live JVM, But there is way in which you can modify the some of the parameters which done using JMX, with this you can connect to live JVM and send the parameters. which will be taken the effect immediately.
Hope that helps
I am using ProcessBuilder in Java to run a Perl script. When I run the Perl script while printing the InputStream of the process, the Java program seems to run for the duration of the Perl script. However if I comment out the getOutPut method in main the Java program terminates very fast and the Perl script does not run at all. Why does this occur?
private final static String SCENARIO = "scen";
/**
* #param args
*/
public static void main(String[] args) {
ProcessBuilder pb = new ProcessBuilder("perl", SCENARIO+".pl");
pb.directory(new File("t:/usr/aman/"+SCENARIO));
try {
Process p = pb.start();
getOutput(p.getInputStream(), true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static List getOutput(InputStream is, boolean print) {
List output = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String s = null;
try {
while ((s = reader.readLine()) != null) {
output.add(s);
if(print){
System.out.println(s);
}
}
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
return null;
}
return output;
}
Likely the OS's output stream buffer for your PERL script process gets filled because nothing is emptying this buffer, and this will kill the process. You need to gobble the output stream for this reason which is what your getOutput method does for you.
Please read the classic reference on this problem: When Runtime.exec() won't. Per this article:
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 want to run an interactive command with apache commons exec. Everything works except that when my command is executed and waits for user input I don't see my input in the console until I press enter which makes it effectively unusable.
This is an example of an interactive program:
public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while (true) {
System.out.print("=> ");
try {
line = in.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(line);
}
}
Now I want to execute that with apache commons exec like this:
public static void main(String[] args) {
Executor ex = new DefaultExecutor();
ex.setStreamHandler(new PumpStreamHandler(System.out, System.err, System.in));
CommandLine cl = new CommandLine("java");
cl.addArguments("-cp target\\classes foo.bar.Main");
try {
ex.execute(cl);
} catch (ExecuteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
As I said, it basically works, I get the "=>" prompt but when I type something I don't see it until I hit enter. I'm doing this on windows 7 with a cmd prompt.
I'd appreciate any hint on how to achieve the desired behaviour.
Edit: It works as expected on linux. I guess this is an issue with the windows cmd prompt. I'd still like to make this work if at all possible, so I would appreciate any insight into this behaviour on windows.
Edit2: I also tested with msys shell and powershell, both exhibit the same problem.
Edit3: I worked around the issue by launching a seperate cmd prompt. This works, but I still like to understand why.
CommandLine cl = new CommandLine("cmd");
cl.addArguments("/C java -cp target\\classes foo.bar.Main");
thanks
Raoul
I'm not sure exactly what you were expecting to happen here; if the spawned process is designed to wait to read from its input, then it shouldn't be surprising when it does exactly that?
If that's the issue, and your question is "How can I make my program automatically send a newline character to the spawned process' input?", then you'll need to define an OutputStream to write the input to, and get hold of the ExecuteStreamHandler to attach it to the process. Something like the following:
Executor ex = new DefaultExecutor();
// Create an output stream and set it as the process' input
OutputStream out = new ByteArrayOutputStream();
ex.getStreamHandler().setProcessInputStream(out);
...
try
{
ex.execute(cl);
out.write("\n".getBytes()); // TODO use appropriate charset explicitly
...
Using Apache exec org.apache.commons.exec.DefaultExecuteResultHandler you can launch a non-blocking command. And then you can follow the steps #Andrzej mentioned.