欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

工具类-Linux-SSH处理类

程序员文章站 2022-07-15 14:58:54
...

ssh工具类

工具类一

package com.alipay.api.com.cn.test.sslTest;

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


import com.trilead.ssh2.Connection;
import com.trilead.ssh2.SCPClient;
import com.trilead.ssh2.Session;
import com.trilead.ssh2.StreamGobbler;

/**
 * <p> @Description </p>
 * <p> @company Asiainfo-linkage (NJ) </p>
 * <p> @author 闫瑞国 </p>
 * <p> @Email [email protected] </p>
 * <p> @createDate 2012-6-23 下午10:40:53 </p>
 * <p> @modifyDate </p>
 * <p> @version 1.0 </p>
 */
public final class SSHUtils {


    public static String ssh4Shell(String ip, int sshPort, String username, String password, String shellName, String shell) throws Exception {
        return ssh4Shell(ip, sshPort, username, password, shellName, null, shell);
    }

    public static String ssh4Shell(String ip, int sshPort, String username, String password, String shellName, String parameters, String shell) throws Exception {
        String rtn = null;
        Connection conn = null;
        Session sess = null;
        try {
            conn = new Connection(ip, sshPort);

            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(username, password);

            if (!(isAuthenticated)) {
                throw new IOException("认证失败");
            }

            String fileName = shellName + ".sh";

            upload(conn, ip, sshPort, username, password, shell.getBytes(), "/tmp/", fileName);
            sess = conn.openSession();

            if (parameters.equals("")||parameters==null) {
                sess.execCommand(" chmod +x /tmp/" + fileName + " && /tmp/" + fileName + " && rm -rf /tmp/" + fileName);
            } else {
                sess.execCommand(" chmod +x /tmp/" + fileName + " && /tmp/" + fileName + " " + parameters + "  && rm -rf /tmp/" + fileName);
            }
            InputStream stdout = new StreamGobbler(sess.getStdout());
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
            while (true) {
                String line = br.readLine();
                if (line == null) {
                    break;
                }

                rtn = line;
            }

        } catch (Exception ex) {
        } finally {
            if (sess != null) {
                sess.close();
            }
            if (conn != null) {
                conn.close();
            }
        }

        return rtn;
    }

    public static String[] ssh4Shell(String ip, int sshPort, String username, String password, String[] shellName, String[] shell) throws Exception {
        return ssh4Shell(ip, sshPort, username, password, shellName, null, shell);
    }

    public static String[] ssh4Shell(String ip, int sshPort, String username, String password, String[] shellName, String[] parameters, String[] shell) throws Exception {
        String[] rtn = new String[shellName.length];
        Connection conn = null;
        try {
            conn = new Connection(ip, sshPort);

            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(username, password);

            if (!(isAuthenticated)) {
                throw new IOException("认证失败");
            }

            String[] fileName = new String[shellName.length];

            byte[][] b = new byte[shellName.length][];
            for (int i = 0; i < shellName.length; ++i) {
                fileName[i] = shellName[i] + ".sh";
                b[i] = shell[i].getBytes();
            }
            upload(conn, ip, sshPort, username, password, b, "/tmp/", fileName);

            for (int i = 0; i < shellName.length; i++) {
                Session sess = conn.openSession();
                try {
                    if ((parameters == null) || (parameters[i]).equals("")) {
                        sess.execCommand(" chmod +x /tmp/" + fileName[i] + " && /tmp/" + fileName[i] + " && rm -rf /tmp/" + fileName[i]);
                    } else {
                        sess.execCommand(" chmod +x /tmp/" + fileName[i] + " && /tmp/" + fileName[i] + " " + parameters[i] + "  && rm -rf /tmp/" + fileName[i]);
                    }
                    InputStream stdout = new StreamGobbler(sess.getStdout());
                    BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
                    while (true) {
                        String line = br.readLine();
                        if (line == null) {
                            break;
                        }

                        rtn[i] = line;
                    }

                } catch (Exception ex) {
                } finally {
                    if (sess != null)
                        sess.close();
                }
            }
        } catch (Exception ex) {
        } finally {
            if (conn != null) {
                conn.close();
            }
        }

        return rtn;
    }

    public static String ssh4Command(String ip, int sshPort, String username, String password, String command) throws Exception {

        StringBuilder rtn = new StringBuilder();
        Connection conn = null;
        Session sess = null;
        try {
            conn = new Connection(ip, sshPort);

            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(username, password);

            if (!(isAuthenticated)) {
                throw new IOException("认证失败");
            }

            sess = conn.openSession();

            sess.execCommand(command);
            InputStream stdout = new StreamGobbler(sess.getStdout());
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
            while (true) {
                String line = br.readLine();
                if (line == null) {
                    break;
                }else {
                    if(line.equals("")){
                        rtn.append(line);
                    }

                }

            }

        } catch (Exception ex) {
            throw ex;
        } finally {
            if (sess != null) {
                sess.close();
            }
            if (conn != null) {
                conn.close();
            }
        }

        return rtn.toString();
    }


    public static void upload(Connection conn, String ip, int sshPort, String username, String password, byte[] bytes, String destPath, String fileName) throws Exception {
        try {
            SCPClient scp = conn.createSCPClient();
            scp.put(bytes, fileName, destPath);
        } catch (Exception ex) {
            throw ex;
        }
    }

    public static void upload(Connection conn, String ip, int sshPort, String username, String password, byte[][] bytes, String destPath, String[] fileName) throws Exception {
        try {
            SCPClient scp = conn.createSCPClient();
            for (int i = 0; i < fileName.length; ++i)
                scp.put(bytes[i], fileName[i], destPath);
        } catch (Exception ex) {
            throw ex;
        }
    }

    public static String ssh4Command(String ip, int sshPort, String username, String password, String command,boolean isSynch) throws Exception {

        StringBuilder rtn = new StringBuilder();
        Connection conn = null;
        Session sess = null;
        try {
            conn = new Connection(ip, sshPort);

            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(username, password);

            if (!(isAuthenticated)) {
                throw new IOException("认证失败");
            }

            sess = conn.openSession();
            sess.execCommand(command);

            InputStream stdout = new StreamGobbler(sess.getStdout());
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
            while (true) {
                String line = br.readLine();
                if (line == null) {
                    break;
                }else {
                    if(line.equals("")){
                        rtn.append(line);
                        if(!isSynch && "---------------------".equals(line)){
                            break;
                        }
                    }

                }

            }

        } catch (Exception ex) {
            throw ex;
        } finally {
            if (sess != null) {
                sess.close();
            }
            if (conn != null) {
                conn.close();
            }
        }

        return rtn.toString();
    }


/*
    public static void runSSH(DTOAmBatchWfPs[] batchWfPsValues, long wfFlowId, String regionId, long billDay,long billlingCycleId) throws Exception {
        if(batchWfPsValues==null || batchWfPsValues.length<1){
            //节点-[{0}]-没有配置AM_BATCH_WF_PS,无法完成
            ExceptionUtil.throwBusinessException("AMS0700505",Long.toString(wfFlowId));
        }
        long acctMode = 0;
        long modeValue = 0;

        for (int i = 0; i < batchWfPsValues.length; i++) {
            acctMode += batchWfPsValues[i].getThreadNum();
        }

        StringBuilder command = new StringBuilder();

        for (int i = 0; i < batchWfPsValues.length; i++) {
            command.delete(0, command.length());

            command.append("cd ").append(batchWfPsValues[i].getShellCatalog())
                    .append(" && ")
                    .append(batchWfPsValues[i].getMonitorShell());

            if(log.isInfoEnabled()){
                log.info("SSH Command : "+command);
            }

            String rtn = SSHUtil.ssh4Command(batchWfPsValues[i].getHostIp(), batchWfPsValues[i].getPort(),
                    batchWfPsValues[i].getUserName(), K.k_s(batchWfPsValues[i].getPassword()), command.toString());

            if(StringUtils.isNotBlank(rtn) && rtn.equals("PROCESS_EXIST")){
                String[] args = new String[]{batchWfPsValues[i].getHostIp(),Long.toString(batchWfPsValues[i].getPort())
                        ,batchWfPsValues[i].getUserName(),batchWfPsValues[i].getWfProcessName(),
                        batchWfPsValues[i].getShellCatalog()+"/"+batchWfPsValues[i].getMonitorShell()};
                //IP-{0}端口-{1}-用户名-{2}-进程-{3}-监控脚本位置-{4},进程已存在
                ExceptionUtil.throwBusinessException("AMS0700545", args);
            }

            command.delete(0, command.length());
            command.append("cd ").append(batchWfPsValues[i].getShellCatalog())
                    .append(" && ")
                    .append(batchWfPsValues[i].getStartShell())
                    .append(" ").append(regionId)
                    .append(":").append(billDay)
                    .append(":").append(billlingCycleId)
                    .append(":").append(wfFlowId)
                    .append(":").append(batchWfPsValues[i].getWfProcessId())
                    .append(":").append(acctMode)
                    .append(":").append(modeValue).append("-").append((modeValue+batchWfPsValues[i].getThreadNum())-1);

            if(StringUtils.isNotBlank(batchWfPsValues[i].getParas())){
                command.append(":").append(batchWfPsValues[i].getParas());
            }

            modeValue += modeValue+batchWfPsValues[i].getThreadNum();

            if(log.isInfoEnabled()){
                log.info("SSH Command : "+command);
            }

            SSHUtils.ssh4Command(batchWfPsValues[i].getHostIp(), batchWfPsValues[i].getPort(),
                    batchWfPsValues[i].getUserName(), K.k_s(batchWfPsValues[i].getPassword()), command.toString());

        }
    }
*/
}

工具类二

package com.xxx.api.com.cn.test.sslTest;

import com.jcraft.jsch.*;


import java.io.BufferedReader;

import java.io.InputStreamReader;
import java.util.ArrayList;

/**
 * Created by Administrator on 2018/10/10.
 */
public class Demo1 {

    //远程主机的ip地址
    private String ip;
    //远程主机登录用户名
    private String username;
    //远程主机的登录密码
    private String password;
    //设置ssh连接的远程端口
    public static final int DEFAULT_SSH_PORT = 22;
    //保存输出内容的容器
    private ArrayList<String> stdout;

    /**
     * 初始化登录信息
     * @param ip
     * @param username
     * @param password
     */
    public Demo1(final String ip, final String username, final String password) {
        this.ip = ip;
        this.username = username;
        this.password = password;
        stdout = new ArrayList<String>();
    }
    /**
     * 执行shell命令
     * @param command
     * @return
     */
    public int execute(final String command) {
        int returnCode = 0;
        JSch jsch = new JSch();
//        MyUserInfo userInfo = new MyUserInfo();

        try {
            //创建session并且打开连接,因为创建session之后要主动打开连接
            Session session = jsch.getSession(username, ip, DEFAULT_SSH_PORT);
            session.setPassword(password);

            session.setConfig("StrictHostKeyChecking", "no");
//            session.setUserInfo(UserInfo);
            session.connect();

            //打开通道,设置通道类型,和执行的命令
            Channel channel = session.openChannel("exec");//exec
            ChannelExec channelExec = (ChannelExec)channel;
            channelExec.setCommand(command);

            channelExec.setInputStream(null);
            BufferedReader input = new BufferedReader(new InputStreamReader
                    (channelExec.getInputStream()));

            channelExec.connect();
            System.out.println("The remote command is :" + command);

            //接收远程服务器执行命令的结果
            String line;
            while ((line = input.readLine()) != null) {
                stdout.add(line);
            }
            input.close();

            // 得到returnCode
            if (channelExec.isClosed()) {
                returnCode = channelExec.getExitStatus();
            }

            // 关闭通道
            channelExec.disconnect();
            //关闭session
            session.disconnect();

        } catch (JSchException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnCode;
    }
    /**
     * get stdout
     * @return
     */
    public ArrayList<String> getStandardOutput() {
        return stdout;
    }

    public static void main(final String [] args) throws Exception {
         Demo1 shell = new Demo1("10.3.3.182", "aiprodcfg", "aiprodcfg#_1213");
        shell.execute("ls");

        ArrayList<String> stdout = shell.getStandardOutput();
        for (String str : stdout) {
            System.out.println(str);
        }
    }



}

MyUserInfo.java

package com.xxx.api.com.cn.test.sslTest;

/**
 * Created by Administrator on 2018/10/10.
 */
import com.jcraft.jsch.UserInfo;

public class MyUserInfo implements UserInfo {

    @Override
    public String getPassphrase() {
        // TODO Auto-generated method stub
        System.out.println("MyUserInfo.getPassphrase()");
        return null;
    }

    @Override
    public String getPassword() {
        // TODO Auto-generated method stub
        System.out.println("MyUserInfo.getPassword()");
        return null;
    }

    @Override
    public boolean promptPassphrase(String arg0) {
        // TODO Auto-generated method stub
        System.out.println("MyUserInfo.promptPassphrase()");
        System.out.println(arg0);
        return false;
    }

    @Override
    public boolean promptPassword(String arg0) {
        // TODO Auto-generated method stub
        System.out.println("MyUserInfo.promptPassword()");
        System.out.println(arg0);
        return false;
    }

    @Override
    public boolean promptYesNo(String arg0) {
        // TODO Auto-generated method stub'
        System.out.println("MyUserInfo.promptYesNo()");
        System.out.println(arg0);
        if (arg0.contains("The authenticity of host")) {
            return true;
        }
        return true;
    }

    @Override
    public void showMessage(String arg0) {
        // TODO Auto-generated method stub
        System.out.println("MyUserInfo.showMessage()");
    }

}