Java连接Linux主机执行命令

Java连接Linux主机执行命令:将IP,用户名和密码替换掉就好了

package com.yulang.service.host;

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

import java.io.*;

/**
 * @ClassName: RemoteHost
 * @Description: Java连接Linux主机并执行命令
 * @version: v1.0.0
 * @author: yulang
 * @date: 2018/8/20 14:11
 * <p>
 * Modification History:
 * Date         Author          Version            Description
 * ------------------------------------------------------------
 * 2018/8/20      yulang          v1.1.0             第一次创建
 */
public class RemoteCommandUtil {
    private static final Logger log = LoggerFactory.getLogger(RemoteCommandUtil.class);
    private static String  DEFAULTCHART="UTF-8";

    private static String IP = "127.0.0.1";
    private static String HOST_NAME = "root";
    private static String HOST_PWD = "root";

    /**
     * 登录主机
     * @return
     *      登录成功返回true,否则返回false
     */
    public static Connection login(String ip, String userName, String userPwd){
        boolean flg=false;
        Connection conn = null;
        try {
            conn = new Connection(ip);
            conn.connect();//连接
            flg=conn.authenticateWithPassword(userName, userPwd);//认证
            if(flg){
                log.info("=========登录成功========="+conn);
                return conn;
            }
        } catch (IOException e) {
            log.error("=========登录失败========="+e.getMessage());
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 远程执行shll脚本或者命令  使用默认的cmd文件
     * @param cmd
     *      即将执行的命令
     * @return
     *      命令执行完后返回的结果值
     */
    public static String execute(String cmd){
        String result="";
        Connection conn = login(IP, HOST_NAME, HOST_PWD);
        try {
            if(conn !=null){
                Session session= conn.openSession();//打开一个会话
                session.execCommand(cmd);//执行命令
                result=processStdout(session.getStdout(),DEFAULTCHART);
                //如果为得到标准输出为空,说明脚本执行出错了
                if(StringUtils.isEmpty(result)){
                    log.info("得到标准输出为空,链接conn:"+conn+",执行的命令:"+cmd);
                    result=processStdout(session.getStderr(),DEFAULTCHART);
                }else{
                    log.info("执行命令成功,链接conn:"+conn+",执行的命令:"+cmd);
                }
                conn.close();
                session.close();
            }
        } catch (IOException e) {
            log.info("执行命令失败,链接conn:"+conn+",执行的命令:"+cmd+"  "+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 远程执行shll脚本或者命令
     * @param cmd
     *      即将执行的命令
     * @return
     *      命令执行完后返回的结果值
     */
    public static String execute(Connection conn,String cmd){
        String result="";
        try {
            if(conn !=null){
                Session session= conn.openSession();//打开一个会话
                session.execCommand(cmd);//执行命令
                result=processStdout(session.getStdout(),DEFAULTCHART);
                //如果为得到标准输出为空,说明脚本执行出错了
                if(StringUtils.isEmpty(result)){
                    log.info("得到标准输出为空,链接conn:"+conn+",执行的命令:"+cmd);
                    result=processStdout(session.getStderr(),DEFAULTCHART);
                }else{
                    log.info("执行命令成功,链接conn:"+conn+",执行的命令:"+cmd);
                }
                conn.close();
                session.close();
            }
        } catch (IOException e) {
            log.info("执行命令失败,链接conn:"+conn+",执行的命令:"+cmd+"  "+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 解析脚本执行返回的结果集
     * @param in 输入流对象
     * @param charset 编码
     * @return
     *       以纯文本的格式返回
     */
    private static String processStdout(InputStream in, String charset){
        InputStream  stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();;
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout,charset));
            String line=null;
            while((line=br.readLine()) != null){
                buffer.append(line+"\n");
            }
        } catch (UnsupportedEncodingException e) {
            log.error("解析脚本出错:"+e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            log.error("解析脚本出错:"+e.getMessage());
            e.printStackTrace();
        }
        return buffer.toString();
    }

    public static void main(String[] args) {
        //sh /home/test/shell/hello.sh 
        String cd = RemoteCommandUtil.execute("sh /root/start.sh");
        System.out.println(cd);
    }
}

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值