简体   繁体   中英

How to perform multiple operations with JSch

I am new to SSH and JSch. When I connect from my client to the server I want to do two tasks:

  1. Upload a file (using ChannelSFTP )
  2. Perform commands, like creating a directory, and searching through a MySQL database

At the moment I am using two separate shell logins to perform each task (actually I haven't started programming the MySQL queries yet).

For the upload the relevant code is

session.connect();

Channel channel=session.openChannel("sftp");
channel.connect();
ChannelSftp c=(ChannelSftp)channel;
c.put(source, destination);

And for the command I have

String command = "ls -l";//just an example 
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);

Should I disconnect the session after the first channel and then open the second channel? Or close the session entirely and open a new session? As I said, I'm new to this.

One SSH session can support any number of channels - both in parallel and sequentially. (There is some theoretical limit in the channel identifier size, but you won't hit it in practice.) This is also valid for JSch. This saves redoing the costly key exchange operations.

So, there is normally no need to close the session and reconnect before opening a new channel. The only reason I can think about would be when you need to login with different credentials for both actions.

To safe some memory, you might want to close the SFTP channel before opening the exec channel, though.

To give multiple commands through Jsch use shell instead of exec. Shell only support native commands of the connecting system. For example, when you are connecting windows system you can't give commands like dir using the exec channel. So it is better to use shell.

The following code can be used to send multiple commands through Jsch

Channel channel = session.openChannel("shell");
OutputStream ops = channel.getOutputStream();
PrintStream ps = new PrintStream(ops, true);

channel.connect();
ps.println("mkdir folder");
ps.println("dir");
//give commands to be executed inside println.and can have any no of commands sent.
ps.close();

InputStream in = channel.getInputStream();
byte[] bt = new byte[1024];

while (true) {
    while (in.available() > 0) {
        int i = in.read(bt, 0, 1024);
        if (i < 0) {
            break;
        }
        String str = new String(bt, 0, i);
        //displays the output of the command executed.
        System.out.print(str);

    }
    if (channel.isClosed()) {
            break;
    }
    Thread.sleep(1000);
    channel.disconnect();
    session.disconnect();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM