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().
Related
I have to launch console commands from java to publish to verdaccio.
So it works(pretty bad), but for few packages processes stucks. When I destroy them it returns code 137, witch means not enough memory. I watched in profiler, I have much more free heap, then used.
Maybe it's not because not enough memory.
How to understand why it stucks and how to fix it?
protected String execCommand(List<String> command) throws IOException, NpmAlreadyExistException{
ProcessBuilder pb = new ProcessBuilder(command);
File workingFolder = new File(System.getProperty("user.dir"));
pb.directory(workingFolder);
Process process = pb.start();
try {
boolean finished = process.waitFor(60, TimeUnit.SECONDS);
logger.info("PROC FINISHED: " + finished);
if (!finished) {
process.destroyForcibly();
int exitCode = process.waitFor();
logger.info("PROC EXIT CODE: " + exitCode);
return null;
}
} catch (InterruptedException e) {
logger.info("PROCESS WAS INTERRUPTED!!!");
logger.info(e.getMessage());
return null;
}
logger.info("PROC EXIT CODE: " + process.exitValue());
String s;
BufferedReader stdErr = new BufferedReader(new InputStreamReader(process.getErrorStream()));
StringBuilder err = new StringBuilder();
while ((s = stdErr.readLine()) != null) {
err.append("\n").append(s);
}
stdErr.close();
BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder result = new StringBuilder();
while ((s = stdInput.readLine()) != null) {
result.append("\n").append(s);
}
stdInput.close();
process.destroy();
logger.info(String.format("execCommand response [stdin]: %s", result));
logger.info(String.format("execCommand response [stdErr]: %s", err));
if (err.length() != 0) {
if (err.toString().contains("Update the 'version' field in package.json and try again.")) {
throw new NpmAlreadyExistException("Пакет с таким именем и версией уже существует в репозитории.");
}
}
return result.toString();
}
Thank you!
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;
}
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");
}
}
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();
}
I want to be able to make run a system command on Mac OSX from within Java. My code looks like this:
public void checkDisks() throws IOException, InterruptedException {
Process p = Runtime.getRuntime().exec("df -h");
int exitValue = p.waitFor();
System.out.println("Process exitValue:" + exitValue);
BufferedReader reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = reader.readLine();
while (line != null) {
line = reader.readLine();
}
System.out.println(line);
}
This always returns null and an exitValue of 0. Never done this before in Java so any thoughts or suggestions greatly appreciated.
Your code is almost OK, you just misplaced the println
public void checkDisks() throws IOException, InterruptedException {
Process p = Runtime.getRuntime().exec("df -h");
int exitValue = p.waitFor();
System.out.println("Process exitValue:" + exitValue);
BufferedReader reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line = reader.readLine();
while (line != null) {
line = reader.readLine();
System.out.println(line);
}
}
I believe it's what you're trying to achieve.
try this
public void checkDisks() throws IOException, InterruptedException {
Process p = Runtime.getRuntime().exec(new String[]{"df","-h"});
int exitValue = p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(
p.getInputStream()));
String line;
while ((line=reader.readLine()) != null) {
System.out.println(line);
}
System.out.println("Process exitValue:" + exitValue);
}