欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

在Java中运行Linux命令( Shell 脚本)的操作指南

最编程 2024-07-25 18:16:24
...

在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();
    }

推荐阅读