0

I have one Java file named app.java which extracts the servers in my application.
I need to connect to every server in that list and extract the logs. In loop, I have to call script for connecting to every machine. Is it possible to call shell script from java file ? Any suggestions please.

Here I am adding sample example:

for (int m = 0; m < AppDetailsN.length(); ++m)
{
    JSONObject AppUsernIP=AppDetailsN.getJSONObject(m));
    Iterator keys = AppUsernIP.keys();

    while(keys.hasNext()) {
        String key = (String)keys.next();
        System.out.println("key:"+key);
        String value = (String)AppUsernIP.get(key);
        System.out.println("value "+value);
        if(key == "user")
            // Store value to user variable
            // [..]  
        if (key == "ip")
            //store value to IP variable 
            // [..]          
    }

    //Here I want to call the script with that username and IP and password 
}

1 Answer 1

1

You could use Runtime.exec(). Here is a very simple example:

import java.io.*;
import java.util.*;

class Foo {
    public static void main(String[] args) throws Exception {
        // Run command and wait till it's done
        Process p = Runtime.getRuntime().exec("ping -n 3 www.google.de");
        p.waitFor();

        // Grab output and print to display
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

        String line = "";
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    }
}
5
  • instead of "ping -n 3 www.google.de" I gave "sshpass -p xxx ssh -o StrictHostKeyChecking=no UN@IP 'mkdir check'" .. But it is not working
    – Vidya
    Oct 20, 2015 at 7:23
  • Does the sshpass require any interaction from the user? I never used it before, sorry. Keep in mind that my code snippet does not work with shell commands that require interation with the user. It runs a program that finishes by itself and prints the output.
    – ap0
    Oct 20, 2015 at 7:32
  • yes . Because it is remote machine.
    – Vidya
    Oct 20, 2015 at 7:50
  • Then maybe JSch is more of something that you are looking for. I don't have any expirience with it, sorry.
    – ap0
    Oct 20, 2015 at 8:05
  • Have you tried running sshpass in an xterm (or equivalent)? In other words, have java use exec() to fire up an xterm which runs the sshpass script - the script then can get what it needs from the user and, once it exits, the xterm will disappear. -- Caveat: if sshpass is simply asking for a password, then that could get annoying for users. Consider instead setting up an ssh key with no passphrase so the script can connect without asking for any text input.
    – mmusante
    Jul 26, 2017 at 8:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .