I am trying to run a Java program to shell out commands on a remote (Linux) machine. I can get the putty.exe to run and then connect to the machine using SSH keys. But am not able to run the actual commands such as "bash" "ps-ef" or "ls -la". Currently using the Java runtime.exec, not sure if using the java.lang.ProcessBuilder would help? What am I doing wrong ? Any help/guidance would be greatly appreciated.. Thanks in advance
package hello;
import java.io.*;
public class RuntimeExample {
public static void main(String args[]) throws IOException {
try{
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(new String[]{"C:\\Users\\yky90455\\Desktop\\putty.exe","abc#login.testserver.helloworld.co.uk","bash", "ps -ef"});
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
System.out.printf("Output of running the command is:");
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
try Jsch From here to get the shell scrips executed from Java to some remote Linux machine. I have worked on this and it was really fun.although you may find little shortage of docs for understanding this but you can overcome that easily.
Also consider ExpectJ which is a wrapper around TCL Expect. The project does not appear to have any active development since mid 2010, but I have used it for SSH in the past.
http://expectj.sourceforge.net/apidocs/expectj/SshSpawn.html
Thanks for all your answers. I tried Ganymed SSH-2 library. It works well for the basic commands on the remote machine. I will have to explore other APIs in case I run into any limitation with SSH-2.
public class triggerPutty {
public static void main(String[] a) {
try {
String command = "putty.exe user#abc.text.com -pw password -m C:\\containing_comman.txt";
Runtime r = Runtime.getRuntime();
Process p = null;
p = r.exec(command);
p.waitFor();
p.destroy();
} catch (Exception e) {
e.printStackTrace();
}
}
}
-m helps to run your command from that file.
You can keep N number of commands in that file.. ## Heading ##
Related
I'm trying to run a shell script (say myscript.sh) from a java program.
when i run the script from terminal, like this :
./myscript.sh
it works fine.
But when i call it from the java program, with the following code :
try
{
ProcessBuilder pb = new ProcessBuilder("/bin/bash","./myScript.sh",someParam);
pb.environment().put("PATH", "OtherPath");
Process p = pb.start();
InputStreamReader isr = new InputStreamReader(p.getInputStream());
BufferedReader br = new BufferedReader(isr);
String line ;
while((line = br.readLine()) != null)
System.out.println(line);
int exitVal = p.waitFor();
}catch(Exception e)
{ e.printStackTrace(); }
}
It doesnt goes the same way.
Several shell commands (like sed, awk and similar commands) get skipped and donot give any output at all.
Question : Is there some way to launch this script in a new terminal using java.
PS : i've found that "gnome-terminal" command launches a new terminal in shell,
But, i'm unable to figure out, how to use the same in a java code.
i'm quite new to using shell scripting. Please help
Thanks in advance
In java:
import java.lang.Runtime;
class CLI {
public static void main(String args[]) {
String command[] = {"/bin/sh", "-c",
"gnome-terminal --execute ./myscript.sh"};
Runtime rt = Runtime.getRuntime();
try {
rt.exec(command);
} catch(Exception ex) {
// handle ex
}
}
}
And the contents of the script are:
#!/bin/bash
echo 'hello!'
bash
Notes:
You'll do this in a background thread or a worker
The last command, in the shell script, is bash; otherwise execution completes and the terminal is closed.
The shell script is located in the same path as the calling Java class.
Don't overrwrite your entire PATH...
pb.environment().put("PATH", "OtherPath"); // This drops the existing PATH... ouch.
Try this instead
pb.environment().put("PATH", "OtherPath:" + pb.environment().get("PATH"));
Or, use the full directories to your commands in your script file.
You must set your shell script file as executable first and then add the below code,
shellScriptFile.setExecutable(true);
//Running sh file
Process exec = Runtime.getRuntime().exec(PATH_OF_PARENT_FOLDER_OF_SHELL_SCRIPT_FILE+File.separator+shellScriptFile.getName());
byte []buf = new byte[300];
InputStream errorStream = exec.getErrorStream();
errorStream.read(buf);
logger.debug(new String(buf));
int waitFor = exec.waitFor();
if(waitFor==0) {
System.out.println("Shell script executed properly");
}
This worked for me on Ubuntu and Java 8
Process pr =new ProcessBuilder("gnome-terminal", "-e",
"./progrm").directory(new File("/directory/for/the/program/to/be/executed/from")).start();
The previous code creates a new terminal in a specificied directory and executes a command
script.sh Must have executable permissions
public class ShellFileInNewTerminalFromJava {
public static void main(String[] arg) {
try{
Process pr =new ProcessBuilder("gnome-terminal", "-e", "pathToScript/script.sh").start();
}catch(Exception e){
e.printStackTrace();
}
}
}
This question already has answers here:
How to run Linux commands in Java?
(9 answers)
Closed 3 years ago.
I am trying to call my rrdtool cmd from a java class, not sure how to go about it.
I have tested my RRDTool cmd from my terminal and it is successful, see below.
rrdtool update mydb.rrd 1385056701:6:5
How do i execute this cmd from a java class?
You can use the below command format to run your Linux command.
Runtime r = Runtime.getRuntime();
Process p = r.exec(yourcmd);
Please go through Running unix command from Java and Unable to run Unix command in Java-Stackoverflow
Hope you get your answers here.
try this
public class ShellTest {
public static void main(String[] args) throws java.io.IOException, java.lang.InterruptedException {
// Get runtime
java.lang.Runtime rt = java.lang.Runtime.getRuntime();
// Start a new process: UNIX command ls
java.lang.Process p = rt.exec("ls");
// Show exit code of process
System.out.println("Process exited with code = " + rt.exitValue());
}
}
also check here for more details
Try like this(As answered by paxdiablo):
public static void main(String args[]) {
String s;
Process p;
try {
p = Runtime.getRuntime().exec("ls -aF");
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
while ((s = br.readLine()) != null)
System.out.println("line: " + s);
p.waitFor();
System.out.println ("exit: " + p.exitValue());
p.destroy();
} catch (Exception e) {}
}
Also check java.lang.Runtime.exec for details.
Executes the specified string command in a separate process.
This is a convenience method. An invocation of the form exec(command)
behaves in exactly the same way as the invocation exec(command, null,
null).
You can use Runtime#exec for this purpose. If you want a Java-like control over the started process, there is a great library called zt-exec that makes handeling processes much easier. The ProcessBuilder is also offering a minor API improvement over Runtime#exec that ships with the Java standard library.
Something you have to take care of is that Java processes come with very little buffer for the in- and output streams what blocks processes once these buffers run full. This happens silently. zt-exec can help you with that.
You can have a look at :
https://github.com/OpenNMS/opennms/blob/master/opennms-rrd/opennms-rrd-rrdtool/opennms-rrdtool-api/src/main/java/org/opennms/netmgt/rrd/rrdtool/JniRrdStrategy.java
for a real life use of rrdtool in java.
Or at
https://code.google.com/p/rrd4j/
For a native version of rrdtool in java.
I runned my rrdtool command in java program as follow:
Process p = null;
try {
ProcessBuilder pb = new ProcessBuilder("/usr/bin/rrdtool","lastupdate", rrdPath);
pb.redirectErrorStream(true);
p = pb.start();
int exitVal = p.waitFor();
if (exitVal == 0)
System.out.println("exitVal of rrdLastUpdate is Successful");
else
System.out.println("exitVal of rrdLastUpdate is Abnormal");
} catch (Exception e) {
System.out.println("Problem in executing rrdlastupdate()");
e.printStackTrace();
}//end of try-catch
I hope this be useful for U :) I worked with some other rrdtool commands in java. if you need more help, I will be happy to help.
I am trying to execute the C code from Java code which is already compiled and executed, but, I am not getting any output from the executable file. Can anyone help me to complete this task?
Code is as follows.
public class Test {
public static void main(String args[]) {
try {
Process processCompile = Runtime.getRuntime().exec("e:/Sample.exe");
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
Try this:
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(processCompile .getInputStream()));
// read the output from the command
System.out.println("EXE OUTPUT");
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
This method would work only if you run the java program with admin privileges.
If you have privileges, then can you try running your process under "cmd" shell (Which is forked by your java process). An implementation do so this is done here "LinuxInteractor" ( But is in linux). Just minor change needed to port to Windows version.
Finding hard and soft open file limits from within jvm in linux (ulimit -n and ulimit -Hn)
I need to obtain the list of the currently running applications on windows using command or java program. for example if MS-Word and Window media player are the applications currently running on the system, then i want the list of these applications using a command or a java program.
Thanks and regards
Vivek Birdi
For windows
WMIC /OUTPUT:C:\ProcessList.txt PROCESS get Caption,Commandline,Processid
Try executing this command from java that will list all currently running process on the file specified
Here is an example how to execute command from java
FYI:
for linux:
ps aux | less
Alternatively you can also use this ready made code for windows:
public static List<String> listRunningProcesses() {
List<String> processes = new ArrayList<String>();
try {
String line;
Process p = Runtime.getRuntime().exec("tasklist.exe /fo csv /nh");
BufferedReader input = new BufferedReader
(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
if (!line.trim().equals("")) {
// keep only the process name
line = line.substring(1);
processes.add(line.substring(0, line.indexOf(""")));
}
}
input.close();
}
catch (Exception err) {
err.printStackTrace();
}
return processes;
}
source :http://www.rgagnon.com/javadetails/java-0593.html
What do you have to do in Java to get the Runtime.exec() to run a program that is on the path? I'm trying to run gpsbabel which I have put into the path (/usr/local/bin).
public class GpxLib {
public static void main(String[] args) {
try
{
Runtime r = Runtime.getRuntime();
Process p = r.exec("gpsbabel -i garmin -f usb: -o gpx -F -");
InputStream is = p.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while (true)
{
String s = br.readLine();
if (s == null)
break;
System.out.println(s);
}
br.readLine();
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
}
I added a call to System.out.println(System.getenv("PATH")); which only prints out
/usr/bin:/bin:/usr/sbin:/sbin
so for some reason /usr/local/bin doesn't show up. Looks like this is a MacOSX question or an Eclipse question, not a Java question. edit: asked this question on superuser instead.
It will inherit the path from the Java process. So whatever environment the Java process has, the spawned process will have as well. Here's how to check the environment:
Map<String, String> env = System.getenv();
for (String envName : env.keySet()) {
System.out.format("%s=%s%n", envName, env.get(envName));
}
Have you set the PATH and exported it ? If you don't export it, then it's not available to subprocesses.
Additionally, you must consume stdout and stderr concurrently, to prevent blocking. Otherwise stuff will work in some circumstances, then your spawned process will output a different quantity of data and everything will grind to a halt.
See this answer for more details.
Here is the solution:
ProcessBuilder proc = new ProcessBuilder("<Directory PAth>" + "Executable.exe");
proc.redirectOutput(ProcessBuilder.Redirect.INHERIT);
proc.directory(fi); //fi = the output directory path
proc.start();
is the path where program\application's excutable is located e.g "C:\MyProg\"