Search code examples
javalinuxcommand-linesql-server-administration

Java, proper approach for controlling Linux server from within Java code?


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


Solution

  • 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