【无标题】

Windows的图片通过sftp传输到Linux服务器上面

pom.xml

<dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>fastjson</artifactId>
     <version>1.2.70</version>
     <scope>compile</scope>
 </dependency>
 <dependency>
     <groupId>org.netbeans.external</groupId>
     <artifactId>com-jcraft-jsch</artifactId>
     <version>RELEASE220</version>
 </dependency>

主类

private static final String SERVER_HOST = "目标主机IP地址";
private static final String USERNAME = "用户名";
private static final String PASSWORD = "密码";
private static final int PORT = 22; // 默认SSH端口

public static void main(String[] args) {
        JSch jsch = new JSch();
        Session session = null;
        try {
            session = jsch.getSession(USERNAME, SERVER_HOST, PORT);
            session.setPassword(PASSWORD);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
            sftpChannel.connect();

            String url = "https://www.baidu.com/aaa.png"; // 替换为实际的 URL
            String remoteFilePath = "/home//aaa.png";//目标服务器路径

            downloadAndSaveToSFTP(url, remoteFilePath, sftpChannel);

            sftpChannel.disconnect();
            System.out.println("File transferred successfully.");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (session != null && session.isConnected()) {
                session.disconnect();
            }
        }
    }
    public static void downloadAndSaveToSFTP(String url, String remoteFilePath, ChannelSftp sftpChannel) throws Exception {
        URL httpUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
        conn.setUseCaches(false); // 设置不要缓存
        conn.setInstanceFollowRedirects(true);
        conn.setDoInput(true); // 设置是否从httpUrlConnection读入
        conn.setConnectTimeout(30000); // 设置超时时间
        conn.setReadTimeout(30000);

        // 发起GET请求
        conn.setRequestMethod("GET");

        int responseCode = conn.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) { // 成功
            InputStream inputStream = conn.getInputStream();
            sftpChannel.put(inputStream, remoteFilePath, ChannelSftp.OVERWRITE);
        } else {
            throw new Exception("Failed : HTTP error code : " + responseCode);
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值