用java实现在一台虚拟机连接另两台虚拟机用密钥形式连接,在远程两台虚拟机上同时生成文件,如果没有文件夹路径新创建路径和文件,还要在远程的多个机器上生成多个不同文件目录和文件名

你可以通过Java代码实现在多台远程虚拟机上连接并创建不同的目录和文件。以下是一个示例代码:

java

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class SSHExample {

    public static void main(String[] args) {
        String[] hosts = {"REMOTE_HOST1", "REMOTE_HOST2"}; // Replace with your remote hosts
        String[] directories = {"/path/to/directory1", "/path/to/directory2"}; // Replace with desired directories
        String[] fileNames = {"file1.txt", "file2.txt"}; // Replace with desired file names
        String username = "USERNAME";
        String privateKey = "/path/to/private/key"; // Private key path

        try {
            for (int i = 0; i < hosts.length; i++) {
                JSch jsch = new JSch();
                jsch.addIdentity(privateKey);

                Session session = jsch.getSession(username, hosts[i], 22);
                session.setConfig("StrictHostKeyChecking", "no");  // Disable host key checking
                session.connect();

                // Command to create the folder and file
                String command = "mkdir -p " + directories[i] + " && touch " + directories[i] + "/" + fileNames[i];

                // Executing the command on the remote machine
                ChannelExec channel = (ChannelExec) session.openChannel("exec");
                channel.setCommand(command);
                channel.connect();
                channel.disconnect();

                session.disconnect();
                System.out.println("File created on " + hosts[i]);
            }

        } catch (JSchException e) {
            e.printStackTrace();
        }
    }
}

在此示例中,hosts数组包含你要连接的远程主机的IP地址或主机名。directories数组包含对应的目录路径,fileNames数组包含对应的文件名。循环遍历每个远程主机,连接并在相应的目录中创建文件。确保你的公钥已添加到远程机器的授权列表中以实现免密码登录。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值