你可以通过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
数组包含对应的文件名。循环遍历每个远程主机,连接并在相应的目录中创建文件。确保你的公钥已添加到远程机器的授权列表中以实现免密码登录。