在Java中运行Linux命令( Shell 脚本)的操作指南
在windows下面编写java代码,然后打包放到Linux下面运行,并且执行某个脚本。
Runtime.getRuntime().exec("xxx.sh").waitFor();
通过RunTime.getRuntime().exec()调用服务器命令脚本来执行。
用法:
// 在单独的进程中执行指定的字符串命令
public Process exec(String command)
// 在单独的进程中执行指定命令和变量
public Process exec(String[] cmdArray)
// 在指定环境的独立进程中执行指定命令和变量
public Process exec(String command,String[] envp)
// 在指定环境的独立进程中执行指定命令和变量
public Process exec(String[] cmdArray,String[] envp)
// 在有指定的环境和工作目录的独立进程中执行指定的字符串命令
public Process exec(String command,String[] encp,File dir)
// 在指定环境和工作目录的独立进程中执行指定的命令和变量
public Process exec(String[] cmdarray,String[] envp,File dir)
举例:
public Process exec(String[] cmdArray);
// Linux下
Runtime.getRuntime().exec(new String[]{"/bin/sh","-c","ps -ef|grep java"});
// Windows下
Runtime.getRuntime().exec(new String[]{"cmd","/c",cmds});
Process的几种方法
1、destroy():杀掉子进程
2、exitValue():返回子进程的出口值,值0表示正常终止
3、getErrorStream():获取子进程的错误流
4、getInputStream():获取子进程的输入流
5、getOutputStream():获取子进程的输出流
6、waitFor():导致当前线程等待,如有必要,一直要等到由该Process对象表示的进程已经终止。如果已终止该子进程,此方法立即返回。如果没有终止该子进程,调用的线程将被阻塞,知道退出子进程,根据管理,0表示正常终止。
注意:在Java中,调用runtime线程执行脚本是非常消耗资源的,所以切记不要频繁使用!
在调用runtime去执行脚本的时候,其实就是JVM开了一个子线程去调用JVM所在系统的命令,其中开了三个通道:输入流、输出流、错误流,其中输出流就是子线程走调用的通道。
大家都知道,waitFor是等待子线程执行命令结束后才访问,但是在runtime中,打开程序的命令如果不关闭,就不算子线程结束,比如如下代码。
private static Process p = null;
p = Runtime.getRuntime().exec("notepad.exe");
p.waitFor();
System.out.println("---------------我被执行了");
以上代码中,打开windows中记事本,如果我们不手动关闭记事本,那么输出语句就不会执行,这点事需要理解的。
然后是JAVA调用代码
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class RunShell {
public static void main(String[] args){
try {
String shpath="/home/felven/word2vec/demo-classes.sh";
Process ps = Runtime.getRuntime().exec(shpath);
ps.waitFor();
BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
StringBuffer sb = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
String result = sb.toString();
System.out.println(result);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
需要注意的是,在调用时需要执行waitFor()函数,因为shell进程是JAVA进程的子进程,JAVA作为父进程需要等待子进程执行完毕。
访问Linux服务器执行shell命令并将结果返回
userName:Linux用户名
password:Linux密码
ipAddr:IP地址
cmd:要执行的命令
public static String execute(String userName, String password, String ipAddr, String cmd) {
try {
//返回的结果
String result = "";
if (InetAddress.getByName(ipAddr).isReachable(1500)) {
Connection conn = new Connection(ipAddr);
conn.connect();
boolean isAuthed = conn.authenticateWithPassword(userName, password);
if (isAuthed) {
//打开一个会话
Session session = conn.openSession();
session.execCommand(cmd);
result = processStdout(session.getStdout(), cmd);
session.close();
conn.close();
} else {
throw new BusinessRuntimeException("执行" + cmd + "命令时失败,连接目标主机失败,用户名密码错误");
}
} else {
throw new BusinessRuntimeException("执行" + cmd + "命令时失败,连接目标主机失败,网络不通");
}
return result;
} catch (IOException e) {
throw new BusinessRuntimeException("执行" + cmd + "命令时失败,未知原因");
}
}
public static String processStdout(InputStream in, String cmd) {
InputStream stdout = new StreamGobbler(in);
StringBuilder buffer = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(stdout, StandardCharsets.UTF_8));
String line;
while ((line = br.readLine()) != null) {
buffer.append(line).append("\n");
}
} catch (IOException e) {
throw new BusinessRuntimeException("执行" + cmd + "命令时失败,未知原因");
}
return buffer.toString();
}
推荐阅读
-
在脚本或命令文件中使用 Shell 来执行命令的操作指南
-
使用Shell脚本来运行Linux命令的操作指南
-
四种在Linux中运行Shell脚本的方法详解
-
` 自动填充为 `cp test.txt`
- 文件和目录名补全:输入文件名首字母后按 Tab,如 `vi ed
` 显示可用的编辑器列表 - 查看命令帮助: - 使用 `man` 命令配合具体命令名获取详尽帮助,如 `man ls` 或者 `man grep --help`"> 在 Linux 中操作指令指南 - 基本构造与种类 - 指令组成: 1. **主指令 + 选项 + 参数**: 如 `ls -l /home`,`main-action option object` - 内置指令:系统预装的 shell 功能,如 `cd`, `pwd` - 外部指令:独立可执行文件,直接用文件名当作命令,如 `rm`, `mv` - **选项与参数**: - 选项:定制命令行为, `-l` 或 `--long-help` - 短选项:简写形式,例如 `-v` 和 `-V` 可能合并使用 - 长选项:详细描述的选项,如 `--version` 或 `--human-readable` - 参数:命令作用的目标,如 `ls` 对 `/home` 目录的操作 - **指令应用**: - 不同指令需要不同的参数 - 选项可带或不带参数,比如 `grep -i "keyword"` (忽略大小写搜索) - 参数间通常用空格分隔,如 `cp file1 file2 file3` - **中断与完成提示**: - 终止当前指令:按下 Ctrl+C - **自动完成**: - 输入部分命令关键词后,按 Tab 键补全命令,如 `cp ta
` 自动填充为 `cp test.txt` - 文件和目录名补全:输入文件名首字母后按 Tab,如 `vi ed ` 显示可用的编辑器列表 - 查看命令帮助: - 使用 `man` 命令配合具体命令名获取详尽帮助,如 `man ls` 或者 `man grep --help` -
在Linux中,通过命令行和脚本来实现远程Shell命令操作指南
-
在Node.js应用中运行shell脚本文件的步骤指南
-
在Python中运行壳(Shell)命令的6种方式指南
-
在Java中运行Linux命令( Shell 脚本)的操作指南
-
在Node.js中运行CMD或Shell命令的简易操作
-
在Python中运行和操作Linux命令的四种方式