Run A .sh script from java - java

I have a game, and I am going to enable auto-restarting features. It will happen every 24 hours, which is easy to make. However, the problem is, I don't know how to open run "run.sh" (which executes the Java Game Server).
The code is going to shut down everything first, and right before System.exit is called, it should open the run.sh in a new terminal. How would I do this?
This is the method I am currently using, but it's giving me this error.
public static boolean start() {
try {
List<String> command = new ArrayList<String>();
command.add("cd /root/Dropbox/[SALLESY] 742 Server");
command.add("java -Xmx1024m -Xss2m -Dsun.java2d.noddraw=true -XX:+DisableExplicitGC -XX:+AggressiveOpts -XX:+UseAdaptiveGCBoundary -XX:MaxGCPauseMillis=500 -XX:SurvivorRatio=16 -XX:+UseParallelGC -classpath bin:data/libs/* com.sallesy.Application");
ProcessBuilder builder = new ProcessBuilder(command);
Process proc = builder.start();
BufferedReader read = new BufferedReader(new InputStreamReader(
proc.getInputStream()));
try {
proc.waitFor();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
while (read.ready()) {
System.out.println(read.readLine());
}
} catch (Exception e) {
System.out.println(e.getMessage());
return false;
}
return true;
}
Error:
sh script.sh
Cannot run program "cd /root/Dropbox/[SALLESY] 742 Server": error=2, No such file or directory
Could not start a new session...

Try escaping the string:
"cd /root/Dropbox/\[SALLESY\]\ 742\ Server"

Nice game m8 did u make it urself!!?
also here :^)
"cd /root/Dropbox/\[SALLESY\]\ 742\ Server"

Related

run cmd command as administrator through java program

I need to build a java program to reset network in windows 10, this command needs cmd to be opened as administrator I tried to build it, but it gives me this error
Cannot run program "runas /profile /user:Administrator "cmd.exe /c Powrprof.dll,SetSuspendState"": CreateProcess error=2, The system cannot find the file specified
this is my code
try {
String[] command
= {
"runas /profile /user:Administrator \"cmd.exe /c Powrprof.dll,SetSuspendState\"",};
Process p = Runtime.getRuntime().exec(command);
new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
PrintWriter stdin = new PrintWriter(p.getOutputStream());
stdin.println("netsh winsock reset");
stdin.close();
int returnCode = p.waitFor();
System.out.println("Return code = " + returnCode);
stat_lbl.setText("Network reset Successfully");
} catch (IOException | InterruptedException e) {
System.out.println(e.getMessage());
}
I don't understand what the problem is and how can I resolve it
You're giving the command as an array with a single element, which is treated as a single command. You're already giving the command as an array - split it accordingly, where runas is the command, and everything else is an argument to runas:
String[] command = {
"runas",
"/profile",
"/user:Administrator",
"cmd.exe /c Powrprof.dll,SetSuspendState",
};
Note that you don't have to add quotes to the last argument.
You can make your program a bit better by using ProcessBuilder. Now you're redirecting streams yourself, but you can easily let ProcessBuilder handle that for you:
Process p = new ProcessBuilder(command).inheritIO().start();
PrintWriter stdin = new PrintWriter(p.getOutputStream());
stdin.println("netsh winsock reset");
stdin.close();
int returnCode = p.waitFor();
System.out.println("Return code = " + returnCode);

SOCAT command tailing from java app isn't working

Here is my runCommand that takes Linux command input as a string
public static ArrayList<String> runCommand(String command) {
ArrayList<String> arrayList = new ArrayList<>();
try {
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
arrayList.add(line);
System.out.println(line);
}
int exitCode = process.waitFor();
System.out.println("\nExited with error code : "+exitCode);
System.out.println();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return arrayList;
}
It is working great with normal command like ls or sudo lsof -t -i:132 or other. Even tailing live log from ping google.com. My socat command
sudo SOCAT_SOCKADDR=192.168.11.131 socat -d -d -T 10 UDP4-LISTEN:132,reuseaddr,fork UDP4:192.168.11.130:130,bind=192.168.11.131:133
(-d -d for verbose) in terminal creates socat process and tails the logs in terminals like incoming connection or connection status. but if I run this command via my runCommand(), this isn't printing anything in the terminal where the java jar application is running. And it worked fine for other cases of commands.
I tried placing the process.waitFor() before reading the loop but nothing. What is the problem here? my main goal is to parse the live-tailed log and do some other stuff depending on that.

How to run .sh file, using process builder?

I already create the .sh file, and the inside is:
sudo iptables --flush
sudo iptables -A INPUT -m mac --mac-source 00:00:00:00:00:00 -j DROP
It works normally when I run it on the terminal, but when I use processbuilder, it didn't do anything. No error, but didn't happen anything, this is the code on my java:
Process pb = new ProcessBuilder("/bin/bash","/my/file.sh").start();
I already looking for the answer, but I still failed to run the .sh file, even I do the same thing with people that already done it.
Sorry if this is a bad question, thank you.
Are you sure that the bash is not run? Do you checked the Process object returned by the startmethod? You can get the output value, the output stream, etc. from this objects.
Check your streams and exitvalue for errors... sudo is probably the problem here.
Not necessarily the best code but it gets the job done. Executes a process, takes the process.streams and prints them to System.out. Might helpt to find out what the issue actually is atlest.
ProcessBuilder pb = new ProcessBuilder(args);
pb.redirectErrorStream(true);
final Process proc = pb.start();
final StringBuilder builder = new StringBuilder("Process output");
final Thread logThread = new Thread() {
#Override
public void run() {
InputStream is = proc.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
try {
String line;
do {
line = reader.readLine();
builder.append("");
builder.append(line == null ? "" : line);
builder.append("<br/>");
} while(line != null);
} catch (IOException e) {
builder.append("Exception! ").append(e.getMessage());
} finally {
try {
reader.close();
} catch (IOException e) {
builder.append("Exception! ").append(e.getMessage());
}
}
}
};
logThread.start();
int retVal = proc.waitFor();
System.out.println(builder.toString());
From Java API Runtime : http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html
// Java runtime
Runtime runtime = Runtime.getRuntime();
// Command
String[] command = {"/bin/bash", "/my/file.sh"};
// Process
Process process = runtime.exec(command);
Also you should be careful with sudo commands that may ask for root password.

How to execute dos commands in java with administrative privilege?

I was developing a project in Java to scan the File System and this involves executing dos commands in java with administrative privilege.
I already wrote the program to execute simple dos commands in Java.
public class doscmd {
public static void main(String args[]) {
try {
Process p = Runtime.getRuntime().exec("cmd /C dir");
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
} catch (IOException e1) {
} catch (InterruptedException e2) {
}
System.out.println("Done");
}
}
But as you can see this does not allow to execute elevated commands.
I am developing the project in Netbeans IDE and i was hoping if any of you folks could tell me if there is any code in java to get admin privilege instead of converting the file to .exe and then clicking run as administrator.
Your JVM needs to be running with admin-privileges in order to start a process with admin-privileges.
Build your code and run it as an administrator - every process spawned by your class will have administrator privileges as well.
try this code, it works for me:
String command = "cmd /c start cmd.exe";
Process child = Runtime.getRuntime().exec(command);
OutputStream output = child.getOutputStream();
output .write("cd C:/ /r/n".getBytes());
output .flush();
output .write("DIR /r/n".getBytes());
output .close();

Running a batch file by java

I just wanted to run a batch file using java code in win7. I can run .exe files with the code but u know it doesn't work with a batch. Where is the problem? You know even cmd.exe doesn't start with that command. But I can run other exe files, I've tried some. The code is this (with try and catch is that): none of them worked!
Runtime.getRuntime().exec("cmd.exe /c demo.bat");
Runtime.getRuntime().exec("demo.bat");
i tried to do work with process and i wrote the code below. it retuened
java.lang.IllegalThreadStateException:process has not exited
at java.lang.ProcessImpl.exitValue(Native Method)
at Test.Asli.main(Asli.java:38)
this is the code:
try{
Runtime rt = Runtime.getRuntime();
Process proc= rt.exec("C:\\Windows\\System32\\cmd.exe");
int b = proc.exitValue();
// int exitVal = proc.exitValue();
//System.out.println("Process exitValue: " + exitVal);}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
Try the following:
String[] cmd = {"cmd.exe", "/c", "demo.bat");
Runtime.getRuntime().exec(cmd);
I always prefer splitting the command and the parameters myself. Otherwise it is done by splitting on space which might not be what you want.
Try this:
Runtime.getRuntime().exec("cmd.exe /c start demo.bat");
Use this:
try {
Process p = Runtime.getRuntime().exec("C:PATH/TO/FILE/yourbatchfile.bat");
} catch(Exception e) {
e.printStackTrace();
}
It even hides the annoying prompt window (if you want that)

Categories

Resources