如何在 JSch 中使用 SFTP 通道执行 shell 命令?
How to execute shell command using SFTP channel in JSch?
我正在尝试列出目录中的所有 *.xml 文件。我先做了 cd
然后试图执行:
find . -type f -name *.xml
但不确定具体怎么做。 Exec 通道周围有一些示例,但有没有办法使用 SFTP 本身进行查找?
String username = "abcd";
String password = "pqrst";
String host = "xxxxxx.xxxx.xxx";
int port = 22;
String SFTPWORKINGDIR = "/xxx/xxx/xxx/xxxx";
Session session = null;
ChannelSftp channelSftp = null;
try {
JSch jSch = new JSch();
session = jSch.getSession(username, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
channelSftp.cd(SFTPWORKINGDIR);
// List all the *xml file.
// --------- Want to execute 'find . -type f -name "*.xml" ' here ---------
/* Vector fileList = channelSftp.ls()
for(int i=0; i<fileList.size();i++){
LsEntry entry = (LsEntry) fileList.get(i);
System.out.println(entry.getFilename());
}*/
} catch (JSchException | SftpException e) {
e.printStackTrace();
}
finally {
if(session != null) session.disconnect();
if(channelSftp != null) channelSftp.disconnect();
}
您的要求有冲突。
您无法使用 SFTP 执行 shell 命令。
(无论您使用什么语言或库,在任何情况下都是如此)。
所以你必须选择。
- 或者 运行 您的
find
shell 命令与“Exec 通道”。
- 或通过
ChannelSftp.ls
使用纯 SFTP 接口(并以编程方式递归到子目录中)。这种方法比较费力,而且速度会慢很多。另一方面,这将是一种更强大的方式。如果您一开始没有 shell 访问权限,这实际上是唯一的解决方案。更不用说它是平台无关的(什么 find
命令不是)。
我正在尝试列出目录中的所有 *.xml 文件。我先做了 cd
然后试图执行:
find . -type f -name *.xml
但不确定具体怎么做。 Exec 通道周围有一些示例,但有没有办法使用 SFTP 本身进行查找?
String username = "abcd";
String password = "pqrst";
String host = "xxxxxx.xxxx.xxx";
int port = 22;
String SFTPWORKINGDIR = "/xxx/xxx/xxx/xxxx";
Session session = null;
ChannelSftp channelSftp = null;
try {
JSch jSch = new JSch();
session = jSch.getSession(username, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
channelSftp.cd(SFTPWORKINGDIR);
// List all the *xml file.
// --------- Want to execute 'find . -type f -name "*.xml" ' here ---------
/* Vector fileList = channelSftp.ls()
for(int i=0; i<fileList.size();i++){
LsEntry entry = (LsEntry) fileList.get(i);
System.out.println(entry.getFilename());
}*/
} catch (JSchException | SftpException e) {
e.printStackTrace();
}
finally {
if(session != null) session.disconnect();
if(channelSftp != null) channelSftp.disconnect();
}
您的要求有冲突。
您无法使用 SFTP 执行 shell 命令。
(无论您使用什么语言或库,在任何情况下都是如此)。
所以你必须选择。
- 或者 运行 您的
find
shell 命令与“Exec 通道”。 - 或通过
ChannelSftp.ls
使用纯 SFTP 接口(并以编程方式递归到子目录中)。这种方法比较费力,而且速度会慢很多。另一方面,这将是一种更强大的方式。如果您一开始没有 shell 访问权限,这实际上是唯一的解决方案。更不用说它是平台无关的(什么find
命令不是)。