java如何执行多行linux命令
1:避免执行一条linux程序卡死,可多条放一起执行
由于执行linux指令后有可能卡死,后面的操作可能不会执行
,同时执行多条语句,并设置执行结束
使用Runtime.getRuntime().exec执行多行linux命令使用分号“;”隔开即可,亲试有效!
举例参考
public static void main(String[] args) throws Exception {
String[] cmd = new String[] { "/bin/sh", "-c", "iptables -I INPUT -s 211.1.0.24 -j DROP;iptables -I INPUT -s 211.1.0.25 -j DROP" };
try {
Runtime.getRuntime().exec(cmd);
} catch (Exception e) {
e.printStackTrace();
}
}
例如:多条linux凭接一起
“iptables -I INPUT -s 211.1.0.24 -j DROP;iptables -I INPUT -s 211.1.0.25 -j DROP”
2:设置out.println(“exit”);防止输入流不结束
out.println(“exit”);//这个命令必须执行,否则in流不结束。
//shell脚本中有echo或者print输出, 会导致缓冲区被用完,程序卡死! 为了避免这种情况,
参考1:
调用多条linux命令:
("/bin/bash", null, new File("/bin"))
public static void zipFile(String filename, String paht) {
File[] file = new File(paht).listFiles();
File zipfile = new File(paht + filename + ".zip");
if(zipfile.exists())
return;
if(file != null && file.length > 0){
Runtime run = Runtime.getRuntime();
File wd = new File("/bin");
Process proc = null;
try {
proc = run.exec("/bin/bash", null, wd);
if (proc != null) {
BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
out.println("cd " + paht);
out.println("pwd");
out.println("zip -m " + filename + ".zip *" + filename + "*.txt");
out.println("exit");//这个命令必须执行,否则in流不结束。
//shell脚本中有echo或者print输出, 会导致缓冲区被用完,程序卡死! 为了避免这种情况,
//一定要把缓冲区读一下 reader.readLine() 读出即可,如果需要输出的话可以使用StringBuilder
//进行拼接然后输出
String line;
StringBuilder sb = new StringBuilder();
while ((line = in.readLine()) != null) {
sb.append(line).append("\r\n");
}
proc.waitFor();
in.close();
out.close();
proc.destroy();
}
} catch (Exception e) {
logger.error("IOException", e);
}
}else
logger.info("无待压缩文件-------------------");
}
参考2
通过数组调用:
String[] cmd = new String[]{“sh”, “-c”, "zip -m " + path + filename + ".zip " + path + “" + filename + ".txt”};
public static void zipFile(String filename, String path) {
File[] file = new File(path).listFiles();
File zipfile = new File(path + filename + ".zip");
if(zipfile.exists())
return;
if(file != null && file.length > 0){
try {
String[] cmd = new String[]{"sh", "-c", "zip -m " + path + filename + ".zip " + path + "*" + filename + "*.txt"};
Process p = Runtime.getRuntime().exec(cmd);
//shell脚本中有echo或者print输出, 会导致缓冲区被用完,程序卡死! 为了避免这种情况,
//一定要把缓冲区读一下 reader.readLine() 读出即可,如果需要输出的话可以使用StringBuilder
//进行拼接然后输出
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while((line = reader.readLine()) != null) {
sb.append(line).append("\r\n");
}
p.waitFor();
p.destroy();
} catch (Exception e1) {
logger.error("IOException", e1);
}
}else
logger.info("无待压缩文件-------------------");
}
参考3
命令之间用&连接
Process p = Runtime.getRuntime().exec(“cmd /cd: & cd bin/”);
附:
执行linux指令后线程阻塞
在java中调用操作系统的程序时,可以使用java.lang.Runtime.getRuntime().exec() 来实现,但是这个方法在调用命令后就直接返回当前线程了;程序设计时,有时候需要在等待调用的系统程序完成操作后,当前线程才能做下一步操作,此时可以用类Process的方法waitFor()来实现,它会阻塞当先线程直至调用程序运行结束
java.lang.Process process = java.lang.Runtime.getRuntime().exec("");//执行命令生成cube
try {
process.waitFor();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
proc_stat = checkFileSize() ? "1" : "3";
Process的方法waitFor()介绍,取自API文档:
waitFor
public abstract int waitFor()
throws InterruptedException导致当前线程等待,如果必要,一直要等到由该 Process 对象表示的进程已经终止。如果已终止该子进程,此方法立即返回。如果没有终止该子进程,调用的线程将被阻塞,直到退出子进程。
返回:
进程的出口值。根据惯例,0 表示正常终止。
抛出:
InterruptedException - 如果当前线程在等待时被另一线程 中断,则停止等待,抛出 InterruptedException。
具体用法参考
https://blog.csdn.net/wochuo1314/article/details/78607642?
3:指令书写
管道符替换参考
1. public Process exec(String command) throws IOExecption
2. public Process exec(String command,String [] envp) throws IOExecption
3. public Process exec(String command,String [] envp,File dir) throws IOExecption
4. public Process exec(String[] cmdarray) throws IOExecption
5. public Process exec(String[] cmdarray,String [] envp) throws IOExecption
6. public Process exec(String[] cmdarray,String [] envp,File dir) throws IOExecption
runtime.exec( new String[]{"/bin/bash", “-c”, “java HelloWorld >> output.txt”} );
runtime.exec( new String[]{"/bin/bash", “-c”, “java HelloWorld >> output.txt”} ,null );
runtime.exec( new String[]{"/bin/bash", “-c”, “java HelloWorld >> output.txt”} ,null,null );
不过要注意,如果使用java /home/path/HelloWorld 时,’ / '会被解析成 " . ",从而报出 “错误: 找不到或无法加载主类 .home.path.HelloWorld ”.
具体参考如下
https://blog.csdn.net/timo1160139211/article/details/75006938?