JSch 获取远端配置文件

601 阅读1分钟

JSch 是 SSH2 的一个 Java 实现,它允许连接到一个 sshd 服务器,使用端口转发,进行文件传输等。

配置文件

properties 文件解析

以 .properties 结尾的配置文件,是 Java 中比较常见的一种配置文件,它的获取可以使用 JDK 自带的工具类 Properties,以下是获取这种配置文件的方法:

public static void loadProperties(String path) throws IOException {
    Properties config = new Properties();
    InputStream input = new FileInputStream(path);
    config.load(input);
    config.forEach((k, v) -> System.out.println(k + ":" + v));
}

yaml 文件解析

以 .yaml 或 .yml 结尾的文件,是比较通用的一种配置文件,解析这类文件可以使用 snakeyaml库。首先引入 snakeyaml 库

<dependency>
    <groupId>org.yaml</groupId>
    <artifactId>snakeyaml</artifactId>
    <version>1.30</version>
</dependency>

获取配置文件内容的方法:

public static void loadYaml(String filePath) throws FileNotFoundException {
    Yaml yaml = new Yaml();
    InputStream input = new FileInputStream(filePath);
    Map<Object, Object> map = yaml.load(input);
    map.forEach((k, v) -> System.out.println(k + ":" + v));
}

JSch 使用

首先引入 JSch 库

<dependency>
    <groupId>com.github.mwiede</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.71</version>
</dependency>

使用 JSch 首先要获取 JSch 链接,这里需要服务器用户名、ssh 端口号,访问密钥或密码。

private static Session getSession(String keyPath) throws JSchException {
    Session session;
    JSch jSch = new JSch();
    jSch.addIdentity("name", keyPath.getBytes(), null, null);
    session = jSch.getSession("ubuntu", "xxx.xxx.xxx.xxx", 22);
    session.setConfig("StrictHostKeyChecking", "no");
    session.setTimeout(3 * 1000);
    session.connect();
    return session;
}

根据配置文件目录获取该目录下所有配置文件的配置数据

public static void remoteConfigs(String privateKey, String dir) {
    Map<Object, Object> map = new HashMap<>();

    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    try {
        session = getSession(privateKey);
        channel = session.openChannel("sftp");
        channel.connect();
        channelSftp = (ChannelSftp) channel;

        Vector<ChannelSftp.LsEntry> vector = channelSftp.ls(dir);
        for (ChannelSftp.LsEntry lsEntry : vector) {
            if (lsEntry.getAttrs().isDir()) {
                continue;
            }
            map.putAll(loadProperties(dir + "/" + lsEntry.getFilename()));
        }
    } catch (JSchException | SftpException | IOException e) {
        e.printStackTrace();
    } finally {
        if (channelSftp != null) channelSftp.exit();
        if (channel != null) channel.disconnect();
        if (session != null) session.disconnect();
    }
    map.forEach((k, v) -> System.out.println(k + " : " + v));
}