วันอาทิตย์ที่ 13 กรกฎาคม พ.ศ. 2557

การเขียนโปรแกรม..เรียกใช้งาน command linux (ตัวอย่าง การ grep log)

- ถ้าเราเข้า ssh จะค้าหาข้อความที่อยู่ใน log เราก็ต้องใช้ command  ---> grep  'xxxxx' /logfile_path
- แล้วถ้าต้องการเขียนโปรแกรมไปหาเองล่ะ... ตัวอย่างข้างล่างเลย ไม่เน้นอธิบาย เน้นให้อ่านโค๊ด

public static String grep(String keyword) {

        try {

            String logpath = "/home/test/server.log";
            List<String> commands = new ArrayList<String>();
            commands.add("/bin/sh");
            commands.add("-c");
            commands.add("grep '" + keyword + "' " + logpath);
            ProcessBuilder pb = new ProcessBuilder(commands);
            pb.redirectErrorStream(true);
            Process process = pb.start();
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            StringBuilder sb = new StringBuilder();

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

            return sb.toString();
            
        } catch (IOException ex) {
            Logger.getLogger(GrepLogLinux.class.getName()).log(Level.SEVERE, null, ex);
        }

        return null;
    }

ไม่มีความคิดเห็น:

แสดงความคิดเห็น