ssh方式与服务器建立连接

ssh方式与服务器建立连接

package com.ustcinfo.cinas.pmng.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

/**
 *************************************************************** 
 * <p> 
 * @ProjectName : CINASProcessManager
 * @CLASS    : SocketConnectUtil 
 * @AUTHOR    : aa 
 * @DESCRIPTION :  ssh方式与服务器建立连接
 * @VERSION   : v1.0 
 * @DATE     : 2014-5-20 上午9:49:01 
 * <p> 
 ****************************************************************
 */
public class SSHConnectUtil {
    private static final Logger logger =LoggerFactory.getLogger(SSHConnectUtil.class);
    private static final SSHConnectUtil instance = new SSHConnectUtil();
    
    public SSHConnectUtil() {
    }

    public static SSHConnectUtil getInstance() {
        return instance;
    }

    /**
     * @description 
     * @description 
     * @author  wangkun
     * @param ip
     * @param user
     * @param psw
     * @param port
     * @param shellCommand
     * @param matcherKey
     * @return
     * @throws Exception
     */
    public  String sshShell(String ip, String user, String psw
            ,int port , String shellCommand) throws Exception{
        Session session = null;
        Channel channel = null;
        String result=null;
        JSch jsch = new JSch();
        if(port <=0){
            //连接服务器,采用默认端口
            session = jsch.getSession(user, ip);
        }else{
            //采用指定的端口连接服务器
            session = jsch.getSession(user, ip ,port);
        }
        //如果服务器连接不上,则抛出异常
        if (session == null) {
            throw new Exception("session is null");
        }
        //设置登陆主机的密码
        session.setPassword(psw);//设置密码   
        //设置第一次登陆的时候提示,可选值:(ask | yes | no)
        session.setConfig("StrictHostKeyChecking", "no");
        //设置登陆超时时间   
        session.connect(30000);
        try {
            //创建sftp通信通道
            channel = (Channel) session.openChannel("shell");
            channel.connect(1000);
            //获取输入流和输出流
            InputStream instream = channel.getInputStream();
            OutputStream outstream = channel.getOutputStream();
            
            //发送需要执行的SHELL命令,需要用
结尾,表示回车
            shellCommand = shellCommand+" 
";
            outstream.write(shellCommand.getBytes());
            outstream.flush();
            //获取命令执行的结果
            result =readStream(instream);
            outstream.close();
            instream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.disconnect();
            channel.disconnect();
        }
        return result;
    }
    
    
    /**
     * @description 读取流
     * @author  wangkun
     * @param inStream
     * @return
     * @throws Exception
     */
    public static String readStream(InputStream inStream) throws Exception {  
        InputStreamReader InputStreamReader = new InputStreamReader(inStream);
        BufferedReader reader=new BufferedReader(InputStreamReader);
        String s = null;
        StringBuffer bf = new StringBuffer();
        
        while((s = reader.readLine())!=null){
            bf.append(s);
             if(s.equals("goodbye")){
                 break;
             }
             
        }
        return bf.toString();
    }
    
    
    
    public static void main(String[] args) {
        String ip ="192.168.80.211";
        String user ="cinas";
        String psw="inas2013";
        int port=22;
        //String shellCommand = "ps -ef|grep 1080 | grep -v grep | awk '{print $10}' 
";
        //String shellCommand ="./$BASE_HOME/scanprocess.sh 
";
        //String processKey="1080net";
         String shellCommand="./$BASE_HOME/restartprocess.sh";
        //String shellCommand ="ps -ef|grep java|grep -v grep 
";
        /*if(!shellCommand.contains("awk '{print")){
            System.out.println("请输入正确的指令");
            return ;
        }*/
        String matcherKey="1080net_4GCS";
        try {
            SSHConnectUtil sSHConnectUtil = new SSHConnectUtil();
            //String result = sSHConnectUtil.sshShell(ip, user, psw, port, shellCommand);
            //System.out.println("result :"+result);
            
            
            
            
            String[] processKey =matcherKey.split("_");
            for (int i = 0; i < processKey.length; i++) {
                System.out.println("**************"+processKey[i]);
                String command =shellCommand+" "+processKey[i].toString();
                System.out.println("执行命令是:"+shellCommand);
                String result = sSHConnectUtil.sshShell(ip, user, psw, port, command);
                System.out.println("==========>命令执行结果是:"+result);
                logger.info("==========>命令执行结果是:"+result);
                command=shellCommand;
            }
            
            
            
            
           /*//StringTokenizer st = new StringTokenizer(matcherKey,"_");
            List listRuning = new ArrayList();
            List listStop = new ArrayList();
            
           String[] processKey =matcherKey.split("_");
           for (int i = 0; i < processKey.length; i++) {
            System.out.println(processKey[i]);
            if(result.contains(processKey[i])){
                listRuning.add(processKey[i]);
            }else{
                listStop.add(processKey[i]);
            }
        }
           System.out.println("运行的进程个数:"+listRuning.size());
           System.out.println("停止的进程个数:"+listStop.size());*/
           
           
           /*List list = new ArrayList();
             while (st.hasMoreTokens()) {
                 System.out.println("AAAAAAAAA:"+st.nextToken());
                 if(result.contains(st.nextToken())){
                     list.add(st.nextToken());
                    }
             }
             System.out.println("队列长度:"+list.size());*/

           
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
        
}