How to perform multiple operations with JSch

元气小坏坏 提交于 2019-12-17 20:24:08

问题


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.


回答1:


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.




回答2:


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();
}


来源:https://stackoverflow.com/questions/7419513/how-to-perform-multiple-operations-with-jsch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!