【问题标题】:How to push the file content using SCP to a remote file directly from the local stream object to a remote file如何使用 SCP 将文件内容直接从本地流对象推送到远程文件到远程文件
【发布时间】:2015-12-25 11:16:56
【问题描述】:

如何使用SCP将文件内容直接从本地流对象推送到远程文件到远程文件,这样就不需要将文件临时存储在本地磁盘上?

目前我正在本地创建流并尝试直接推送到远程服务器,它能够成功建立会话,但 channel.isConnected 会因为未创建远程文件而变得错误,请帮助。

    Runtime rt = Runtime.getRuntime();
    BufferedWriter out= new BufferedWriter(new FileWriter(f));
    Process proc = rt.exec(cmd);       
    BufferedReader stdInput = new BufferedReader(new 
         InputStreamReader(proc.getInputStream()));
    BufferedReader stdError = new BufferedReader(new 
         InputStreamReader(proc.getErrorStream()));

    //Intiate SCP connection

    JSch jsch=new JSch();
    jsch.setConfig("StrictHostKeyChecking", "no");
    Session session=jsch.getSession("userName", "scpServer", 22);        
    UserInfo ui=new MyUserInfo(); //Passing password from this class
    session.setUserInfo(ui);
    session.connect();

    String rfile="/home/npachava/SCPTest/myTest.bson";
    // exec 'scp -f rfile' remotely
    String command="scp -f "+rfile;
    Channel channel=session.openChannel("exec");
    ((ChannelExec)channel).setCommand(command);
    System.out.println("session.getServerVersion()"+session.getServerVersion());;
    System.out.println("session.isConnected() "+session.isConnected());
    System.out.println("channel.isConnected() "+channel.isConnected());
    // get I/O streams for remote scp
    OutputStream outScp=channel.getOutputStream();
    InputStream inScp=channel.getInputStream();

    channel.connect();

    // read the output from the command
    System.out.println("standard output of the command:\n");
    String s = null;
    while ((s = stdInput.readLine()) != null) {
        System.out.println(s);
        out.write(s);
        byte[] b = s.getBytes();
        System.out.println("Bytes Length"+b.length);
        outScp.write(b);



    }
    System.out.println("OutPutSCP"+outScp);
    // read any errors from the attempted command
    System.out.println("standard error of the command (if any):\n");
    while ((s = stdError.readLine()) != null) {
        System.out.println(s);
    }
    out.close();
    outScp.flush();
    outScp.close();
    channel.disconnect();
    session.disconnect();
}

我指的是http://www.jcraft.com/jsch/examples/ScpTo.java.html中提到的例子

【问题讨论】:

  • scp absoluteSourcePathToFile userName@Ip-Addres:/absoluteDestinationpath
  • 在不创建源文件的情况下,我们可以将本地流对象复制到远程文件吗?

标签: java scp jsch


【解决方案1】:

只需使用您的内存流而不是 FileInputStream

在这一行(ScpTo.java 代码,而不是您上面的代码)中,将您的“本地”流对象(例如 ByteArrayInputStream)分配给 fis,而不是创建 FileInputStream

fis=new FileInputStream(lfile);

确保您首先寻找您的信息流的开头。

【讨论】:

  • 谢谢,我已经更新了我用来连接和复制内容的代码。
  • 对不起,我没有得到你的零钱。只需保留原始的ScpTo.java 代码即可。您需要做的就是将FileInputStream 替换为例如ByteArrayInputStream.
猜你喜欢
  • 2013-11-25
  • 2012-07-03
  • 1970-01-01
  • 1970-01-01
  • 2019-11-07
  • 1970-01-01
  • 2019-12-31
  • 2018-03-12
  • 1970-01-01
相关资源
最近更新 更多