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

最近须要监控服务器性能状况,须要查询linux服务器硬盘使用状况,window系统下命令可以正常执行,linux下一直执行不了,而且不报错。发了点时间解决,留个备忘录。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 是要执行的命令:shell

String[] c = new String[]{"sh","-c",cmd};

p = r.exec(c);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值