Java在linux服务器上执行shell命令

ExecCommandController:

package com.neusoft.shell;

//@CrossOrigin
//@RestController
//@RequestMapping("/linux")
public class ExecCommandController {

//    @Autowired
    private IExecCommandServer execCommandServer;


    /**
     * 请求示例: http://192.168.142.222:8086/linux/exec?cmd=ls /mnt
     * @param cmd
     * @return
     * @throws Exception
     */
//    @GetMapping("/exec")
    public void execCommand(String cmd) throws Exception {
        execCommandServer.execCommand(cmd);
    }

    public static void main(String[] args) {
        new ExecCommandServerImp().execCommand("notepad");
        //windows下要这么执行,linux上没差别,正常传入命令即可 cmd /c  后面加要执行的命令
        new ExecCommandServerImp().execCommand("cmd /c dir");
        new ExecCommandServerImp().execCommand("cmd /c calc");
        new ExecCommandServerImp().execCommand("cmd /k dir");
    }
}

ExecCommandServerImp:

package com.neusoft.shell;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;

//@Service
public class ExecCommandServerImp implements IExecCommandServer {

    @Override
    public void execCommand(String cmd){
        try{
            Runtime rt = Runtime.getRuntime();
            //执行命令, 最后一个参数,可以使用new File("path")指定运行的命令的位置
            Process proc = rt.exec(cmd,null,new File("F:\\回收站\\vspcloud-vsptrunk-cmcc"));
            //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();
        }
    }
}

IExecCommandServer:

package com.neusoft.shell;

public interface IExecCommandServer {

    void execCommand(String cmd);

}

 

上一篇:拍照技巧 风景摄影中的三分法与井字构图


下一篇:html将内容复制到剪贴板