写一段java程序来执行linux命令

时间:2023-03-09 17:31:37
写一段java程序来执行linux命令

摘要

在日常开发中,程序员需要经常查询服务器日志来排查问题和调试程序。如果是本地调试还好,但项目一旦发布到服务器上,每次查日志就很麻烦,而且日志量巨大,有时我们无法找到我们需要的信息。经常需要借助第三方工具来执行此类操作。那么我们可不可以在编辑器上运行代码就能完成相应的操作呢?

答案是肯定的!经过研究与测试,我总结了以下的方法,调用次服务就能执行相应的linux命令,无需麻烦借用第三方工具了,在同一个开发工具上就能完成所有的操作。接下来看看代码吧!

程序代码

一、写一个对外提供的services(ReadLogServlet)

public class ReadLogServletextends SlingAllMethodsServlet {

private static final LoggerLOG = LoggerFactory.getLogger(ReadLogServlet.class);

@Override

        protected void doPost(final SlingHttpServletRequest request,

final SlingHttpServletResponse response)throws ServletException, IOException {

request.setCharacterEncoding("UTF-8");

response.setContentType("application/json;charset=utf-8;");

String jsonStr = HttpRequestUtil.getRequestJson(request);

try {

JSONObject jsonObject =new JSONObject(jsonStr);

String commond = jsonObject.getString("command");

String result = executeLinuxCmd(commond);

if (result ==null) {

LOG.error("result null");

return;

}

try (PrintWriter printWriter = response.getWriter()) {

printWriter.write(result);

response.flushBuffer();

}catch (IOException e) {

LOG.error("Response writer error:" + e.toString());

}

}catch (JSONException e) {

}catch (IOException io){

try (PrintWriter printWriter = response.getWriter()) {

printWriter.write(io.getMessage());

response.flushBuffer();

}catch (IOException e) {

LOG.error("Response writer error:" + e.toString());

}

}

}

//核心代码

public String executeLinuxCmd(String cmd)throws IOException {

//System.out.println("got cmd job : " + cmd);

            Runtime run = Runtime.getRuntime();

//            Process process = run.exec(cmd);

            Process process = run.exec(new String[]{"/bin/sh","-c", cmd});

InputStream in = process.getInputStream();

BufferedReader bs =new BufferedReader(new InputStreamReader(in));

//List list = new ArrayList();

            StringBuffer sf =new StringBuffer();

String result =null;

while ((result = bs.readLine()) !=null) {

//System.out.println("job result [" + result + "]");

//list.add(result);

                sf.append(result);

sf.append("\n");

}

in.close();

// process.waitFor();

            process.destroy();

return sf.toString();

}

}

二、使用postman调用ReadLogServlet(使用其他工具调用也可)

写一段java程序来执行linux命令

总结:

  除了查询日志外,还可执行其他linux命令。大家可继续优化发掘,如果有更好的意见和技术,欢迎留言探讨哦!