java连接远程给服务器后把对应目录文件另一台远程服务器的目录下,另一台远程服务通过密码登录

要通过Java连接到一个远程服务器,并将目录下的文件复制到另一个远程服务器,你可以使用SSH协议和SCP(Secure Copy Protocol)。以下是一般的步骤:

  1. 导入必要的Java库:

    import com.jcraft.jsch.*;

  2. 编写Java代码连接到远程服务器并进行文件复制:

public class RemoteFileCopy {
    public static void main(String[] args) {
        String sourceHost = "source_remote_host";
        String sourceUser = "source_username";
        String sourcePassword = "source_password";
        String destinationHost = "destination_remote_host";
        String destinationUser = "destination_username";
        String destinationPassword = "destination_password";
        String sourceFilePath = "path_to_source_file";
        String destinationFilePath = "path_to_destination_directory";

        try {
            JSch jsch = new JSch();

            // Connect to the source server
            Session sourceSession = jsch.getSession(sourceUser, sourceHost, 22);
            sourceSession.setPassword(sourcePassword);
            sourceSession.setConfig("StrictHostKeyChecking", "no");
            sourceSession.connect();

            // Connect to the destination server
            Session destinationSession = jsch.getSession(destinationUser, destinationHost, 22);
            destinationSession.setPassword(destinationPassword);
            destinationSession.setConfig("StrictHostKeyChecking", "no");
            destinationSession.connect();

            // Open SCP channel to copy file from source to destination
            ChannelSftp sourceChannel = (ChannelSftp) sourceSession.openChannel("sftp");
            sourceChannel.connect();
            ChannelSftp destinationChannel = (ChannelSftp) destinationSession.openChannel("sftp");
            destinationChannel.connect();

            // Copy file from source to destination
            sourceChannel.get(sourceFilePath, destinationFilePath);

            // Disconnect all channels and sessions
            sourceChannel.disconnect();
            destinationChannel.disconnect();
            sourceSession.disconnect();
            destinationSession.disconnect();

            System.out.println("File copied successfully from source to destination server.");
        } catch (JSchException | SftpException e) {
            e.printStackTrace();
        }
    }
}

在上面的代码中,你需要将 source_remote_hostdestination_remote_host 替换为源服务器和目标服务器的IP地址或主机名,source_usernamesource_passworddestination_usernamedestination_password 分别替换为源服务器和目标服务器的用户名和密码,path_to_source_file 替换为源文件的路径,path_to_destination_directory 替换为目标服务器目标目录的路径。

请确保你的项目中包含JSch库。这个例子假设源服务器和目标服务器都支持SSH连接,并且允许密码验证。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值