• 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;
    	}
    }
    
  • 相关阅读:
    dsp1
    数字信号处理中的常用方法
    近一星期的学习计划4-8 到 4-15
    近一个月的学习计划!4-8
    离散时间与系统-1
    python _列表
    2016-1-19
    fushioncharts 使用教程要点---使用JSON数据方式
    使用easeui dialog弹出框中使用CKeditor多次加载后无法编辑问题
    MVC之路随记3--Html辅助方法
  • 原文地址:https://www.cnblogs.com/fuhengheng/p/8038161.html
Copyright © 2020-2023  润新知