我在Linux Ubuntu服务器上编写了一个shell 脚本. 我想在Java上运行一个shell 脚本.
在Linux服务器中运行shell 脚本会改变我编写它的方式,但不是通过Java.
我将向您展示Java代码、shell 脚本文件和捕获屏幕.
Java个
public class ShellScriptApplication {
public static void main(String[] args) {
String start = "start";
String stop = "stop";
String name = "";
Scanner sc = new Scanner(System.in);
System.out.print("start or stop? : ");
String s = sc.nextLine();
if(s.equals(start)) {
System.out.print("시작하실 프로그램을 입력해주세요 [admin / ap / json / fixed] : ");
name = sc.nextLine();
openShell(start, name);
} else if (s.equals(stop)) {
System.out.print("종료하실 프로그램을 입력해주세요 [admin / ap / json / fixed] : ");
name = sc.nextLine();
openShell(stop, name);
} else {
System.out.println("wrong");
}
}
public static String openShell(String status, String name) {
String result = "";
String dir = "/data/GSLinkIN/app";
String cdExec = "cd " + dir + " && ./"+ name + "-" + status + ".sh";
String [] command = {"/bin/sh","-c", cdExec};
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command(command);
try {
// Run script
Process process = processBuilder.start();
// Read output
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line);
}
if(output.toString().equals("")) {
result = "success";
}else {
result = output.toString();
}
} catch (Exception e) {
result = "fail";
}
System.out.println(result);
return result;
}
}
stop.sh个
#!/bin/sh
APP_NAME=linkin-admin-www-2.0.war
APP_PID=$(ps -ef | grep $APP_NAME | grep -v grep | awk '{print $2}')
echo "$APP_NAME (PID:$APP_PID)"
kill -9 $APP_PID
echo "$APP_NAME stopped"
When running a shell script using Java
When running directly on a Linux server个
即使我在Java上运行一个Shell脚本,我也想打印这个ID,然后得到一个新行.