【问题标题】:How to execute shell command using SFTP channel in JSch?如何在 JSch 中使用 SFTP 通道执行 shell 命令?
【发布时间】:2018-12-21 16:24:45
【问题描述】:

我正在尝试列出目录中的所有 *.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();
}

【问题讨论】:

    标签: java shell sftp jsch


    【解决方案1】:

    您的要求有冲突。

    您无法使用 SFTP 执行 shell 命令。
    (在任何情况下都是如此,无论您使用什么语言或库)。


    所以你必须选择。

    • 要么使用“执行通道”运行 find shell 命令。
    • 或通过ChannelSftp.ls 使用纯SFTP 接口(并以编程方式递归到子目录)。这种方法更费力,而且速度会慢很多。另一方面,这将是一种更强大的方式。如果您一开始没有 shell 访问权限,它实际上是唯一的解决方案。更不用说它是独立于平台的(find 命令不是)。

    【讨论】:

      猜你喜欢
      • 2011-08-15
      • 2022-01-27
      • 1970-01-01
      • 1970-01-01
      • 2012-07-16
      • 1970-01-01
      • 1970-01-01
      • 2017-05-05
      • 1970-01-01
      相关资源
      最近更新 更多