java执行shell命令工具类


import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author :cuilei
 * @description:主要调用ssh2和io的包,用于远程执行一两条命令,没加任何过滤限制,谨慎使用
 * @date :2020/8/17 11:18
 */
public class ExecShellUtil {
    private final static Logger logger = LoggerFactory.getLogger(ExecShellUtil.class);

    private String IP;//要远程登录的IP地址
    private String username;//用户名
    private String password;//密码

    public ExecShellUtil(String IP, String username,String password){
        this.IP=IP;
        this.username=username;
        this.password=password;
    }

    //命令执行
    public boolean exec(String command) throws InterruptedException{
        boolean rtn = false;
        try {
            Connection conn = new Connection(IP);
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(username, password);
            if (isAuthenticated == false){
                throw new IOException("Authentication failed.");
            }
            logger.info("=======================>>>"+IP+"-"+username+"<<<=======================");
            logger.info("command: "+command);
            Session sess = conn.openSession();
            sess.execCommand(command);

            InputStream stdout = new StreamGobbler(sess.getStdout());
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));

            InputStream stderr = new StreamGobbler(sess.getStderr());
            BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stderr));

            String line = null;
            while ( (line = br.readLine())!=null )
            {
                logger.info(IP+" "+username+" out> "+line);
            }

            while (true)
            {
                line = stderrReader.readLine();
                if (line == null)
                    break;
                logger.info(IP+" "+username+" out> "+line);
            }

            /* Show exit status, if available (otherwise "null") */
            logger.info("ExitCode: " + sess.getExitStatus()+" "+IP+":"+command);
            sess.close();
            conn.close();
            rtn = new Integer(0).equals(sess.getExitStatus());
            return rtn;
        } catch (IOException e) {
            logger.warn("Error ......",e);
            e.printStackTrace();
            System.exit(2);
            return rtn;
        }
    }





/*    public static void main(String[] args) throws InterruptedException {

        ExecShellUtil es = new ExecShellUtil("192.168.1.16","topcom","lenovo123");
        System.out.println("==========================================单个命令测试执行==========================================");
        es.exec("ls");//执行单行命令
        System.out.println("==========================================多个命令测试执行==========================================");
        es.exec("cd /home/xcl/spider/weibo_pc_spider_local/bin/ && ls && date");//多个命令之间使用&&隔开
        //ganyMedUtil.execMoreShellCommand("");
        //ganyMedUtil.exec("ls");

    }*/
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM