I have this code to execute terminal command using java and storing output in string variable but sometimes the output changed. How to get continuous output into a file or string?
When I execute command I get initial output for first output
but in this example when a client connected to access point the output change saying someone connected how to get this output to a variable?
//String output : stores the output of airbase-ng but after a while the
//output will change because it will notify me when something happened < so
//how to store the output again
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.swing.JOptionPane;
class ExecuteShellComand {
public static void main(String[] args) {
ExecuteShellComand obj = new ExecuteShellComand();
String domainName = "google.com";
//in mac oxs
String command = "airbase-ng start mon0";
String output = obj.executeCommand(command);
System.out.println(output);
JOptionPane.showMessageDialog(null,output);
}
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();
}
}
Related
I want to communicate with the linux terminal with java code. I want to store the output and work with it. I implemented the code below following the instructions in given link.
I would expect the complete terminal output of help. But neither for the standard commands, nor for the mosquitto commands I get anything from the input stream. Where is the mistake? Or are you supposed to do it completely differnt?
Stackoverflow link: how to run a command at terminal from java program?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class LinuxInputStream
{
public static void main(String[] args)
{
// Linux Terminal
String prefix = "/bin/bash";
String terminalCommand = "help";
String mosquittoCommand = "mosquitto --help";
ProcessBuilder pb1 = new ProcessBuilder(
new String[] {prefix, terminalCommand});
ProcessBuilder pb2 = new ProcessBuilder(
new String[] {prefix, mosquittoCommand});
try
{
executeCommand(pb1);
}
catch (IOException e)
{
System.out.println("IO Error in Terminal Command execution!");
e.printStackTrace();
}
try
{
executeCommand(pb2);
}
catch (IOException e)
{
System.out.println("IO Error in Mosquitto Command execution!");
e.printStackTrace();
}
}
private static void executeCommand(ProcessBuilder pb) throws IOException
{
Process terminalCommandProcess = pb.start();
InputStream inputStream = terminalCommandProcess.getInputStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(inputStream));
String line;
int i = 0;
while ((line = br.readLine()) != null)
{
System.out.println("Line: " + line);
i++;
}
if (i == 0) System.out.println("Nothing read from input stream");
}
}
Output:
Nothing read from input stream Nothing read from input stream
Just found the solution immidiatly after the post: The "-c" part is missing. Correct code snippet is:
// Linux Terminal
String prefix = "/bin/bash";
String c = "-c";
String terminalCommand = "help";
String mosquittoCommand = "mosquitto --help";
ProcessBuilder pb1 = new ProcessBuilder(
new String[] {prefix, c, terminalCommand});
ProcessBuilder pb2 = new ProcessBuilder(
new String[] {prefix, c, mosquittoCommand});
String command:
python FileName.py <ServerName> userName pswd<b>
Process p = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println(line + "\n");
}
Code is neither terminating nor giving the actual results. ...
This May Be Helpful !
You can use Java Runtime.exec() to run python script, As an example first create a python script file using shebang and then set it executable.
#!/usr/bin/python
import sys
print 'Number of Arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.arv)
print('This is Python Code')
print('Executing Python')
print('From Java')
if you save the above file as script_python and then set the execution permissions using
chmod 777 script_python
Then you can call this script from Java Runtime.exec() like below
import java.io.*;
import java.nio.charset.StandardCharsets;
public class ScriptPython {
Process mProcess;
public void runScript(){
Process process;
try{
process = Runtime.getRuntime().exec(new String[]{"script_python","arg1","arg2"});
mProcess = process;
}catch(Exception e) {
System.out.println("Exception Raised" + e.toString());
}
InputStream stdout = mProcess.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stdout,StandardCharsets.UTF_8));
String line;
try{
while((line = reader.readLine()) != null){
System.out.println("stdout: "+ line);
}
}catch(IOException e){
System.out.println("Exception in reading output"+ e.toString());
}
}
}
class Solution {
public static void main(String[] args){
ScriptPython scriptPython = new ScriptPython();
scriptPython.runScript();
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
try {
String line;
Process p = Runtime.getRuntime().exec
(System.getenv("windir") +"\\system32\\"+"tasklist.exe");
BufferedReader input = new BufferedReader(new InputStreamReader(
p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line); // <-- Parse data here.
}
input.close();
} catch (Exception err) {
err.printStackTrace();
}
}
}
The output of this program shows the process list from windows task manager .....but i also need the Description of the running process ??? How do i get that???
tasklist.exe takes an optional parameter /v for verbose. This outputs the description
Example
taskmgr.exe 5648 Console 1 18,280 K Running 0:00:00 Windows Task Manager
You'll need to update your call to exec() to pass the "/v". Full example including parsing.
public static void main(String[] args) throws IOException {
String taskListExe = System.getenv("windir") + "\\system32\\" + "tasklist.exe";
Process p = Runtime.getRuntime().exec(new String[] { taskListExe, "/v" });
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
Pattern pattern = Pattern.compile("(.*?)\\s+(\\d+).*(\\d+:\\d+:\\d+)\\s+(.*?)");
String line;
while ((line = input.readLine()) != null) {
Matcher matcher = pattern.matcher(line);
if (matcher.matches()) {
System.out.println(String.format("%s, pid = %s, description = %s", matcher.group(1), matcher.group(2),
matcher.group(4)));
}
}
input.close();
}
Output
firefox.exe, pid = 3152, description = cmd - Get the windows running process description In java - Stack Overfl
taskmgr.exe, pid = 5648, description = Windows Task Manager
System Idle Process, pid = 0, description = N/A
I have made a cross compiler using gcc. Now I want the compile and run commands to be executed in a terminal through java program. Here is the code that I am using for this :
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Runterminal {
public static void main(String[] args) {
Process proc;
Process procRun;
String compileCommand = "aarch64-linux-g++ -std=c++14 test.cpp";
String runCommand = "aarch64-linux-objdump -d a.out";
try{
proc = Runtime.getRuntime().exec(compileCommand);
procRun = Runtime.getRuntime().exec(runCommand);
// Read the output
BufferedReader reader =
new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = "";
while((line = reader.readLine()) != null) {
System.out.print(line + "\n");
}
proc.waitFor();
BufferedReader readero =
new BufferedReader(new InputStreamReader(procRun.getInputStream()));
String lineo = "";
while((lineo = readero.readLine()) != null) {
System.out.print(lineo + "\n");
}
procRun.waitFor();
}
catch(Exception e)
{
System.out.println("Exception occurred "+e);
}
}
}
Now my first command is executing since I could see the a.out file being generated. The second command should dump the memory contents of file and it should print in in terminal but I am not seeing any output. Can anyone tell where I am going wrong?
null from bfr.readLine()
However, there is no problem if I run the python file directly on terminal by firing:
python C:/Machine_Learning/Text_Analysis/Ontology_based.py
The last line in my Python script is >> print(data)
The result of the following code is:
Running Python starts:
First Line: null
Picked up _JAVA_OPTIONS: -Xmx512M
package text_clustering;
import java.io.*;
public class Similarity {
/**
*
* #param args
*
*/
public static void main(String[] args){
try{
String pythonPath = "C:/Machine_Learning/Text_Analysis/Ontology_based.py";
//String pythonExe = "C:/Users/AppData/Local/Continuum/Anaconda/python.exe";
ProcessBuilder pb = new ProcessBuilder("python", pythonPath);
Process p = pb.start();
BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
System.out.println("Running Python starts: " + line);
line = bfr.readLine();
System.out.println("First Line: " + line);
while ((line = bfr.readLine()) != null){
System.out.println("Python Output: " + line);
}
}catch(Exception e){System.out.println(e);}
}
}
Usually when executing commands using ProcessBuilder, PATH variable is not taken into consideration. Your python C:/Machine_Learning/Text_Analysis/Ontology_based.py is directly working in your CMD shell because it can locate the python executable using the PATH variable. Please provide the absolute path to python command in your Java code. In below code replace <Absolute Path to Python> with the path to python command and its libraries. Usually it will something like C:\Python27\python in Windows by default
package text_clustering;
import java.io.*;
public class Similarity {
/**
*
* #param args
*
*/
public static void main(String[] args){
try{
String pythonPath = "C:/Machine_Learning/Text_Analysis/Ontology_based.py";
//String pythonExe = "C:/Users/AppData/Local/Continuum/Anaconda/python.exe";
ProcessBuilder pb = new ProcessBuilder(Arrays.asList("<Absolute Path to Python>/python", pythonPath));
Process p = pb.start();
BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
System.out.println("Running Python starts: " + line);
int exitCode = p.waitFor();
System.out.println("Exit Code : "+exitCode);
line = bfr.readLine();
System.out.println("First Line: " + line);
while ((line = bfr.readLine()) != null){
System.out.println("Python Output: " + line);
}
}catch(Exception e){System.out.println(e);}
}
}
Reading from stdin returns null when the script is killed/dies. Do a Process#waitFor and see what the exitValue is. If it isn't 0 then it's highly probable that your script is dying.
I'd try making it work with a dumb script that only writes a value. Make sure that you print all error information from python.
try {
Process p = Runtime.getRuntime().exec(
"python D://input.py ");
BufferedReader in = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
p.waitFor();
} catch (Exception e) {
}
try {
ProcessBuilder pb = new ProcessBuilder("C:/Python27/python", "D://searchTestJava//input.py");
Process p = pb.start();
BufferedReader bfr = new BufferedReader(new InputStreamReader(p.getInputStream()));
System.out.println(".........start process.........");
String line = "";
while ((line = bfr.readLine()) != null) {
System.out.println("Python Output: " + line);
}
System.out.println("........end process.......");
} catch (Exception e) {
System.out.println(e);
}
I tried this one. This script runs a python file with the argument in Java. It also logs about which line, your program is executing. Hope this Helps.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
public class Test {
public static void main(String... args) throws IOException {
ProcessBuilder pb =
new ProcessBuilder("python","samples/test/table_cv.py","1.pdf");
pb.redirectErrorStream(true);
Process proc = pb.start();
Reader reader = new InputStreamReader(proc.getInputStream());
BufferedReader bf = new BufferedReader(reader);
String s;
while ((s = bf.readLine()) != null) {
System.out.println(s);
}
}
}