【问题标题】:How to append data in a SFTP server file using Java如何使用 Java 在 SFTP 服务器文件中附加数据
【发布时间】:2019-02-26 11:10:45
【问题描述】:

我已经尝试了所有可能的方法来将一些内容附加到 SFTP 文件路径中存在的文件中。我收到了成功消息,但找不到更新的文件。 不知道是什么原因。

请在下面找到我的代码:

jsch = new JSch();
jsch.addIdentity(privateKey); 
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
session.setConfig("PreferredAuthentications", "publickey,keyboard-interactive,password");
ProxyHTTP  proxy = new ProxyHTTP(PROXY, 8080);
session.setProxy(proxy);

session.setConfig("StrictHostKeyChecking", "no");
session.setConfig("cipher.s2c", "aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc,aes192-cbc,aes256-cbc,aes256-ctr");
session.setConfig("cipher.c2s", "aes128-ctr,aes128-cbc,3des-ctr,3des-cbc,blowfish-cbc,aes192-cbc,aes256-cbc,aes256-ctr");
session.connect();

sftpChannel = (ChannelSftp)session.openChannel("sftp");
sftpChannel.connect();
if(sftpChannel.getSession().isConnected())
    logger.debug("Remote session established through the channel");

sftpChannel.cd(remoteDirectory);

List<String> list = new ArrayList<>();

ChannelSftp sftp = (ChannelSftp) sftpChannel;
Vector<LsEntry> files = sftp.ls(remoteDirectory);

for (LsEntry entry : files)
{
    if (!entry.getFilename().equals(".") && !entry.getFilename().equals(".."))
    {
        list.add(entry.getFilename());
    }
}

System.out.println(list);

InputStream stream = sftp.get(remoteDirectory + remoteFile);
try {
    BufferedReader br = new BufferedReader(new InputStreamReader(stream));
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
    // read from br
} finally {
    stream.close();
}
Files.write(Paths.get(remoteFile), "CH|OK|en,ch,de,it|CH ".getBytes(), StandardOpenOption.APPEND);
System.out.println("added country to remote path");
sftpChannel.exit();
session.disconnect();

【问题讨论】:

    标签: java sftp jsch


    【解决方案1】:

    使用ChannelSftp.put method overloads 之一,并将mode 参数设置为ChannelSftp.APPEND

    例如:

    String s = "CH|OK|en,ch,de,it|CH ";
    
    sftp.put(new ByteArrayInputStream(s.getBytes()), remoteFile, ChannelSftp.APPEND);
    

    请注意,您的代码甚至无法远程执行您想要的操作。 Files.write 写入本地文件,而不是远程文件。


    强制警告:不要使用StrictHostKeyChecking=no 盲目接受所有主机密钥。那是一个安全漏洞。您将失去对MITM attacks 的保护。

    有关正确(且安全)的方法,请参阅:
    How to resolve Java UnknownHostKey, while using JSch SFTP library?

    【讨论】:

      猜你喜欢
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多