How to monitor VPN disconnection? Java 11 - java

I need my Java program to immediately stop if my VPN disconnects. I understand I can periodically run a command and parse the output, but this seems inefficient. I'm assuming it's possible to setup a receiver/listener instead but all the solutions I come across are Android oriented. Any recommendations?
Here's my approach (run every n seconds):
public boolean isConnected() {
boolean isConnected = false;
try {
Process p = Runtime.getRuntime().exec("cmd.exe /c netsh interface show interface");
BufferedReader stdin = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line;
while ((line = stdin.readLine()) != null) {
if (line.contains("Ethernet 2")) {
List<String> valueList = Arrays.asList(line.split("[\\s]{2,}"));
String connectedOrDisconnected = valueList.get(valueList.indexOf("Ethernet 2") - 2);
System.out.println("connectedOrDisconnected: " + connectedOrDisconnected);
isConnected = Objects.equals(connectedOrDisconnected, "Connected");
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return isConnected;
}

Related

execute julia scripts from Java

I'm coding Julia script with ZeroMQ.
My goal is to communicate with ZMQ between two scripts. Here is an example:
# script1
using ZMQ
ctx = ZMQ.Context()
sockDealer = ZMQ.Socket(ctx, DEALER)
ZMQ.set_identity(sockDealer, "idA")
ZMQ.connect(sockDealer, "tcp://localhost:5555")
ZMQ.send(sockDealer, "hello world!")
ZMQ.close(sockDealer)
ZMQ.close(ctx)
#script2
using ZMQ
function pollrecv(socket::ZMQ.Socket,zmsg::Message)
rc = -1
while true
rc = ccall((:zmq_msg_recv, ZMQ.zmq), Cint, (Ptr{Message}, Ptr{Void}, Cint),
&zmsg, socket.data, ZMQ.ZMQ_DONTWAIT)
if rc == -1
# Base.Libc.EAGAIN = 11
# Problem unsolved: Failure to find Base.Libc.EAGAIN
if !(ZMQ.zmq_errno() == 11)
throw(ZMQ.StateError(ZMQ.jl_zmq_error_str()))
end
return false
else
ZMQ.get_events(socket) != 0 && notify(socket)
break
end
end
return true
end
ctx = ZMQ.Context()
sockRouter = ZMQ.Socket(ctx, ROUTER)
ZMQ.bind(sockRouter, "tcp://*:5555")
fini = false
while !fini
println("listening...")
idSock = Message()
while pollrecv(sockRouter, idSock)
msg = ZMQ.recv(sockRouter)
println("msg recv: " * bytestring(msg))
fini = true
end
sleep(1)
end
ZMQ.close(sockRouter)
ZMQ.close(ctx)
I can execute them with Julia on the command prompt. Everything goes fine. Script 2 can receive the message of Script 1.
Now, I need to execute them from Java. Meaning that I need to create a java project which is just like a controller. Here is my Java project:
public class Container {
private Vector<String[]> commands;
public Container() {
this.commands = new Vector<String[]>();
}
public void addCommand(String[] strs) {
this.commands.addElement(strs);
}
public void execute() {
for(int i = 0; i < this.commands.size(); i++) {
try {
Process p = Runtime.getRuntime().exec(this.commands.get(i));
if(p.waitFor() != 0){
System.err.println("exit value = " + p.exitValue());
}
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line = null;
while((line = in.readLine()) != null){
stringBuffer.append(line + "-");
}
System.out.println(stringBuffer.toString());
} catch (IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
} catch(InterruptedException e){
System.err.println(e);
}
}
}
}
//main
public class Main {
public static void main(String[] args) {
Container c = new Container();
String[] script1 = {"/usr/bin/julia", "/home/thomas/Julia/script1.jl"};
String[] script2 = {"/usr/bin/julia", "/home/thomas/Julia/script2.jl"};
c.addCommand(script1);
c.addCommand(script2);
c.execute();
}
}
However, when I run my java project, I can see that it keeps running but I can't see anything on the console: no result, no message, no error.
I think there is something wrong in my java project.
You'll want to run the two scripts concurrently: script2 is the server script, so it should be running when you run script1. As it is now, Process.waitFor() will wait for script1, the client script, to complete, before executing the server script script2 in the next for iteration.
You could start them as such:
String[] clientScript = { "/usr/bin/julia", "/home/thomas/Julia/script1.jl" };
String[] serverScript = { "/usr/bin/julia", "/home/thomas/Julia/script2.jl" };
Process server = Runtime.getRuntime().exec(serverScript);
Process client = Runtime.getRuntime().exec(clientScript);
and instantiate two threads to read their outputs:
(new ProcessReader(server)).start();
(new ProcessReader(client)).start();
using
public class ProcessReader extends Thread {
private Process p;
public ProcessReader(Process p) {
this.p = p;
}
#Override
public void run() {
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
try {
String line;
while ((line = in.readLine()) != null) {
System.out.println("Read: " + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Although, since the clientScript doesn't produce any output, you could just
start the scripts, and only read the output from the server script - no thread needed.
There's one more thing to consider: the serverScript must be listening... before the clientScript attempts to connect. So you may want to do this:
Process server = Runtime.getRuntime().exec(serverScript);
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
if ( in.readLine().equals("listening...") ) {
Process client = Runtime.getRuntime().exec(clientScript);
String line;
while ( (line=in.readLine()) != null )
System.out.println("Read: " + line );
}
Since this is not a specific answer to your question, this may help to you or other users that attempt to similar jobs.
JuliaCaller is an early stage library for calling Julia from Java. It executes the Julia executable as a Java process and runs a script in the Julia side. This script opens a TCP server that listens on a given port number. Every command, statement or expression sent from Java is then executed and results are sent back to Java in JSON format.
This library also implements the standard javax.script interface, that means, Julia libraries, functions, and programs can run like a scripting language that is implemented in Java (mimics).
Here is the example:
Constants.setProperties(Constants.JULIA_PATH, "/usr/local/bin/julia");
Constants.setProperties(Constants.JULIA_PORT, "8001");
// Creating a scripting interface for Julia
manager = new ScriptEngineManager();
engine = manager.getEngineByName("Julia");
// Sending command 'a = 3' to Julia from Java
engine.eval("a = 3");
// Handling the result in Java
Object a = engine.get("a");
More examples are given in the GitHub page.
Source code with Apache License

Running SoX from Processing/Java on Windows computer

This might be an easy one - but it's driving me nuts at this point. I'm trying to run SoX from Processing which on my mac computer is running smoothly and with no problems. I need to migrate the code to a windows 7 machine but can't get it to work for some reason. Talking to the terminal from processing works fine. I'm in the right folder (sketch data folder where SoX is also intalled) since I can run commands like "dir" etc. and get the right content printed - but as soon as I try to run sox.exe nothing happens (getting an exit value 1). Running sox.exe straight from the cmd terminal works fine. Here is a sample of what I'm trying to do:
void playBackYear (){
soxPlay = "cmd /c sox.exe year.wav -d";
println (soxPlay);
try {
File workingDir = new File(sketchPath("data"));
Process p=Runtime.getRuntime().exec(soxPlay, null, workingDir);
p.waitFor();
BufferedReader reader=new BufferedReader(
new InputStreamReader(p.getInputStream())
);
String line;
while ( (line = reader.readLine ()) != null)
{
println(line);
}
int exitVal = p.waitFor();
System.out.println("Exited with error code "+exitVal);
}
catch(IOException e1) {
System.err.println("Caught IOException: " + e1.getMessage());
System.out.println( "error 1" );
}
catch(InterruptedException e2) {
System.err.println("Caught IOException: " + e2.getMessage());
System.out.println( "error 2" );
}
}
So the questions is what am I doing wrong here?
Any help is appreciated.
I have written a small wrapper application that wraps sox binary in java. If you are interested in the full project, check it out on GitHub: sox java wrapper project
This is, how i have solved the problem:
private List<String> arguments = new ArrayList<String>();
// add sox arguments to this list above
public void execute() throws IOException {
File soxBinary = new File(soXBinaryPath);
if (!soxBinary.exists()) {
throw new FileNotFoundException("Sox binary is not available under the following path: " + soXBinaryPath);
}
arguments.add(0, soXBinaryPath);
logger.debug("Sox arguments: {}", arguments);
ProcessBuilder processBuilder = new ProcessBuilder(arguments);
processBuilder.redirectErrorStream(true);
Process process = null;
IOException errorDuringExecution = null;
try {
process = processBuilder.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
logger.debug(line);
}
} catch (IOException e) {
errorDuringExecution = e;
logger.error("Error while running Sox. {}", e.getMessage());
} finally {
arguments.clear();
if (process != null) {
process.destroy();
}
if (errorDuringExecution != null) {
throw errorDuringExecution;
}
}
}

How can I execute linux terminal command from java?

I want to automatically change the ip address of an Ubuntu 12.04 PC by a program fires at startup. For some certain reasons, I want to code it in Java.
Exactly the solution is written here:
Java - Execute a .SH file
But it does not work in my case. I could not manage to find why,essentially my case is a special case of so called thread, I try to run a sudo-command in linux with
public static void executeCommandLine(String strCommand){
Runtime rt = Runtime.getRuntime();
try {
Process p = rt.exec(strCommand);
if(p==null){
System.out.println("Error in process");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
try {
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
I call this executeCommandLine() function from another function as follows:
public static void changeIpAddress(String strIpAddress, String strRootPassword, String strEthDevice){
String strCommandLine = "";
if(PLATFORM == PLATFORM_LINUX){
strCommandLine = "/bin/echo " + strRootPassword + "| sudo -S /sbin/ifconfig " + strEthDevice + " " + strIpAddress;
}else if(PLATFORM == PLATFORM_WINDOWS){
// TODO: Write for Windows
}else{
System.out.println("OS not supported");
}
System.out.println("Executed command:");
System.out.println(strCommandLine);
executeCommandLine(strCommandLine);
}

How to use java program to run command prompt commands?

this is my first time posting here, so I'm not really sure what to say/ask.
Anyways, I am trying to make a simple java program that runs command prompt commands from the java program, mainly used for ping flood (ping flooding myself).
Here is my current code
public class Core extends JFrame {
JTextField ipTextField;
int packets = 0;
boolean running = false;
public Core() {
super("Fatique");
Container container = getContentPane();
JButton bAttack = new JButton("Start Attack");
JButton bStop = new JButton("Stop Attack");
JPanel jPanel = new JPanel();
container.setLayout(new FlowLayout());
ipTextField = new JTextField("IP Address", 30);
container.add(ipTextField);
bAttack.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String input = ipTextField.getText();
String[] value = input.split(":");
int amountOfPackets = Integer.parseInt(value[1]);
exec("cmd /c" + input + " -t -n " + amountOfPackets);
running = true;
}
});
bStop.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
stop();
}
});
if(!running) {
jPanel.add(bAttack);
} else {
jPanel.add(bStop);
}
add(jPanel);
}
public void exec(String cmd) {
try {
Process p = Runtime.getRuntime().exec(cmd);
System.out.println(getOutput(p) + " - " + getPacketsSent());
} catch (IOException e) {
e.printStackTrace();
}
}
public String getOutput(Process p) {
String output = null;
try {
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
output = line;
packets++;
}
return output;
} catch (IOException e) {
System.err.println(e.getStackTrace());
}
return null;
}
public int getPacketsSent() {
return packets;
}
public void stop() {
exec("cmd /c break");
running = false;
}
public static void main(String[] args) {
Core c = new Core();
c.setSize(500, 300);
c.setVisible(true);
c.setResizable(false);
c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c.setLocationRelativeTo(null);
}
I'm quite new at java, so that might not do what I want it to do.
What I want it to do is I enter an ip address in the textfield, and split it with ":", and after that the amount of packets, for instance
127.0.0.1:100
Though now when I try to use that ip and packet amount, it returns "null - 0" (from exec method), and I'm not even sure if it did anything related to ping.
What I am trying to accomplish is as I already said, ping flood myself, and then output whatever I get as response, though I have no idea if this code does anything even related to that, I mostly use logic when coding java.
public String getOutput(Process p) {
String output = null;
try {
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
output = line;
packets++;
}
return output;
} catch (IOException e) {
System.err.println(e.getStackTrace());
}
return null;
}
Could someone explain me why my code code is not working how I want it to work? Please don't judge, as I already said, I'm quite new to java programming.
EDIT: Here is a quick "informative" explanation of what I am trying to accomplish.
I type in an ip address and how many packets I want to send. In this explanation, I am using localhost ip, and 5 packets.
I start the attack. At this part, I want the program to run cmd prompt command
ping 127.0.0.1 -t -n 5
127.0.0.1 being the ip that I put in the textfield in my program, and 5 is the amount of packets I put in the textfield.
I started the attack, so this is what should happen in the command prompt:
The language is Finnish, but still the same thing.
This is the basic explanation of what I am trying to accomplish, hopefully someone understood and can help/tell why my code is not working, or is working but not printing the proper lines in eclipse console.
There is a problem with your getOutput method. It looks like you intend to collect every line of output. But in fact, since you are assigning line to output, you will only return the last line before the end of stream.
To fix this, change
output = line;
to
output += line + "\n";
Or to be more correct:
output += line + LINE_SEPARATOR;
where you previously declared the latter as:
final String LINE_SEPARATOR = System.getProperty("line.separator");
That doesn't directly explain why you are getting null, but that might be because the command you are running is writing output to the 'error' stream rather than the 'output' stream.
Try something like this:
try {
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("ping 192.168.16.67");
InputStream in = p.getInputStream();
OutputStream out = p.getOutputStream ();
InputStream err = p.getErrorStream();
p.destroy();
} catch(Exception exc) {}
Then, you'll have to read the out variable to parse the ping command output continuously.
bAttack.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String input = ipTextField.getText();
String[] value = input.split(":");
int amountOfPackets = Integer.parseInt(value[1]);
try {
p=Runtime.getRuntime().exec("ping -n "+amountOfPackets+" "+value[0]);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
running = true;
}
Just a small modification of your code. get output is as:
public String getOutput(Process p) {
String output = null;
try {
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
output =output+ line+"\n";
packets++;
}
return output;
} catch (IOException e) {
System.err.println(e.getStackTrace());
}
return null;
}
Here output is JTextArea I have taken to display the output of PING process. I cannot show you the output because I lack reputation.
I don't know why first line is null. Anyway, it works.
Hope this help you. Have good time coding.

Set time out for mysql service it couldn't started/stopped after sometime using java program in windows

In windows,I am trying to write a java program to stop mysql service and update my.ini file, then start the mysql service. It can works successfully. I can check the status of mysql service, that is started/stopped by using java code. If any unpredicted conditions occurs, the specified service couldn't started/stopped and also it can looping. Please check my code:
public void processStatusOfMySQLService() {
String[] commandScript = { "cmd.exe", "/c", "sc", "query", "MySQL" };
String STATE_PREFIX = "STATE : ";
Process process;
try {
process = new ProcessBuilder(commandScript).start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
// check that the temp string contains the status prefix
int indexStatus = line.indexOf(STATE_PREFIX);
if (indexStatus >= 0) {
// compare status number to one of the states
String stateStr = line.substring(
indexStatus + STATE_PREFIX.length(),
indexStatus + STATE_PREFIX.length() + 1);
int state = Integer.parseInt(stateStr);
switch (state) {
case (1):
// service stopped
break;
case (4):
// service started
break;
case (2):
case (3):
// service pending
try {
Thread.sleep(1000);
processStatusOfMySQLService();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
br.close();
isr.close();
is.close();
process.destroy();
}
I need to break from the loop after a specific time if the service can't started/stopped. How to set an appropriate time out value???

Categories

Resources