前言
最近项目上有一个需求需要暴露rest请求,这个rest请求要去执行python或者shell脚本;
1、目录结构
2、py示例
print 'hello python'
3、shell示例
echo 'hello shell'
mkdir hello
4、rest接口示例
package com.hxs.demo.soon.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.List;
/**
* @Date 2022/8/5
* @Author hxs
*/
@RestController
@RequestMapping(path = "/api/v1/op")
public class OptionController {
private static final String PYNAME ="hello.py";
private static final String SHELLNAME ="hello.sh";
@GetMapping(path = "/python")
public List<String> python() {
String path = OptionController.class.getClassLoader().getResource("").getPath();
Process proc;
try {
//执行脚本
proc = Runtime.getRuntime().exec("python " + path + PYNAME);
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
proc.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return Collections.singletonList("success");
}
@GetMapping(path = "/shell")
public List<String> shell() {
String path = OptionController.class.getClassLoader().getResource("").getPath();
try {
//先授权
ProcessBuilder pb = new ProcessBuilder("/bin/chmod", "755", path+SHELLNAME);
Process ps = pb.start();
ps.waitFor();
//执行脚本
Process process = Runtime.getRuntime().exec(path+SHELLNAME);
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
process.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return Collections.singletonList("success");
}
}
5、测试
http://localhost:8980/api/v1/op/shell
新增的目录