JSCH连接ssh终端执行文件操作

2023-10-25 15:50:49 浏览数 (1)

JSch是一个纯Java实现的SSH2协议的客户端库。它允许您在Java应用程序中进行安全的远程登录、文件传输和执行命令。您可以使用JSch来连接到远程服务器并执行各种操作。 导入pom包

代码语言:javascript复制
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.55</version>
        </dependency>
执行命令相关操作

特别注意⚠️代码里面配置的是exec渠道

代码语言:javascript复制
    // write a create file directory function
    public static void cmdCreateFileDirectory(final String path, final String serverUser, final String serverPassword) {
        String command = "mkdir -p "   path;
        int exitValue = 0;
        long startTime = System.currentTimeMillis();
        final StringBuilder result = new StringBuilder();
        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession(serverUser, "127.0.0.1", 22);
            session.setPassword(serverPassword);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);
            channel.setInputStream(null);
            ((ChannelExec) channel).setErrStream(System.err);

            InputStream in = channel.getInputStream();
            channel.connect();
            byte[] tmp = new byte[1024];
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0) break;
                    result.append(new String(tmp, 0, i));
                }
                if (channel.isClosed()) {
                    if (in.available() > 0) continue;
                    exitValue = channel.getExitStatus();
                    log.debug("exit-status: {}", exitValue);
                    break;
                }
                try {
                    Thread.sleep(100);
                } catch (Exception ee) {
                }
            }
            channel.disconnect();
            session.disconnect();
            if (exitValue != 0) {
                log.error("create file directory error: "   exitValue   " "   command);
            }
            log.info(" create file directory success, command: {}, content:{} total cost time:{}", command,
                    result.toString(), System.currentTimeMillis() - startTime);
        } catch (JSchException e) {
            log.error(e.getMessage(), e);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }
执行上传文件和配置权限

特别注意⚠️代码里面配置是sftp渠道

代码语言:javascript复制
/**
     * 使用账户登陆方式创建文件
     * @param fileName
     * @param path
     * @param content
     * @param username
     * @param password
     * @return
     */
    private static boolean processTargetFileAndAuth(String fileName, String path, byte[] content, String username,
                                                   String password) {
        JSch jsch = new JSch();
        Session session = null;
        Channel channel = null;
        ChannelSftp channelSftp = null;
        // Read, write, and execute permissions for owner, group, and others
        int permissions = 0777;
        try {
            session = jsch.getSession(username, "127.0.0.1", 22);
            session.setPassword(password);
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            channel = session.openChannel("sftp");
            channel.connect();

            channelSftp = (ChannelSftp) channel;

            // Check if the directory exists
            try {
                channelSftp.stat(path);
                log.debug("Directory already exists.");
            } catch (SftpException e) {
                // Create the directory if it does not exist
                channelSftp.mkdir(path);
                log.debug("Directory created successfully.");
            }

            // Change to the new directory
            channelSftp.cd(path);

            // Create the file
            channelSftp.put(new ByteArrayInputStream(content), fileName);
            channelSftp.chmod(permissions, fileName);
            log.info("Directory:{} and file:{} created successfully.", path, fileName);
        } catch (JSchException | SftpException e) {
            log.error("Failed to create", e);
            return false;
        } finally {
            if (channelSftp != null) {
                channelSftp.disconnect();
            }
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        }
        return true;
    }
总结

JSch是一个功能强大且广泛使用的Java SSH客户端库,它提供了许多有用的功能和API,可以轻松地实现SSH连接、文件传输和执行命令等操作。JSch的文档和示例非常详细,易于使用和理解。然而,一些用户可能会发现JSch的学习曲线比较陡峭,需要一些时间来掌握其工作原理和API。总体而言,JSch是一个非常优秀的Java SSH客户端库,适用于各种SSH连接和文件传输方案。

0 人点赞