Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
229 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...