使用JSch上传文件到liunx

本来打算用ftp或者sftp上传,但是都失败了,直到发现了JSch
服务器使用的是阿里云,免费一个月,默认开启了22端口

public static void main(String[] args) {
    String username = "root";
    String password = "********";
    String host = "********";
    int port = 22;

    // 创建JSch对象
    JSch jSch = new JSch();
    Session jSchSession = null;
    ChannelSftp chSftp = null;

    try {
        // 根据主机账号、ip、端口获取一个Session对象
        jSchSession = jSch.getSession(username, host, port);

        // 存放主机密码
        jSchSession.setPassword(password);

        // 去掉首次连接确认
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        jSchSession.setConfig(config);

        // 超时连接时间为3秒
        jSchSession.setTimeout(3000);

        // 进行连接
        jSchSession.connect();

        // 打开SFTP通道
        chSftp = (ChannelSftp)jSchSession.openChannel("sftp");

        // 建立SFTP通道的连接
        chSftp.connect();

        // 设置编码格式
        chSftp.setFilenameEncoding("UTF-8");

        /**
         * 说明:
         * 1、当前文件上传信息没有任何反馈,如果没有异常则代表成功
         * 2、如果需要判断是否读取成功的进度,可参考https://blog.csdn.net/coding99/article/details/52416373?locationNum=13&fps=1
         * 3、将文件上传到服务器中nginx的根目录下
         */
        chSftp.put("E:\\download\\b7dae00ace525b8a12fb3d6b4bdac007.jpeg", "/usr/local/nginx/html/images");

        log.info("文件上传成功");
    } catch (JSchException | SftpException e) {
        log.warn(e.getMessage());
    } finally {

        // 关闭sftpChannel
        if (chSftp != null && chSftp.isConnected()) {
            chSftp.quit();
        }

        // 关闭jschSesson流
        if (jSchSession != null && jSchSession.isConnected()) {
            jSchSession.disconnect();
        }
    }
}

  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值