migffp
migffp

Reputation: 21

sshpass command not found when I run it in java

I am trying to run a command to read a string from a file inside a remote address (and I'm sure the file is there), this command works when I run it on the bash but it doesn't work when I run it in my java code.

    Runtime rt = Runtime.getRuntime();
    String[] command;
    String line;

    try {
        command = new String[] {"sh", "-c", "\"sshpass " + "-p " + password + " ssh " + user + "@" + ip + " 'cat " + file.getAbsolutePath() + "'\"" };

        Process mountProcess = rt.exec(command);

        mountProcess.waitFor();

        bufferedReader = new BufferedReader(new InputStreamReader(mountProcess.getInputStream()));
        while ((line = bufferedReader.readLine()) != null) {
            user_list.put(user, line);
        }
        bufferedReader.close();

        bufferedReader = new BufferedReader(new InputStreamReader(mountProcess.getErrorStream()));
        while ((line = bufferedReader.readLine()) != null) {
            LOGGER.debug("Stderr: " + line);
        }
        bufferedReader.close();
    } catch ...

No line is added to my user_list (so the line from getInputStream is null) and I get the following error from the logger in the code:

Stderr: sh: 1: sshpass: not found

If I use the exact same command on the bash it works and it prints the string I need.

sshpass -p password ssh [email protected] 'cat /home/ID/ID'

Anyone knows why this is happening? thanks!

Upvotes: 1

Views: 700

Answers (2)

migffp
migffp

Reputation: 21

When doing this command with java the user is tomcat8 instead of root (when used in the bash terminal)

The solution that worked for me included some flags:

String.format("/usr/local/bin/sshpass -p %s /usr/bin/ssh -q -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no %s@%s 'cat %s'", password, user, ip, file.getAbsolutePath());

Upvotes: 0

glenn jackman
glenn jackman

Reputation: 246774

I'd suggest you don't need to use sh to wrap your command. Try

command = new String[] {"sshpass", "-p", password, "ssh", user + "@" + ip, "cat " + file.getAbsolutePath() };

If you need to use sh, then remove the escaped double quotes from the command string: you are sending those as literal characters:

command = new String[] {
    "sh", 
    "-c", 
    String.format("sshpass -p %s ssh %s@%s 'cat %s'", password, user, ip, file.getAbsolutionPath())
};

If you're still getting "command not found", then you need to either specify the full path to sshpass, or ensure that its directory is in your PATH.

Upvotes: 2

Related Questions