jsch 跨主機上傳文件(fstp)

/**
        import com.jcraft.jsch.Channel;
        import com.jcraft.jsch.ChannelSftp;
        import com.jcraft.jsch.JSch;
        import com.jcraft.jsch.Session;
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
        String uploadPath = "";//要上傳到那個路徑下
        String localFilePath = "";//要上傳的文件路徑
        String fileName = "";//文件名稱
        String userName = "";//登錄主機用戶名
        String passWord = "";//登錄主機密碼
        String ip = "";//主機地址
        int port = 0;//ftp端口
        Session session = null;
        Channel channel = null;
        JSch jsch = new JSch();
        session = jsch.getSession(userName, ip ,port);
        if (session == null) {
            throw new Exception("session is null");
        }
        session.setPassword(passWord);
        session.setConfig("kex", "diffie-hellman-group1-sha1");
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect(30000);
        try {
            channel = (Channel) session.openChannel("sftp");
            channel.connect(1000);
            ChannelSftp sftp = (ChannelSftp) channel;
            sftp.cd(uploadPath);
            
            OutputStream outstream = sftp.put(fileName);
            InputStream instream = new FileInputStream(new File(localFilePath));
            
            byte b[] = new byte[1024];
            int n;
            while ((n = instream.read(b)) != -1) {
                outstream.write(b, 0, n);
            }
            outstream.flush();
            outstream.close();
            instream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.disconnect();
            if(channel!=null)
            channel.disconnect();
        }
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章