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);

}

 

posted @   浅笑19  阅读(322)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示