zoukankan      html  css  js  c++  java
  • SSH连接工具类

    public class SshConnTool {
    
    	private Connection conn;
    
    	private String ipAddr;
    	private String charset = Charset.defaultCharset().toString();
    	private String userName;
    	private String password;
    
    	public SshConnTool(String ipAddr, String userName, String password,
    			String charset) {
    		this.ipAddr = ipAddr;
    		this.userName = userName;
    		this.password = password;
    		if (charset != null) {
    			this.charset = charset;
    		}
    	}
    
    	/**
    	 * 登录远程Linux主机
    	 * 
    	 * @return
    	 * @throws IOException
    	 */
    	public boolean login() throws IOException {
    		conn = new Connection(ipAddr);
    		conn.connect(); // 连接
    		return conn.authenticateWithPassword(userName, password); // 认证
    	}
    
    	/**
    	 * 执行Shell脚本或命令
    	 * 
    	 * @param cmds
    	 *            命令行序列
    	 * @return
    	 */
    	public String exec(String cmds) {
    		InputStream in = null;
    		String result = "";
    		try {
    			if (this.login()) {
    				Session session = conn.openSession(); // 打开一个会话
    				session.execCommand(cmds);
    				in = session.getStdout();
    				result = this.processStdout(in, this.charset);
    				conn.close();
    			}
    		} catch (IOException e1) {
    			e1.printStackTrace();
    		}
    		return result;
    	}
    
    	/**
    	 * 解析流获取字符串信息
    	 * 
    	 * @param in
    	 *            输入流对象
    	 * @param charset
    	 *            字符集
    	 * @return
    	 */
    	public String processStdout(InputStream in, String charset) {
    		byte[] buf = new byte[1024];
    		StringBuffer sb = new StringBuffer();
    		try {
    			while (in.read(buf) != -1) {
    				sb.append(new String(buf, charset));
    			}
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    		return sb.toString();
    	}
    	
    	public Connection getConn() {
    		return conn;
    	}
    
    	public void setConn(Connection conn) {
    		this.conn = conn;
    	}
    }
    
  • 相关阅读:
    csu1217: 奇数个的那个数
    小试SAS 判别分析
    bfs poj2965
    STL set常用操作
    csu1002 A+B(III)
    HDOJ 1002 的几种方法
    SQL知识积累
    CSV文件格式介绍
    ASP.net Web Form 知识积累
    C# 位域[flags] 枚举
  • 原文地址:https://www.cnblogs.com/fuhengheng/p/8038161.html
Copyright © 2011-2022 走看看