操作linux工具类

一、maven依赖

  <dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh2</artifactId>
        </dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
 

二、一些常量

/**
     * 判断远程路径是否存在
     */
    String IS_EXIST_DIR = "if [ -d "%s" ];then
" +
            "echo "1"
" +
            "else
" +
            "echo "0"
" +
            "fi";
    /**
     * 判断远程路径是否存在
     */
    String IS_EXIST_FILE = "if [ -f "%s" ];then
" +
            "echo "1"
" +
            "else
" +
            "echo "0"
" +
            "fi";
    /**
     * 修改指定文件夹下面的shell脚本的权限
     */
    String CHMODE_FILE_SH = "chmod 755 %s/*.sh ";

    /**
     * 进入某个路径
     */
    String CD_DIR = "cd %s
";

    /**
     * 文件重命名
     */
    String RENAME = CD_DIR + "mv %s %s";

    /**
     * 一次创建多级目录
     */
    String MKDIRS = "mkdir -p %s";

    /**
     * 执行指定脚本
     */
    String EXECUTE_SCRIPT = CD_DIR + " ./%s ";


    /**
     * 查看文件内容 第一个%s:开始行号,第二个%s:指定文件
     */
    String CAT_FILE_CONTENT = "tail -n +%s %s";

    /**
     * 查看指定文件的指定最后几行的内容:第一个%s:最后多少行,%s:指定文件
     */
    String PREVIEW_FILE_CONTENT = "tail -%s %s";

    /**
     * 查看文件大小
     */
    String FILE_SIZE_OR_FILES = CD_DIR + "du -h %s*";

    /**
     * 查看文件指定区域的内容(并输出行号):第一个%s:文件路径 第二个%s:起始行,第三个%s:截止行
     */
    String CAT_FILE_RANGE_CONTENT = "nl %s | sed -n '%s,%sp'";

三、相关操作方法

1、建立连接

 /**
     * 建立连接
     * @param ip
     * @param port
     * @param user
     * @param password
     * @return
     */
    public static Connection getConnection(String ip, Integer port, String user, String password) {
        //建立连接
        Connection conn = new Connection(ip, port);
        boolean isAuthed;
        try {
            conn.connect();
            isAuthed = conn.authenticateWithPassword(user, password);
        } catch (IOException e) {
            throw new RunTimeException("建立连接失败:{},{},{},{}", ip, port, user, password, e);
        }
        if (!isAuthed) {
            throw new RuntimeException("用户名或密码错误:{},{},{},{}", ip, port, user, password);
        }
        return conn;
    }

2、关闭连接

 /**
     * 关闭连接
     * @param conn
     */
    public static void closeConnection(Connection conn) {
        if (null != conn) {
            conn.close();
        }
    }

3、关闭session

    /**
     * 关闭session
     * @param session
     */
    public static void closeSession(Session session) {
        if (null != session) {
            session.close();
        }
    }

4、文件上传

/**
     * 文件上传
     * @param localFile
     * @param remoteTargetDirectory 需要保存到的远程路径
     * @param conn
     */
    public static void upload(String localFile, String remoteTargetDirectory, Connection conn) {
        try {
            SCPClient client = conn.createSCPClient();
            client.put(localFile, remoteTargetDirectory);
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败:", e);
        }
    }

    /**
     * 文件上传
     * @param data
     * @param remoteTargetDirectory 需要保存到的远程路径
     * @param remoteFileName 保存的文件名
     * @param conn
     */
    public static void upload(byte[] data, String remoteTargetDirectory, String remoteFileName, Connection conn) {
        try {
            SCPClient client = conn.createSCPClient();
            client.put(data, remoteFileName, remoteTargetDirectory);
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败:", e);
        }
    }

5、执行相关命令

/**
     * 执行命令
     *
     * @param cmd
     * @param con
     */
    private static String executeCommand(String cmd, Connection con) {
        Session session = null;
        InputStream in = null;
        try {
            session = con.openSession();
            session.execCommand(cmd);
            in = session.getStdout();
            return IOUtils.toString(in);
        } catch (Exception e) {
            throw new RuntimeException("命令执行失败:", e);
        } finally {
            closeSession(session);
            if (null != in) {
                try {
                    in.close();
                } catch (IOException ignored) {
                }
            }
        }
    }

6、远程文件下载

/**
     * 远程文件下载
     * @param conn
     * @param out 输出流
     * @param remotePath 远程文件地址
     */
    public static void dowload(Connection conn, OutputStream out, String remotePath) {
        try {
            SCPClient client = conn.createSCPClient();
            client.get(remotePath, out);
        } catch (IOException e) {
            throw new RuntimeException("文件下载失败:", e);
        }
    }

7、获取远程文件类容

 /**
     * 获取远程文件内容
     * @param remotePath 远程文件路径
     * @param line 开始行号
     * @param con
     * @return
     */
    public static Session getFileContent(String remotePath, Integer line, Connection con) {
        Session session;
        try {
            session = con.openSession();
            session.execCommand(String.format(CAT_FILE_CONTENT, null == line ? 1 : line, remotePath));
            return session;
        } catch (IOException e) {
            throw new RuntimeException("获取远程文件内容失败:", e);
        }
    }

8、预览指定文件的最后多少行内容

 /**
     * 预览文件内容
     * @param remotePath
     * @param line
     * @param con
     * @return
     */
    public static List<String> previewFile(String remotePath, Integer line, Connection con) {
        Session session = null;
        InputStream in = null;
        String cmd = String.format(PREVIEW_FILE_CONTENT, null == line ? 1 : line, remotePath);
        try {
            session = con.openSession();
            session.execCommand(cmd);
            in = session.getStdout();
            return IOUtils.readLines(in);
        } catch (Exception e) {
            throw new RunTimeException("命令执行失败:", e);
        } finally {
            closeSession(session);
            if (null != in) {
                try {
                    in.close();
                } catch (IOException ignored) {
                }
            }
        }
    }

9、读取指定目录下面以某个字段开头的文件

/**
     * 获取指定目录下面的符合命名规则的文件
     * @param parentPath
     * @param fileNamePre
     * @param conn
     * @return
     */
    public static String findFiles(String parentPath, String fileNamePre, Connection conn) {
        String result = executeCommand(String.format(FILE_SIZE_OR_FILES, parentPath, null == fileNamePre ? "" : fileNamePre), conn);
        return StringUtils.remove(result, "
");
    }

10、修改shell文件的读写权限

 /**
     * 修改shell文件的读写权限
     *
     * @param remotePath
     * @param con
     */
    public static void chmodeSh(String remotePath, Connection con) {
        executeCommand(String.format(CHMODE_FILE_SH, remotePath), con);
    }

11、解压压缩包,并返回解压的文件名

/**
     * 解压
     * @param parentPath 需要解压的文件目录
     * @param cmd 解压命令
     * @param con
     * @return 返回文件名称
     */
    public static String uzip(String parentPath, String cmd, Connection con) {
        if (StringUtils.isNotBlank(parentPath)) {
            cmd = String.format(CD_DIR, parentPath) + cmd;
        }
        String result = StringUtils.remove(executeCommand(cmd, con), "
");
        return StrUtil.subBefore(result, "/", false);
    }

12、检查指定路径是否存在(文件夹是否存在)

/**
     * 检查指定路径是否存在
     * @param remotePath 远程路径
     * @param con        ssh连接
     * @return
     */
    public static boolean isDirExists(String remotePath, Connection con) {
        String result = StringUtils.remove(executeCommand(String.format(IS_EXIST_DIR, remotePath), con),"
");
        return "".equals(result) || "1".equals(result);
    }

13、检查指定文件是否存在

/**
     * 检查指定文件是否存在
     * @param remotePath
     * @param con
     * @return
     */
    public static boolean isFileExists(String remotePath, Connection con) {
        String result =StringUtils.remove(executeCommand(String.format(IS_EXIST_FILE, remotePath), con),"
");
        return "".equals(result) || "1".equals(result);
    }

14、获取文件指定范围内的内容

/**
     * 获取文件指定区域的内容
     * @param remotePath
     * @param start
     * @param end
     * @param con
     * @return
     */
    public static String getFileRangeContent(String remotePath,Integer start,Integer end,Connection con){
        if (JudgeUtil.isNullOr(start,end)){
            throw new RuntimeException("开始和结束行号不能为空");
        }
        if (start < 0){
            start = 1;
        }
        return executeCommand(String.format(CAT_FILE_RANGE_CONTENT, remotePath, start, end), con);
    }

15、文件重命名

/**
     * 文件重命名
     *
     * @param remotePath 远程路径
     * @param srcName    需要修改的文件名
     * @param destName   修改之后的文件名
     * @param conn       ssh连接
     */
    public static void rename(String remotePath, String srcName, String destName, Connection conn) {
        String cmd = String.format(RENAME, remotePath, srcName, destName);
        executeCommand(cmd, conn);
    }

16、创建文件夹

/**
     * 创建文件夹
     *
     * @param conn       ssh连接
     * @param remotePath 指定的路径
     */
    public static void mkdir(Connection conn, String remotePath) {
        String cmd = String.format(MKDIRS, remotePath);
        executeCommand(cmd, conn);
    }

17、执行指定的远程shell脚本

/**
     * 执行指定的远程shell脚本
     * @param remotePath 远程路径
     * @param script     脚本名称
     * @return
     */
    public static boolean executeScript(String remotePath, String script, Connection conn) {
        String result = StringUtils.remove(executeCommand(String.format(EXECUTE_SCRIPT, remotePath, script), conn),"
");
        return "".equals(result) || "1".equals(result);
    }