java在linux本地执行shell命令的实现方法
作者:纯洁的小魔鬼 时间:2023-11-14 02:31:33
一.以springboot为例,建立代码
1.IExecCommandServer:
public interface IExecCommandServer {
void execCommand(String cmd);
}
2.ExecCommandServerImp:
@Service
public class ExecCommandServerImp implements IExecCommandServer {
@Override
public void execCommand(String cmd){
try{
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd,null,null);
InputStream stderr = proc.getInputStream();
InputStreamReader isr = new InputStreamReader(stderr,"GBK");
BufferedReader br = new BufferedReader(isr);
String line="";
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}catch (Exception e){
e.printStackTrace();
}
}
}
3.ExecCommandController:
@CrossOrigin
@RestController
@RequestMapping("/linux")
public class ExecCommandController {
@Autowired
private IExecCommandServer execCommandServer;
@GetMapping("/exec")
public ResultMap execCommand(String cmd) throws Exception {
execCommandServer.execCommand(cmd);
return Result.success("ok");
}
}
二,执行示例
http://192.168.142.222:8086/linux/exec?cmd=ls /mnt
日志中输出:
来源:https://blog.csdn.net/xyy1028/article/details/91349697
标签:java,执行,shell命令
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Java基于rest assured实现接口测试过程解析
2022-07-25 09:30:25
Java数组(Array)最全汇总(上篇)
2022-12-19 23:22:30
![](https://img.aspxhome.com/file/2023/8/77498_0s.jpg)
深入理解spring事务
2023-10-13 14:51:36
MapStruct处理Java中实体与模型间不匹配属性转换的方法
2023-08-02 22:31:28
Android View类与SurfaceView类详解
2022-07-17 14:49:24
C#对XmlHelper帮助类操作Xml文档的通用方法汇总
2023-06-29 05:37:01
Android使用CountDownTimer模拟短信验证倒计时
2022-10-24 18:00:28
![](https://img.aspxhome.com/file/2023/3/123243_0s.gif)
关于自定义过滤器获取不到session问题
2022-05-16 11:30:21
![](https://img.aspxhome.com/file/2023/2/113182_0s.jpg)
Spring Batch批处理框架使用解析
2021-12-24 03:41:19
Java常用函数式接口总结
2022-02-02 00:02:50
![](https://img.aspxhome.com/file/2023/8/68178_0s.png)
Java应用程序开发学习之static关键字应用
2021-12-20 13:23:41
![](https://img.aspxhome.com/file/2023/8/75708_0s.png)
JAVA线程池原理实例详解
2021-10-01 17:59:01
![](https://img.aspxhome.com/file/2023/2/88522_0s.jpg)
Android 启动activity的4种方式及打开其他应用的activity的坑
2023-12-25 01:18:48
Android AIDL通信DeadObjectException解决方法示例
2022-06-04 14:53:27
使用IDEA开发配置Java Web的初始化过程
2022-09-25 16:33:38
![](https://img.aspxhome.com/file/2023/4/64794_0s.jpg)
android 字体颜色选择器(ColorPicker)介绍
2021-10-05 01:13:31
Java毕业设计实战之二手书商城系统的实现
2022-03-21 14:06:20
![](https://img.aspxhome.com/file/2023/4/72524_0s.jpg)
GraalVM系列Native Image Basics静态分析
2023-08-08 03:05:38
java web个人通讯录系统设计
2022-09-14 11:12:15
![](https://img.aspxhome.com/file/2023/0/71910_0s.png)
Java中的接口多继承机制
2023-08-28 06:13:48
![](https://img.aspxhome.com/file/2023/4/79824_0s.png)