Java服务器通过SCP连接Linux服务器上传、下载文件

java通过SCP链接Linux服务器上传文件

    Connection connection = new Connection(ip,port);

    try {
        connection.connect();
        boolean isAuthenticated = connection.authenticateWithPassword(name,password);
        if(!isAuthenticated){
            System.out.println("连接建立失败");
            return ;
        }
        SCPClient scpClient = new SCPClient(connection);
        SCPOutputStream os = scpClient.put(f.getName(),length,remoteTargetDirectory,mode);
        byte[] b = new byte[4096];
        FileInputStream fis = new FileInputStream(f);
        int i;
        while ((i = fis.read(b)) != -1) {
            os.write(b, 0, i);
        }
        os.flush();
        fis.close();
        os.close();
        connection.close();
    }catch (IOException e) {
        e.printStackTrace();
    }

下载文件

    Connection connection = new Connection(ip,port);

    try {
        connection.connect();
        boolean isAuthenticated = connection.authenticateWithPassword(name,password);
        if(!isAuthenticated){
            System.out.println("连接建立失败");
            return ;
        }
        SCPClient scpClient = new SCPClient(connection);
        SCPOutputStream os = scpClient.put(f.getName(),length,remoteTargetDirectory,mode);
        byte[] b = new byte[4096];
        FileInputStream fis = new FileInputStream(f);
        int i;
        while ((i = fis.read(b)) != -1) {
            os.write(b, 0, i);
        }
        os.flush();
        fis.close();
        os.close();
        connection.close();
        System.out.println("upload ok");
    } catch (IOException e) {
        e.printStackTrace();
    }

相关jar包:

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

完整代码:

/**
 * java服务器通过SCP上传文件至Linux服务器
 */
public class ScpClient {

    private static ScpClient instance;

    private String ip;

    private int port;

    private String name;

    private String password;

    /**
     * 私有化默认构造函数
     * 实例化对象只能通过getInstance
     */
    private ScpClient(){

    }

    /**
     * 私有化有参构造函数
     * @param ip 服务器ip
     * @param port 服务器端口 22
     * @param name 登录名
     * @param password 登录密码
     */
    private ScpClient(String ip,int port,String name,String password){
        this.ip = ip ;
        this.port = port;
        this.name = name;
        this.password = password;
    }

    /**
     * download
     * @param remoteFile 服务器上的文件名
     * @param remoteTargetDirectory 服务器上文件的所在路径
     * @param newPath 下载文件的路径
     */
    public void downloadFile(String remoteFile, String remoteTargetDirectory,String newPath){
        Connection connection = new Connection(ip,port);

        try {
            connection.connect();
            boolean isAuthenticated = connection.authenticateWithPassword(name,password);
            if(isAuthenticated){
                SCPClient scpClient = connection.createSCPClient();
                SCPInputStream sis = scpClient.get(remoteTargetDirectory + "/" + remoteFile);
                File f = new File(newPath);
                if(!f.exists()){
                    f.mkdirs();
                }
                File newFile = new File(newPath + remoteFile);
                FileOutputStream fos = new FileOutputStream(newFile);
                byte[] b = new byte[4096];
                int i;
                while ((i = sis.read(b)) != -1){
                    fos.write(b,0, i);
                }
                fos.flush();
                fos.close();
                sis.close();
                connection.close();
                System.out.println("download ok");
            }else{
                System.out.println("连接建立失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     *  获取服务器上相应文件的流
     * @param remoteFile 文件名
     * @param remoteTargetDirectory 文件路径
     * @return
     * @throws IOException
     */
    public SCPInputStream getStream(String remoteFile, String remoteTargetDirectory) throws IOException {
        Connection connection = new Connection(ip,port);
        connection.connect();
        boolean isAuthenticated = connection.authenticateWithPassword(name,password);
        if(!isAuthenticated){
            System.out.println("连接建立失败");
            return null;
        }
        SCPClient scpClient = connection.createSCPClient();
        return scpClient.get(remoteTargetDirectory + "/" + remoteFile);
    }

    /**
     * 上传文件到服务器
     * @param f 文件对象
     * @param length 文件大小
     * @param remoteTargetDirectory 上传路径
     * @param mode 默认为null
     */
    public void uploadFile(File f, long length, String remoteTargetDirectory, String mode) {
        Connection connection = new Connection(ip,port);

        try {
            connection.connect();
            boolean isAuthenticated = connection.authenticateWithPassword(name,password);
            if(!isAuthenticated){
                System.out.println("连接建立失败");
                return ;
            }
            SCPClient scpClient = new SCPClient(connection);
            SCPOutputStream os = scpClient.put(f.getName(),length,remoteTargetDirectory,mode);
            byte[] b = new byte[4096];
            FileInputStream fis = new FileInputStream(f);
            int i;
            while ((i = fis.read(b)) != -1) {
                os.write(b, 0, i);
            }
            os.flush();
            fis.close();
            os.close();
            connection.close();
            System.out.println("upload ok");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 单例模式
     * 懒汉式
     * 线程安全
     * @return
     */
    public static ScpClient getInstance(){
        if(null == instance){
            synchronized (ScpClient.class){
                if(null == instance){
                    instance = new ScpClient();
                }
            }
        }
        return instance;
    }

    public static ScpClient getInstance(String ip,int port,String name,String password){
        if(null == instance){
            synchronized (ScpClient.class){
                if(null == instance){
                    instance = new ScpClient(ip,port,name,password);
                }
            }
        }
        return instance;
    }

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

demo:https://github.com/running17/scp

  • 4
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要将文件JavaLinux服务器的指定路径,可以使用SSH(Secure Shell)库和协议进行远程连接文件输。下面是一个简单的示例代码,展示了如何使用JSch库在Java中进行文件: ```java import com.jcraft.jsch.*; public class FileUploader { public static void main(String[] args) { String hostname = "服务器地址"; int port = 22; String username = "登录用户名"; String password = "登录密码"; String localFilePath = "本地文件路径"; String remoteDirectory = "远程服务器上的目标文件夹路径"; JSch jsch = new JSch(); try { Session session = jsch.getSession(username, hostname, port); session.setConfig("StrictHostKeyChecking", "no"); session.setPassword(password); session.connect(); Channel channel = session.openChannel("sftp"); channel.connect(); ChannelSftp sftpChannel = (ChannelSftp) channel; sftpChannel.cd(remoteDirectory); // 切换到远程服务器上的目标文件夹路径 sftpChannel.put(localFilePath, ""); // 将本地文件到指定路径,指定空字符串表示保持原有文件名 sftpChannel.disconnect(); session.disconnect(); System.out.println("文件成功!"); } catch (JSchException | SftpException e) { e.printStackTrace(); } } } ``` 在上述代码中,你需要将代码中的服务器地址、登录用户名、登录密码、本地文件路径以及远程服务器上的目标文件夹路径替换为你自己的实际设置。 这个例子使用JSch库建立与远程服务器的SSH连接,并使用SFTP协议进行文件输。首先,通过创建一个Session对象,设置登录用户名、服务器地址和端口号,并使用密码进行身份验证。然后,打开一个sftp通道,连接到远程服务器。通过调用cd()方法切换到目标文件夹路径。最后,使用put()方法将本地文件到指定的远程路径。完成后,断开sftp通道和SSH会话。 希望这个示例能对你有所帮助!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值