CmdController.java
2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package com.tianbo.analysis.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.List;
@Controller
@Slf4j
public class CmdController {
@RequestMapping("/linuxCmd")
public String linuxCmd(@RequestParam(value = "command",required = false) String command,Model model){
List<String> strList = new ArrayList();
try {
if (command !=null && !command.isEmpty()){
Process process;
process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", command}, null, null);
InputStreamReader ir = new InputStreamReader(process
.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
String line;
process.waitFor();
while ((line = input.readLine()) != null) {
strList.add(line);
log.info(line);
}
model.addAttribute("cmdResult",strList);
}
}catch (Exception e){
e.printStackTrace();
log.error("执行命令出错",e);
}
return "cmd/cmd";
}
@RequestMapping("/windowsCmd")
public String windowsCmd(@RequestParam(value = "command",required = false) String command,Model model){
List<String> strList = new ArrayList();
try {
if (command !=null && !command.isEmpty()){
Runtime rt = Runtime.getRuntime();
String[] args = new String[]{"cmd","/c",command};
Process pr = rt.exec(args,null,null);
//Process pr = rt.exec("cmd /c dir"); // cmd /c calc
// Process pr = rt.exec("D:\\xunlei\\project.aspx");
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream(), "GBK"));
String line;
while ((line = input.readLine()) != null) {
strList.add(line);
log.info(line);
}
int exitVal = pr.waitFor();
log.info("exitVal",exitVal);
model.addAttribute("cmdResult",strList);
}
}catch (Exception e){
e.printStackTrace();
log.error("执行命令出错",e);
}
return "cmd/wincmd";
}
}