SSH连接操作交换机

Posted Joyce-Luo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SSH连接操作交换机相关的知识,希望对你有一定的参考价值。

        SSH 为 Secure Shell 的缩写,由 IETF 的网络小组(Network Working Group)所制定;SSH为建立在应用层和传输层基础上的安全协议。SSH是目前较可靠,专为远程登录会话和其他网络服务提供安全性的协议。利用SSH协议可以有效防止远程管理过程中的信息泄露问题。SSH最初是UNIX系统上的一个程序,后来又迅速扩展到其他操作平台。SSH在正确使用时可弥补网络中的漏洞。SSH客户端适用于多种平台。几乎所有UNIX平台—包括HP-UX、Linux、AIX、Solaris、Digital UNIX、Irix,以及其他平台,都可运行SSH。

        今天要和大家分享的是使用SSH连接操作交换机,完成Telnet交换机可以完成的事情。此次分享主要依赖mina-core-2.0.9.jar、slf4j-api-1.7.7.jar、expectit-core-0.8.1.jar和sshd-core-1.2.0.jar,相关资源大家可以上网找,在Apache官网、Github官网或者Maven上都能找到。把简单封装的Demo分享给大家!


package com.joyce.net.ssh;

import static net.sf.expectit.filter.Filters.removeColors;
import static net.sf.expectit.filter.Filters.removeNonPrintable;
import static net.sf.expectit.matcher.Matchers.regexp;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import net.sf.expectit.Expect;
import net.sf.expectit.ExpectBuilder;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ClientChannel;
import org.apache.sshd.client.future.ConnectFuture;
import org.apache.sshd.client.session.ClientSession;

import com.hupu.iman.util.StringUtil;

/**
 * SSH基类
 * @author Joyce.Luo
 * @date 2016-8-8 上午09:12:51
 * @version V3.0
 * @since Tomcat6.0,Jdk1.6
 * @copyright Copyright (c) 2016
 */
public class BaseSSH 
	private static final Logger logger = LogManager.getLogger(BaseSSH.class.getName());
	
	private SshClient client;
	private ClientSession session;
	private ClientChannel channel;
	private Expect expect;
	
	public String account;
	public String password;
	public String enablepassword;
	public String host;
	public int port = 22;
	public int timeout = 3000;
	
	public BaseSSH(String host) 
		super();
		this.host = host;
	

	public BaseSSH(String host, int port) 
		this.host = host;
		this.port = port;
	
	
	public BaseSSH(String host, int port, int timeout) 
		this.host = host;
		this.port = port;
		this.timeout = timeout;
	

	public String getAccount() 
		return account;
	

	public void setAccount(String account) 
		this.account = account;
	

	public String getPassword() 
		return password;
	

	public void setPassword(String password) 
		this.password = password;
	

	public String getEnablepassword() 
		return enablepassword;
	

	public void setEnablepassword(String enablepassword) 
		this.enablepassword = enablepassword;
	
	
	/**
	 * SSH连接
	 * @author Joyce.Luo
	 * @date 2016-8-8 上午10:13:16
	 * @version V3.0
	 * @since Tomcat6.0,Jdk1.6
	 * @copyright Copyright (c) 2016
	 */
	public boolean connect()
		client = SshClient.setUpDefaultClient();
		try 
			client.start();
			ConnectFuture cf = client.connect(account, host, port);
			if(cf.awaitUninterruptibly(timeout, TimeUnit.MILLISECONDS) && cf.isConnected())
				session = cf.getSession();
				session.addPasswordIdentity(password);
				return session.auth().awaitUninterruptibly(timeout, TimeUnit.MILLISECONDS);
			
		 catch (Exception e) 
			logger.error("SSH Connect Error --> ", e.getMessage(), e);
		
		return false;
	
	
	/**
	 * 获得Expect对象,该对用可以往SSH发送命令请求
	 * @author Joyce.Luo
	 * @date 2016-8-16 上午10:17:03
	 * @version V3.0
	 * @since Tomcat6.0,Jdk1.6
	 * @copyright Copyright (c) 2016
	 */
	public void getExpect()
		try 
			if (null == channel || channel.isClosed() || channel.isClosing()) 
				channel = session.createShellChannel();
				channel.open().awaitUninterruptibly();
			
			if (channel.isOpen()) 
				expect = new ExpectBuilder()
					.withOutput(channel.getInvertedIn())
					.withInputs(channel.getInvertedOut(), channel.getInvertedErr())
					.withInputFilters(removeColors(), removeNonPrintable())
					.withExceptionOnFailure()
					.build();
			
		 catch (Exception e) 
			logger.error("getExpect Error ---> ", e.getMessage(), e);
		
	
	
	/**
	 * 是否连接登录成功
	 * @return 是否登录成功;成功:true,失败:false
	 * @author Joyce.Luo
	 * @date 2016-8-16 上午10:48:53
	 * @version V3.0
	 * @since Tomcat6.0,Jdk1.6
	 * @copyright Copyright (c) 2016
	 */
	public boolean login()
		return true;
	
	
	/**
	 * 向终端发送命令
	 * @author Joyce.Luo
	 * @date 2016-8-16 上午10:48:53
	 * @version V3.0
	 * @throws IOException 
	 * @since Tomcat6.0,Jdk1.6
	 * @copyright Copyright (c) 2016
	 */
	public void write(String value) throws IOException 
		if (null == expect) 
			return;
		
		try 
			expect.sendLine(value);
		 catch (Exception e) 
			logger.error("发命令异常:write()", value, e.getMessage(), e);
		
	
	
	/**
	 * 向终端发送命令
	 * @author Joyce.Luo
	 * @date 2016-8-16 上午10:25:29
	 * @version V3.0
	 * @since Tomcat6.0,Jdk1.6
	 * @copyright Copyright (c) 2016
	 */
	public String write(String value, String sprompt) 
		if (null == expect) 
			return StringUtil.EMPTY;
		
		try 
			expect.sendLine(value);
			return expect.expect(regexp(sprompt)).getInput();
		 catch (Exception e) 
			logger.error("发命令异常:write()", value, e.getMessage(), e);
		
		return StringUtil.EMPTY;
	
	
	/**
	 * 读取
	 * @author Joyce.Luo
	 * @date 2016-8-16 上午10:48:53
	 * @version V3.0
	 * @since Tomcat6.0,Jdk1.6
	 * @copyright Copyright (c) 2016
	 */
	public String read() 
		try 
		 catch (Exception e) 
			logger.error("读取回显信息异常!", e.getMessage(), e);
		
		return null;
	
	
	/**
	 * 关闭连接
	 * @author Joyce.Luo
	 * @date 2016-8-8 上午10:30:10
	 * @version V3.0
	 * @since Tomcat6.0,Jdk1.6
	 * @copyright Copyright (c) 2016
	 */
	public void close()
		try 
			if (null != expect) 
				expect.close();
			
			if (channel.isOpen() || !channel.isClosing()) 
				channel.close(true);
			
			if (null != session && session.isOpen()) 
				session.close(true);
			
			if (null != client && client.isOpen()) 
				client.close(true);
			
		 catch (Exception e) 
			logger.error("Close Error ---> ", e.getMessage(), e);
		
	
	
	public static void main(String[] args) throws IOException 
		String host = "10.10.2.252", account = "cisco", password = "cisco", enpwd = "cisco";
		String cmd_one = "show arp", cmd_two = "show mac address-table";
		
		BaseSSH base = new BaseSSH(host);
		base.setAccount(account);
		base.setPassword(password);
		base.setEnablepassword(enpwd);
		base.connect();
		base.getExpect();
		base.login();
		
		System.out.println(base.write("terminal length 0", ">"));
		System.out.println(base.write(cmd_one, ">"));
		System.out.println(base.write(cmd_two, ">"));
		System.out.println(base.write("en", "word:"));
		System.out.println(base.write("cisco", "#"));
		System.out.println(base.write("show running-config", "#"));
		
		base.close();
	


为保证在一次连接中可以持续的通过SSH操作交换机,向交换机发送命令,借助了expectit,相关资料就自己去找吧,分享就到了,一贯宗旨:只为引导!


以上是关于SSH连接操作交换机的主要内容,如果未能解决你的问题,请参考以下文章

CRT连接远程交换机时出现协议错误,连接被SSH服务器关闭,怎么解决??

思科:路由器交换机 ssh远程连接

构建SSH连接远程操作Linux的Centos系统,并配置静态IP地址

securecrt通过ssh连接板子: 密钥交换失败,没有兼容的加密程序

paramiko连接并配置交换机

ssh跳板机与远程连接