2

I've been tasked with setting up an automated system that will have to do some things on the Linux server that, from my understanding and research thus far are not able to easily be done from within Java, such as mounting a hard drive on the linux server. I have used some SSH over Java libraries but found them a bit difficult to use reliably. I can run the java app directly on the linux server so I'm wondering if there is a better way to make the needed calls to the server than over SSH. Any advice would be appreciated

Rick
  • 16,612
  • 34
  • 110
  • 163

2 Answers2

2

Runtime.getRuntime().exec("some linux command");


Example:
jcomeau@intrepid:/tmp$ cat /tmp/test.java; javac test.java; java test
import java.net.*;
import java.io.*;
public class test {
 public static void main(String args[]) throws Exception {
  String line;
  Process process = Runtime.getRuntime().exec("ls");
  BufferedReader process_out = new BufferedReader(
   new InputStreamReader(process.getInputStream()));
  while ((line = process_out.readLine()) != null)
   System.out.println(line);
  process.waitFor();
 }
}
bin
hash.class
hash.java
hsperfdata_jcomeau
profile
test.class
test.java
tmpe66f4e
tmplvOd2n
tmpn8FI2Q
tmpoYaciK
tmpx27knK
vmlinux
繁體中文.txt
jcomeau_ictx
  • 37,688
  • 6
  • 92
  • 107
  • Also, can this give the response back from the server? – Rick Jun 21 '11 at 07:18
  • 1
    The response come in the usual way for Unix programs. You can read the standard output and standard error from the program, and get the exit code. – Thorbjørn Ravn Andersen Jun 21 '11 at 07:24
  • It works for me, however I'm wondering is there a way I can do a command like `"cd /some/directory"` to where it will go into that directory for the next time I run a command. Also, I am wondering if I can do something as `su someuser` then be able to enter the password so I can continue doing inputs as that user, I have tried this but its not working – Rick Jun 21 '11 at 17:18
  • I think I found an answer to the above question: http://www.webmasterworld.com/linux/3613813.htm allows me to run a terminal basically from Java, really cool.. thanks for all the help, this will make my life a lot easier :) – Rick Jun 21 '11 at 17:36
1

There are plenty of Linux webadmin tools that allow this sort of administration - Google's top hit is Webmin - written in Perl or PHP. Unless you need to integrate with existing a java code on the server I think I'd look at adapting one of these rather than starting from scratch in a language that really isn't well suited to this type of task.

Don't underestimate the potential security risks of this system - another advantage to building on the work of others.

Duncan McGregor
  • 17,665
  • 12
  • 64
  • 118
  • I just need a way to control it from Java code, if a tool such as Webmin has an API I can access through Java then thats all I would need – Rick Jun 21 '11 at 07:16