java comjcraftjsch ssh判断宿主机路径是否存在不存在就创建
要使用JSch库来执行SSH命令,首先需要确保已将JSch库添加到项目中。
以下是一个示例代码,用于通过SSH连接到远程主机,并判断给定路径是否存在。如果路径不存在,它将创建该路径。
import com.jcraft.jsch.*;
public class SSHExample {
public static void main(String[] args) {
String host = "hostname";
String username = "username";
String password = "password";
String remotePath = "/path/to/check";
try {
JSch jsch = new JSch();
Session session = jsch.getSession(username, host, 22);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
ChannelSftp channelSftp = (ChannelSftp) session.openChannel("sftp");
channelSftp.connect();
try {
channelSftp.cd(remotePath);
System.out.println("Path exists!");
} catch (SftpException e) {
// Path does not exist, create it
channelSftp.mkdir(remotePath);
System.out.println("Path created!");
}
channelSftp.disconnect();
session.disconnect();
} catch (JSchException | SftpException e) {
e.printStackTrace();
}
}
}
请注意,您需要将hostname替换为远程主机的实际主机名或IP地址,将username和password替换为实际的SSH登录凭据。还要将/path/to/check替换为要检查的宿主机路径。
此示例使用JSch库创建一个SSH会话,然后通过SFTP连接到远程主机。它尝试更改到给定的远程路径。如果路径不存在,它会捕获SftpException并创建路径。
请确保您已正确配置JSch库,并将其添加到项目的类路径中
原文地址: https://www.cveoy.top/t/topic/iEXC 著作权归作者所有。请勿转载和采集!