scp via java

前端 未结 15 994
粉色の甜心
粉色の甜心 2020-11-27 13:06

What is the best method of performing an scp transfer via the Java programming language? It seems I may be able to perform this via JSSE, JSch or the bouncy castle java libr

15条回答
  •  旧巷少年郎
    2020-11-27 14:01

    JSch is a nice library to work with. It has quite an easy answer for your question.

    JSch jsch=new JSch();
      Session session=jsch.getSession(user, host, 22);
      session.setPassword("password");
    
    
      Properties config = new Properties();
      config.put("StrictHostKeyChecking","no");
      session.setConfig(config);
      session.connect();
    
      boolean ptimestamp = true;
    
      // exec 'scp -t rfile' remotely
      String command="scp " + (ptimestamp ? "-p" :"") +" -t "+rfile;
      Channel channel=session.openChannel("exec");
      ((ChannelExec)channel).setCommand(command);
    
      // get I/O streams for remote scp
      OutputStream out=channel.getOutputStream();
      InputStream in=channel.getInputStream();
    
      channel.connect();
    
      if(checkAck(in)!=0){
        System.exit(0);
      }
    
      File _lfile = new File(lfile);
    
      if(ptimestamp){
        command="T "+(_lfile.lastModified()/1000)+" 0";
        // The access time should be sent here,
        // but it is not accessible with JavaAPI ;-<
        command+=(" "+(_lfile.lastModified()/1000)+" 0\n");
        out.write(command.getBytes()); out.flush();
        if(checkAck(in)!=0){
          System.exit(0);
        }
      }
    

    You can find complete code at

    http://faisalbhagat.blogspot.com/2013/09/java-uploading-file-remotely-via-scp.html

提交回复
热议问题