I want to execute a command from Java but this command wants me to give it a username.
Like this example:
$ my command
[command] Username:_
So how can I give the command my username in Java?
Currently my code is like this:
Process p = Runtime.getRuntime().exec(command);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s;
while ((s = br.readLine()) != null){
System.out.println(s);
}
br.close();
p.waitFor();
p.destroy();
You need to create another thread and pump user input through process#getOutputStream(). See the following example:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
public class ProcessWithInput {
public static void main(String[] args) throws IOException, InterruptedException {
Process p = Runtime.getRuntime().exec("cat");
OutputStream os = p.getOutputStream();
os.write("Hello World".getBytes());
os.close();
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s;
while ((s = br.readLine()) != null) {
System.out.println(s);
}
br.close();
p.waitFor();
p.destroy();
}
}
Ofcourse, you need to do proper error/exception handling etc.
Other option is to use ProcessBuilder which allows you to provide input through a File.
Related
I want to execute a Linux command (curl) using java code
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class ExecuteShellCommand {
public String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
public static void main(String args[]) {
ExecuteShellCommand com = new ExecuteShellCommand();
System.out.println(com.executeCommand(
"curl -u '<username><pw>' -k <host>/services/search/jobs -d search=\"abc""));
System.out.println("hello");
The console output is printing hello only with no errors though when i tried the command in git bash it will give a xml response.
I am trying to create a program (personal practice) to access CMD and type any command you want, as if you were working on cmd.exe;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class CMD_Live {
public static void main(String[] args) throws IOException {
// The purpose of this program is to use Java to perform CMD commands as if you are working on it live
Scanner ScanCMD = new Scanner(System.in);
while(true) {
System.out.print("Insert your Command> ");
String CMDcommand = ScanCMD.nextLine();
Process processToCMD = Runtime.getRuntime().exec(CMDcommand);
BufferedReader readerToCMD = new BufferedReader(new InputStreamReader(processToCMD.getInputStream()));
String line;
while ((line = readerToCMD.readLine()) != null) {
System.out.println(line);
}
System.out.println();
readerToCMD.close();
}
}
}
The problem with this code is, it works for straightforward commands,
like ping google.com, or nslookup google.com,
but if I insert nslookup and hit enter to access advance mode, then the response goes off.
Is there a way to fix it?
This should work for you:
ProcessBuilder processBuilder = new ProcessBuilder(CMDcommand); //note, that you can build your command here step by step.
Process process = processBuilder.start();
String response = null;
InputStream inputStream = process.getInputStream();
BufferedReader bufferedInputStream = new BufferedReader(new InputStreamReader(inputStream));
//and then do whatever you want to do.. my example is this:
while(response=bufferedInputStream.readLine()!=null) {
..some code..
}
} catch (IOException e) {
e.printStackTrace();
}
I want to open installed softwares in my pc using a java program. For Example- If I want to open Microsoft Outlook using java program, how would I do it? Thanks in advance!!
You can use Java ProcessBuilder to launch any program.
Example from this site
package com.javacodegeeks.process;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ProcessBuilderExample {
public static void main(String[] args) throws InterruptedException,
IOException {
ProcessBuilder pb = new ProcessBuilder("echo", "This is ProcessBuilder Example from JCG");
System.out.println("Run echo command");
Process process = pb.start();
int errCode = process.waitFor();
System.out.println("Echo command executed, any errors? " + (errCode == 0 ? "No" : "Yes"));
System.out.println("Echo Output:\n" + output(process.getInputStream()));
}
private static String output(InputStream inputStream) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + System.getProperty("line.separator"));
}
} finally {
br.close();
}
return sb.toString();
}
}
powercfg in java program no error no output, when i run it does not shows any output
import java.net.*;
import java.io.*;
public class ip{
public static void main(String args[]) throws IOException{
try{
String inputLine;
Runtime r=Runtime.getRuntime();
Process p=r.exec("cmd.exe /c powercfg/batteryreport");
BufferedReader in=new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
//pingResult += inputLine;
}
}
catch(Exception e){
System.out.println(e);
}
}
}
This is because at least on Windows 7, if you try to run powercfg/batteryreport from cmd, you will get
"Invalid Parameters -- try "/?" for help", if you are NOT on laptop. To see this message from Java you should attach p.getErrorStream()
Try 'powercfg -energy', for example
I'm trying to parse some text that is generated by a command-line command. The command-line command I want to use is Ubuntu's landscape-sysinfo. In an attempt to run this, I'm using the following Java code:
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(new String[] { "landscape-sysinfo" });
The thing I'm not sure of is, how do I get the output of the command-line command into a string that I work with in my Java app?
Thank you so much for your valuable insights!
Hope this one helps its what the Apprentice Queue said
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class BatchExecuteService {
public static void main(String[] args) {
BatchExecuteService batchExecuteService = new BatchExecuteService();
batchExecuteService.run();
}
public void run() {
try {
String cmds[] = {"D:\\test.bat"};
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(cmds);
process.getOutputStream().close();
InputStream inputStream = process.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputStream);
BufferedReader bufferedrReader = new BufferedReader(inputstreamreader);
String strLine = "";
while ((strLine = bufferedrReader.readLine()) != null) {
System.out.println(strLine);
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
Reference