如何使用 JSch 执行多项操作
我是 SSH 和 JSch 的新手。当我从客户端连接到服务器时,我想要执行两项任务:
- 上传文件(使用 ChannelSFTP)
- 执行命令,例如创建目录和搜索 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);
我应该在第一个通道之后断开会话,然后打开第二个通道吗?或者完全关闭会话并打开一个新会话?正如我所说,我对此很陌生。
I am new to SSH and JSch. When I connect from my client to the server I want to do two tasks:
- Upload a file (using
ChannelSFTP
) - 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一个 SSH 会话可以支持任意数量的通道 - 并行和顺序。 (通道标识符大小存在一些理论上的限制,但实际上不会达到它。)这对于 JSch 也有效。这可以节省重做成本高昂的密钥交换操作。
因此,在打开新通道之前通常不需要关闭会话并重新连接。我能想到的唯一原因是当您需要使用不同的凭据登录以执行这两个操作时。
不过,为了保护一些内存,您可能需要在打开 exec 通道之前关闭 SFTP 通道。
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.
通过 Jsch 发出多个命令
使用 shell 代替 exec。
Shell 仅支持连接系统的本机命令。
例如,当您连接 Windows 系统时,您无法使用 exec 通道发出诸如
dir
之类的命令。所以还是用shell比较好。
以下代码可用于通过Jsch发送多个命令
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