How to get average response time IP in linux - java

I have a code that works for Windows, but due to the fact that there is a cmd.exe, it does not work under Linux, what can be fixed?
public static String getAverageTime(String ip) throws IOException {
String command = String.format("ping %s | ForEach-Object {if($_ -match '(?:Average) = (\\d+)'){$Matches[1]}}", ip);
ProcessBuilder builder = new ProcessBuilder(
"powershell.exe", "/c", command);
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new
InputStreamReader(p.getInputStream()));
String averageTime;
averageTime = r.readLine();
if(averageTime == null) {
System.out.println("Wrong IP address");
System.exit(-1);
}
return averageTime;
}

Related

Open git bash using processBuilder and execute command in it

Is it possible in java by using something like ProcessBuilder to open gitbash, write a command (for example git status) and output the results?
I can successfully open git bash by using the following code but i don't know how to write any commands in it.
String[] commands = {"cmd","/C","C:\\Users\\......\\Git\git-bash"};
ProcessBuilder builder = new ProcessBuilder(commands);
builder.redirectErrorStream(true);
Process process = builder.start();
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
try
{
br=new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + System.getProperty("line.seperator"));
}
} finally {
br.close();
}
String outcome = get_output(process.getInputStream());
process.waitFor();
System.out.println("Process finished with outcome = " + outcome);
You just have to change the paths and the git command. But the git-bash output is printed on a separate .txt file because I couldn't read it in any other way.
public class GitBash {
public static final String path_bash = "C:/Program Files/Git/git-bash.exe";
// Create a file Output.txt where git-bash prints the results
public static final String path_file_output_git_bash =
"C:/Users/Utente/Documents/IntelliJ-DOC/IntelliJ_project/Prova/src/main/Git-bash/Output.txt";
public static void main(String[] args) {
// Path to your repository
String path_repository = "cd C:/Users/Utente/Documents/Repository-SVN-Git/Bookkeeper";
// Git command you want to run
String git_command = "git ls-files | grep .java | wc -l";
String command = path_repository + " && " + git_command + " > " + path_file_output_git_bash;
runCommand(command);
}
public static void runCommand(String command) {
try {
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command(path_bash, "-c", command);
Process process = processBuilder.start();
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println(" --- Command run successfully");
System.out.println(" --- Output = " + readFileTxt());
} else {
System.out.println(" --- Command run unsuccessfully");
}
} catch (IOException | InterruptedException e) {
System.out.println(" --- Interruption in RunCommand: " + e);
// Restore interrupted state
Thread.currentThread().interrupt();
}
}
public static String readFileTxt() {
String data = null;
try {
File myObj = new File(path_file_output_git_bash);
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
data = myReader.nextLine();
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println(" --- An error occurred");
e.printStackTrace();
}
return data;
}
}
}
--- EDIT 2021/03/26 ---
Answer without the needs of a .txt file : Read output git-bash with ProcessBuilder in Java

How to get tomcat process id by the port and end that process

As per the below code, I'm trying to get tomcat process id by the port and end that process. I'm given this command in CMD is working but used to java doesn't work. I want to correct way please help me
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("netstat -aon | find /i \"listening\"");
InputStream stdin = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(stdin);
BufferedReader br = new BufferedReader(isr);
String line = null;
System.out.println("<OUTPUT>");
while ( (line = br.readLine()) != null)
System.out.println(line);
System.out.println("</OUTPUT>");
int exitVal = proc.waitFor();
System.out.println("Process exitValue: " + exitVal);
} catch (Throwable t) {
t.printStackTrace();
}
If you are using windows it will be like this. I did not tested for linux but it should work I think if you check commented code.
public static void main(String[] args) throws IOException, InterruptedException {
try {
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec("cmd /c netstat -ano | findstr 8080");
//for linux
//Process proc = rt.exec("/bin/bash -c netstat -ano |grep 8080");
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(proc.getInputStream()));
String line = null;
System.out.println("<OUTPUT>");
if ((line = bufferedReader.readLine()) != null) {
int processIdString = line.lastIndexOf(" ");
String processId = line.substring(processIdString, line.length());
System.out.println("Your process Id to Kill : " + processId);
rt.exec("cmd /c Taskkill /PID" + processId + " /T /F");
//for linux
//rt.exec("/bin/bash -c kill -9 "+processId);
}
System.out.println("<OUTPUT>");
} catch (Exception e) {
System.out.println("Error Occured");
}
}

Run Logstash in Java Program

I have created indexes and fields in ElasticSearch.
I could successfully run Logstash config file to add data from MySQL database table into ElasticSearch using the following command :
bin/logstash -f [PATH TO LOGSTASH CONFIG FILE] -v
I need to run this command from my Java source code. How do I run this logstash config file from Java code?
import java.io.*;
class UserTest{
public static void main(String[] args)
{
try
{
String s = "";
String[] cmd = new String[]{"/bin/sh", "./logstash","-f","loggingConfFile.conf"};
Process processes = Runtime.getRuntime().exec(cmd);
BufferedReader stdInput = new BufferedReader(new InputStreamReader(processes.getInputStream()));
while ((s = stdInput.readLine()) != null)
{
System.out.println(s);
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
Try this code. It works.
try {
ProcessBuilder b1 = new ProcessBuilder("cmd.exe", "/c", "cd \"C:\\elk\\logstash-5.1.2\\bin\" && logstash -f first-pipeline.conf --config.reload.automatic");
b1.redirectErrorStream(true);
Process p1 = b1.start();
BufferedReader r1 = new BufferedReader(new InputStreamReader(p1.getInputStream()));
String line1;
while (true) {
line1 = r1.readLine();
if (line1 == null) { break; }
System.out.println(line1);
}
}catch(Exception e) {
}
Try this and this works fine with few changes to the above mentioned code:
try {
ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "logstash -f --Your file Path-- ");
builder.redirectErrorStream(true);
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line1;
while (true) {
line1 = r.readLine();
if (line1 == null) { break; }
System.out.println(line1);
}
}catch(Exception e) {
e.printStackTrace();
}

how to run command line commands inside java program and copy the output of console into a file?

class cmdln_file {
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("cmd /c dir");
//Process pr = rt.exec("C://apkfiles//new_pro2.apk");
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input.readLine()) != null) {
System.out.println(line);
}
int exitVal = pr.waitFor();
System.out.println("Exited with error code "+exitVal);
} catch(Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
}
}
Your question is not so clear, but if your code runs normally, replace cmd /c dir with cmd /c dir > test.txt

Stop Bufferedreader Process

my packet capture command in linux terminal..
sudo tcpdump -w kbh-ns.pcap -i lo greater 106 and less 106
Process will stop and save captured packet when i Press
^c
I have a code as below that uses BufferedReader to do it
public void SaveCapture() throws IOException
{
List<String> command1 = new ArrayList<String>();
//perintah untuk mecari koneksi ( SIP DIP SPort DPort )
command1.clear();
command1.add("sudo"); command1.add("tcpdump");
command1.add("-w"); command1.add("kbh-ns.pcap"); //write
command1.add("-i"); command1.add("vmnet1"); //interface
command1.add("greater");command1.add("106"); //packet length
command1.add("and");
command1.add("less"); command1.add("106");//packet length
command1.add("-c"); command1.add("20");
ProcessBuilder pb = new ProcessBuilder(command1);
process = pb.start();
ProcessBuilder PB = new ProcessBuilder(command1);
Process TerminalTask = PB.start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
String s;
s = stdInput.readLine();
}
it works if i use
command1.add("-c"); command1.add("5");//number of packets to capture
my quetion :
How to make process stop with ^c command with java?
if i use process.destroy()
private void ButtonStopScanActionPerformed(java.awt.event.ActionEvent evt) {
if (process != null)
{
process.destroy();
TxtAreaKet.setText(TxtAreaKet.getText() + "Complete.. \n");
}
end = System.currentTimeMillis();
try {
ReadPacket();
} catch (IOException ex) {
Logger.getLogger(Receiver1.class.getName()).log(Level.SEVERE, null, ex);
}
TxtAreaKet.setText(TxtAreaKet.getText() + "waktu : "+ ((end - start) / 1000.0) + " ms");
}
private void ReadPacket() throws IOException {
List<String> command1 = new ArrayList<String>();
//perintah untuk mecari koneksi ( SIP DIP SPort DPort )
command1.clear();
command1.add("sudo"); command1.add("tcpdump");
command1.add("-r"); command1.add("kbh-ns.pcap"); //read
command1.add("-n");
ProcessBuilder pb = new ProcessBuilder(command1);
process2 = pb.start();
ProcessBuilder PB = new ProcessBuilder(command1);
Process TerminalTask = PB.start();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process2.getInputStream()));
BufferedReader stdError = new BufferedReader(new InputStreamReader(process2.getErrorStream()));
String s;
long a = 0;
while ((s = stdInput.readLine()) != null)
{
a++;
}
TxtAreaKet.setText(TxtAreaKet.getText() + "Captured Packet : " + a + "\n");
while ((s = stdError.readLine()) != null)
{
TxtAreaKet.setText(TxtAreaKet.getText() + s + "\n");
}
}
that's not really stop my process because..
when i press Stop Scan again
How to make process stop with ^c command with java?
Just call Process.destroy().

Categories