java在linux本地執行shell命令的實現方法

一.以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

 日志中輸出:

到此這篇關於java在linux本地執行shell命令的實現方法的文章就介紹到這瞭,更多相關java在linux執行shell命令內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: