如何使用JSch执行多个操作

我是SSH和JSch的新手。 当我从客户端连接到服务器时,我想做两个任务:

  1. 上传文件(使用ChannelSFTP
  2. 执行命令,例如创建目录,以及搜索MySQL数据库

目前我使用两个单独的shell登录来执行每个任务(实际上我还没有开始编程MySQL查询)。

对于上传相关代码是

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

而对于我的命令

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

我应该在第一个频道之后断开会话,然后打开第二个频道吗? 或者完全关闭会话并开启新会话? 正如我所说,我是新手。

一个SSH会话可以支持任意数量的通道 – 并行和顺序。 (通道标识符大小有一些理论限制,但在实践中你不会遇到它。)这对JSch也有效。 这节省了重做昂贵的密钥交换操作。

因此,在打开新频道之前,通常无需关闭会话并重新连接。 我能想到的唯一原因是当你需要使用不同的凭据登录这两个操作时。

为了保护一些内存,您可能希望在打开exec通道之前关闭SFTP通道。

通过jsch给出多个命令使用shell而不是exec。 shell仅支持连接系统的本机命令。 对于ex,当你连接Windows系统时,你不能使用exec通道给dir这样的命令。 所以最好使用shell。

以下代码可用于通过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(); }