Why doesn't cd command work using Java Jsch?

BenG :

I'm just learning Java and Jsch, and I can get it to run other commands but not cd. The error code returned by the SSHManager sendCommand function is not null, but some unreadable string that is different every time (maybe that means it is null not that familiar with inner workings of Java).

Any idea why not? Similar question here JSch - Why doesn't CD work? but unanswered.

I won't copy and paste the whole SSHManager class here - useful answer with complete code here that I'm trying to follow. Run a command over SSH with JSch

Sample code below:

import SSH.SSHManager;
public class src
{
    int ERROR = 0;
    public static void main(String[] args)
    {
        String username = "debian";
        String password = "temppwd";
        String ipadd = "192.168.7.2";
        SSHManager ssh = new SSHManager(username, password, ipadd, "");
        ssh.connect();

        String out = "";

        //this doesn't work, printing output as bytes to show how weird it is
        out = ssh.sendCommand("cd Desktop");
        System.out.println(out.getBytes());

        //some other test commands
        out = ssh.sendCommand("mkdir test");
        System.out.println(out);
        out = ssh.sendCommand("ls");
        System.out.println(out);
        ssh.sendCommand("logout");
    }
}

Output from the Eclipse Console (bin and Desktop are already there in root directory):

[B@b065c63

bin
Desktop
test
Martin Prikryl :

Each command executed over SSH "exec" channel (what is behind SSHManager.sendCommand) is executed in its own shell. So the commands have no effect on each other.

To execute multiple commands in the same shell, just use an appropriate syntax of your server shell. Most *nix server use semicolon or double-ampersand (with different semantics).

In your case, the double-ampersand would be more appropriate.

cd Desktop && mkdir test && ls

See also Multiple commands using JSch.


Though, if your want to read commands output, you will have problem distinguishing, where output of one commands ends and output of the following commands starts. Let only if you wanted to check command exit code.

Then it's better to execute each command in its own "exec" channel in a way that does not require a context. In your case that means using full paths:

mkdir Desktop/test
ls Desktop

See also How to perform multiple operations with JSch.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=183141&siteId=1