Java 执行linux的shell命令

Java程序运行时如何对linux服务器做出一些指令,可以直接执行shell命令或者脚本并输出控制台信息。
1.引入类
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

2.单个命令执行方法

    public void exec(String deployHost, String deployUsername, String deployPassword, String cmd) {
        try {
            Connection conn = new Connection(deployHost);
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(deployUsername, deployPassword);
            if (isAuthenticated == false) {
                throw new IOException("认证失败");
            }
            Session sess = conn.openSession();
            sess.execCommand(cmd);
            //创建输入流
            InputStream stdout = new StreamGobbler(sess.getStdout());
            //字符流
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
            while (true) {
                String line = br.readLine();
                if (line == null)
                    break;
                logger.info(line);
            }
            logger.info("ExitCode: " + sess.getExitStatus());
            //关闭连接
            stdout.close();
            sess.close();
            conn.close();
        } catch (IOException e) {
            logger.error("Command execution error");
            e.printStackTrace();
        }

    }

3.多条命令执行方法

public void execCommands(String deployHost, String deployUser, String deployPassword, String[] cmd) {
        try {
            Connection conn = new Connection(deployHost);
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(deployUser, deployPassword);
            if (isAuthenticated == false) {
                throw new IOException("认证失败");
            }
            Session sess = null;
            for (int i = 0; i < cmd.length; i++) {
                sess = conn.openSession();
                sess.execCommand(cmd[i]);
                InputStream stdout = new StreamGobbler(sess.getStdout());
                //字符流
                BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
                while (true) {
                    String line = br.readLine();
                    if (line == null)
                        break;
                    logger.info(line);
                }
                stdout.close();
                sess.close();
            }
//            logger.info("ExitCode: over");
            //关闭连接
            conn.close();
        } catch (IOException e) {
            logger.error("Command execution error");
            e.printStackTrace();
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值