Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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 
}
share|improve this question

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);
        }
    }
}
share|improve this answer
    
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 '15 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 '15 at 7:32
    
yes . Because it is remote machine. – Vidya Oct 20 '15 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 '15 at 8:05

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.