java连接linux服务器实现下载和上传文件

Java连接linux服务器实现文件下载到本地 和 本地上传文件到服务器

1、pom文件引入jar包

		<dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh2</artifactId>
            <version>build210</version>
        </dependency>

2、代码实现

package com.example.demo.server;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;

import java.io.IOException;

public class ServerUploadAndDownload {
    public static Connection connection;

    public static void main(String[] args) {
        getSSHConnection("192.168.0.110",22,"root","123456");
        getSSHFile("/root/testdata.txt","D:\\");
        putSSHFile("D:\\","/root/testdata.txt");
    }

    /**
     *实现服务器连接
     * @param host 192.168.0.110
     * @param port 22
     * @param username root
     * @param password 123456
     * @return
     * @throws IOException
     */
    public static void getSSHConnection(String host,int port,String username,String password){
        connection=new Connection(host,port);
        try {
            connection.connect();
            boolean b=connection.authenticateWithPassword(username,password);
            System.out.println(b);
            if (b){
                System.out.println("登录连接成功");
            }else {
                System.out.println("登录连接失败,请检查用户名、密码");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    /**
     *实现下载服务器上的文件到本地指定目录
     * @param fileName 服务器上的文件地址 /root/app/test.txt
     * @param localPath 本地路径:D:\
     * @throws IOException
     */

    public static void getSSHFile(String fileName,String localPath){
        SCPClient scpClient= null;
        try {
            scpClient = connection.createSCPClient();
            //String logPath="cd /root/app/";
            //Session session = conn.openSession();
            //session.execCommand(logPath);//执行shell命令
            scpClient.get(fileName,localPath);
            System.out.println("下载文件成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     *实现上传本地文件到服务器上指定目录
     * @param fileName D:\test.txt
     * @param localPath 服务器地址路径://root/app/
     * @throws IOException
     */
    public static void putSSHFile(String fileName,String localPath){
        SCPClient scpClient= null;
        try {
            scpClient = connection.createSCPClient();
            scpClient.put(fileName,localPath);
            System.out.println("上传文件成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值