SshCommandUtil工具类的学习

package com.po;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;

import com.trilead.ssh2.Connection;
import com.trilead.ssh2.InteractiveCallback;
import com.trilead.ssh2.KnownHosts;
import com.trilead.ssh2.ServerHostKeyVerifier;
import com.trilead.ssh2.Session;
import com.trilead.ssh2.StreamGobbler;

public class SshCommandUtil {

    private static SshCommandUtil sshUtil = null;
    
    private static String knownHostPath = "knownHost";
    
    private static KnownHosts database = new KnownHosts();
    
    private SshCommandUtil() throws IOException{
        
        String path = System.getProperty("user.home")+"/.gridview";        
        File knownHostFile = new File(path);
        if (!knownHostFile.exists()) {
            
            knownHostFile.mkdir();
        }
        knownHostPath = path+"/"+knownHostPath;
        File knownHostFileR = new File(knownHostPath);
        
        if (! knownHostFileR.exists()) {
            
            knownHostFileR.createNewFile();
        }
        database.addHostkeys(knownHostFileR);
    }
    
    public synchronized static SshCommandUtil getinstance() throws IOException{
        
          if (null == sshUtil) {
              
              sshUtil = new SshCommandUtil();
          }
          return sshUtil;
    }
    
    public Result exeCommand(String hostName,int port,String userName,String password,String command){
        
        Result result = new Result();
        
        Connection con = new Connection(hostName,port);
        
        try{
            
            String[] hostKeyAlgos = database.getPreferredServerHostkeyAlgorithmOrder(hostName);
            
            if (null != hostKeyAlgos){
                
                con.setServerHostKeyAlgorithms(hostKeyAlgos);
            }
            
            con.connect(new ServerHostKeyVerifier(){
                
                @Override
                public boolean verifyServerHostKey(String hostName, int port,
                        String serverHostKeyAlgorithm, byte[] serverHostKey) throws Exception {
                    
                    int result = database.verifyHostkey(hostName, serverHostKeyAlgorithm, serverHostKey);
                    
                    switch(result) {
                    
                    case KnownHosts.HOSTKEY_IS_OK:
                        
                        return true;
                        
                    case KnownHosts.HOSTKEY_HAS_CHANGED:
                        
                        break;
                        
                    case KnownHosts.HOSTKEY_IS_NEW:
                        
                        break;
                        
                    default:
                            throw new IllegalStateException();
                    }
                    
                    
                    String hashedHostName = KnownHosts.createHashedHostname(hostName);
                    //hashedHostName = hostName;
                    database.addHostkey(new String[]{hashedHostName}, serverHostKeyAlgorithm, serverHostKey);
                    
                    KnownHosts.addHostkeyToFile(new File(knownHostPath),new String[]{hashedHostName}, serverHostKeyAlgorithm, serverHostKey);
                    
                    return true;
                }
                
                
            });
            
        }catch(IOException e) {
            
            e.printStackTrace();            
            result.setStatus(false);
            result.setErrMsg(e.getMessage());
            return result;
        }
        
        Session session = null;
        
        boolean isAuthenticated = false;
        try{
            
            final String pwd = password;
            if (con.isAuthMethodAvailable(userName,"keyboard-interactive")) {
                
                isAuthenticated = con.authenticateWithKeyboardInteractive(userName, new InteractiveCallback(){

                    @Override
                    public String[] replyToChallenge(String name, String instruction,
                            int numPrompts, String[] prompt, boolean[] echo)
                            throws Exception {
                        
                        String[] result = new String[numPrompts];
                        
                        for (int i=0; i < numPrompts;i++) {
                            
                             result[i] = pwd;
                        }
                        return result;
                    }
                    
                    
                });
            } else if (con.isAuthMethodAvailable(userName,"publickey")) {
                
                isAuthenticated = con.authenticateWithPublicKey(userName,new char[0], password);
            } else {
                
                isAuthenticated = con.authenticateWithPassword(userName, password);
                
            }
            
            if (!isAuthenticated) {
                
                System.out.println(hostName+" Authentication failed.");
                result.setStatus(false);
                result.setErrMsg(hostName+" Authentication failed.");
                return result;
            }
            
            session = con.openSession();
            
            session.execCommand(command);
            
            StringBuilder errsb = new StringBuilder();
            
            InputStream stdErr = new StreamGobbler(session.getStderr());
            
            BufferedReader reader = new BufferedReader(new InputStreamReader(stdErr));
            
            while(true) {
                
                String line = reader.readLine();
                
                if (null == line) {
                    
                    break;
                }
                
                errsb.append(line+"\n");
            }
            
            result.setErrMsg(errsb.toString());
            
            StringBuilder successsb = new StringBuilder();
            
            InputStream stdOut = new StreamGobbler(session.getStdout());
            reader = new BufferedReader(new InputStreamReader(stdOut));
            
            while(true) {
                
                String line = reader.readLine();
                if (null == line) {
                    
                    break;
                }
                successsb.append(line+"\n");
            }
            
            result.setSuccessMsg(successsb.toString());
            
            if (errsb.length() <= 0) {
                
                result.setStatus(true);
            } else {
                
                result.setStatus(false);
            }
            
        }catch(IOException e) {
            
            e.printStackTrace();
            result.setStatus(false);
            result.setErrMsg(e.getMessage());
            return result;
        }finally{
            
             if (null != session) {
                
                 session.close();
                 session = null;
             }
             if (null != con) {
                
                 con.close();
                 con = null;
             }
        }
        
        return result;
    }
    /**
     * @param args
     */
    public static void main(String[] args)throws Exception {
        // TODO Auto-generated method stub
        SshCommandUtil ssh = SshCommandUtil.getinstance();
        Result result = ssh.exeCommand("10.0.31.231",22,"root","sugon123","cat /proc/cpuinfo");
        System.out.println(result);
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值