使用java 在linux 系统执行命令。

最近需要监控服务器性能情况,需要查询linux服务器硬盘使用情况,window系统下命令能够正常执行,linux下一直执行不了,并且不报错。发了点时间解决,留个备忘录。

/***
     * 
     * 获取操作系统类型
     * @author  2019-03-09
     * @return 1: window  2: 非window 
     */
    public static String getOsType()
    {
        String osName = System.getProperty("os.name");   
        String os_type = "";
        if (osName == null)   
            os_type = "";   
        if (osName.toLowerCase().indexOf("win") != -1) {   
            os_type = "1";
        } else {  
           os_type = "2";
        }
        
        return os_type;
    }
    
    /***
     * 
     * 执行shell命令
     * @author  2019-03-09
     * @param cmd
     * @return
     */
    public static List executeShell(String cmd)
    {
        List text = new ArrayList();
        
        Runtime r = Runtime.getRuntime();
        Process p = null;
        BufferedReader in = null;
        
        //没有命令
        if(cmd == null && cmd.length() == 0)
        {
            return text ;
        }
        
        try {
            //非window系统
            if("2".equals(getOsType()))
            {
                String[] c = new String[]{"sh","-c",cmd};
                p = r.exec(c);
            }
            else
            {
                p = r.exec(cmd); 
            } 
            
            in = new BufferedReader(new InputStreamReader(
                    p.getInputStream()));
            String str = null;
            int line = 0;
            
            while ((str = in.readLine()) != null) {
                line ++;
                if(!"".equals(str))
                {
                    text.add(str);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            text.add(e.getMessage());
        } finally {
            
            try {
                p.waitFor();
            }
            catch (Exception e) {
                // TODO: handle exception
                text.add(e.getMessage());
            }
            
            try {
                in.close();
              
            }
            catch (Exception e) {
                e.printStackTrace();
                text.add(e.getMessage());
            }
            
            p.destroy();
             
        }
        
        return text;
    }

最主要是加了下面,其中cmd 是要执行的命令:

  String[] c = new String[]{"sh","-c",cmd};
                p = r.exec(c);

 

你可能感兴趣的:(JAVA)