public static void uploadFile ( Session session , String localFile , String remoteFile ) throws Exception { boolean ptimestamp = true ; // exec 'scp -t rfile' remotely String command = "scp " + ( ptimestamp ? "-p" : "" ) + " -t " + remoteFile ; 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 ) { throw new RuntimeException ( ) ; } File _lfile = new File ( localFile ) ; 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 ) { throw new RuntimeException ( ) ; } } // send "C0644 filesize filename", where filename should not include '/' long filesize = _lfile . length ( ) ; command = "C0644 " + filesize + " " ; if ( localFile . lastIndexOf ( ' ' ) > 0 ) { command += localFile . substring ( localFile . lastIndexOf ( ' ' ) + 1 ) ; } else { command += localFile ; } command += "\n" ; out . write ( command . getBytes ( ) ) ; out . flush ( ) ; if ( checkAck ( in ) != 0 ) { throw new RuntimeException ( ) ; } // send a content of lfile FileInputStream fis = new FileInputStream ( localFile ) ; byte [ ] buf = new byte [ 1024 ] ; while ( true ) { int len = fis . read ( buf , 0 , buf . length ) ; if ( len <= 0 ) break ; out . write ( buf , 0 , len ) ; // out.flush(); } fis . close ( ) ; fis = null ; // send '\0' buf [ 0 ] = 0 ; out . write ( buf , 0 , 1 ) ; out . flush ( ) ; if ( checkAck ( in ) != 0 ) { throw new RuntimeException ( ) ; } out . close ( ) ; channel . disconnect ( ) ; }
Upload a file to the remote host via scp .