教你用页面操作liunx命令

简介

前言: liunx命令是我们每一个学编程的小伙伴都需要掌握的一个课程,对于不会liunx命令的小伙伴来说是一个很头疼的一件事,所以我们可以通过java连接centos服务器进行liunx命令的操作,做一些可视化的界面帮助不会liunx命令的小伙伴解决这些问题,或者我们也可以通过可视化页面减少我们的操作。

java连接服务器

Maven

<dependency>
    <groupId>ch.ethz.ganymed</groupId>
    <artifactId>ganymed-ssh2</artifactId>
    <version>262</version>
</dependency>

java代码

public class LiunxUtil {

    public static String execute(String ip,String username,String password, String cmd) {

        try {
            // 创建连接
            Connection conn = new Connection(ip, 22);
            // 启动连接
            conn.connect();
            // 验证用户密码
            conn.authenticateWithPassword(username, password);
            Session session = conn.openSession();
            //执行命令
            session.execCommand(cmd);
            session = conn.openSession();
            //执行命令
            session.execCommand(cmd);
            InputStream stdout = new StreamGobbler(session.getStdout());
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
            StringBuffer buffer = new StringBuffer();
            String line;

            while ((line = br.readLine()) != null) {
                buffer.append(line + "\n");
            }

            String result = buffer.toString();
            System.out.println(result);

            session.close();
            conn.close();
            //如果没有异常,返回结果为命令执行结果,如果有异常,返回null
            return result;

        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}

执行代码

public static void main(String[] args) {

        String execute = LiunxUtil.execute(host,userName,password,"ls");
        System.out.println(execute);

    }

执行结果
在这里插入图片描述

centos服务器的文件上传和下载

工具包

public class FtpUtil {
    private static final Logger loggerMonitor = LoggerFactory.getLogger("monitor");

    /**
     * FTPClient对象
     **/
    private static ChannelSftp ftpClient = null;
    /**
     *
     */
    private static Session sshSession = null;

    /**
     * 连接服务器
     *
     * @param host
     * @param port
     * @param userName
     * @param password
     * @return
     * @throws Exception
     */
    public static ChannelSftp getConnect(String host, String port, String userName, String password)
            throws Exception {
        try {
            JSch jsch = new JSch();
            // 获取sshSession
            sshSession = jsch.getSession(userName, host, Integer.parseInt(port));
            // 添加s密码
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            // 开启sshSession链接
            sshSession.connect();
            // 获取sftp通道
            ftpClient = (ChannelSftp) sshSession.openChannel("sftp");
            // 开启
            ftpClient.connect();
            loggerMonitor.debug("success ..........");
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("连接sftp服务器异常。。。。。。。。");
        }
        return ftpClient;
    }

    /**
     * 下载文件
     *
     * @param ftp_path    服务器文件路径
     * @param save_path   下载保存路径
     * @param oldFileName 服务器上文件名
     * @param newFileName 保存后新文件名
     * @throws Exception
     */
    public static void download(String ftp_path, String save_path, String oldFileName, String newFileName)
            throws Exception {
        FileOutputStream fos = null;
        try {
            ftpClient.cd(ftp_path);
            File file = new File(save_path);
            if (!file.exists()) {
                file.mkdirs();
            }
            String saveFile = save_path + newFileName;
            File file1 = new File(saveFile);
            fos = new FileOutputStream(file1);
            ftpClient.get(oldFileName, fos);
        } catch (Exception e) {
            loggerMonitor.error("下载文件异常............", e.getMessage());
            throw new Exception("download file error............");
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new Exception("close stream error..........");
                }
            }
        }
    }

    /**
     * 上传
     *
     * @param upload_path 上传文件路径
     * @param ftp_path    服务器保存路径
     * @param newFileName 新文件名
     * @throws Exception
     */
    public static void uploadFile(String upload_path, String ftp_path, String newFileName) throws Exception {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(new File(upload_path));
            ftpClient.cd(ftp_path);
            ftpClient.put(fis, newFileName);
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("Upload file error.");
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    throw new Exception("close stream error.");
                }
            }
        }
    }

    /**
     * 关闭
     *
     * @throws Exception
     */
    public static void close() throws Exception {
        loggerMonitor.debug("close............");
        try {
            ftpClient.disconnect();
            sshSession.disconnect();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            throw new Exception("close stream error.");
        }
    }

    /**
     * 遍历文件夹里的文件
     * @file 文件夹路径
     * @fileList 存储文件名的集合
     */

    public static ArrayList<String> isDirectory(File file, ArrayList<String> fileList) {
        if(file.exists()){
            if (file.isFile()) {
                int start = file.getAbsolutePath().lastIndexOf("\\")+1;
                int end = file.getAbsolutePath().length();
                fileList.add(file.getAbsolutePath().substring(start,end));
            }else{
                File[] list = file.listFiles();
                if (list.length == 0) {
                    System.out.println(file.getAbsolutePath() + " is null");
                } else {
                    for (int i = 0; i < list.length; i++) {
                        isDirectory(list[i],fileList);//递归调用
                    }
                }
            }
        }else{
            System.out.println("文件不存在!");
        }
        return fileList;
    }
}

文件下载

public static void main(String[] args) {

        try {
            getConnect(host, port, user, password);
            download("/home/admin/log","C:\\Users\\Talisman\\Desktop\\csdn博客\\",
                    "blog-pro.log","123.log");
            close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

文件上传

public static void main(String[] args) {

        try {
            getConnect(host, port, user, password);
			uploadFile("C:\\Users\\Talisman\\Desktop\\csdn博客\\1.png", "/home/admin/log", "1.png");
            close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

结语

如果你将上面的代码掌握之后,你就能通过页面来操作你服务器上的命令了。

PS: 我们可以通过页面的操作请求java代码执行shell脚本并返回数据给前端,这样就很方便我们完成一些自动化的脚本啦!!!

最后: 喜欢我们该文章的可以给我点赞收藏关注加评论哈哈哈!!!!!!

推荐阅读:

2.5万字详细讲解个人网站的开发过程和项目的部署

不会用liunx命令怎么办?教你安装宝塔解除该烦恼

教你使用java的爬虫爬取你想要的资源

Redis常用的命令整理和springboot的整合

  • 50
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 60
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 60
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Talisman丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值