当前位置:   article > 正文

SSH连接操作交换机_net.sf.expectit.expect

net.sf.expectit.expect

        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分享给大家!


  1. package com.joyce.net.ssh;
  2. import static net.sf.expectit.filter.Filters.removeColors;
  3. import static net.sf.expectit.filter.Filters.removeNonPrintable;
  4. import static net.sf.expectit.matcher.Matchers.regexp;
  5. import java.io.IOException;
  6. import java.util.concurrent.TimeUnit;
  7. import net.sf.expectit.Expect;
  8. import net.sf.expectit.ExpectBuilder;
  9. import org.apache.logging.log4j.LogManager;
  10. import org.apache.logging.log4j.Logger;
  11. import org.apache.sshd.client.SshClient;
  12. import org.apache.sshd.client.channel.ClientChannel;
  13. import org.apache.sshd.client.future.ConnectFuture;
  14. import org.apache.sshd.client.session.ClientSession;
  15. import com.hupu.iman.util.StringUtil;
  16. /**
  17. * SSH基类
  18. * @author Joyce.Luo
  19. * @date 2016-8-8 上午09:12:51
  20. * @version V3.0
  21. * @since Tomcat6.0,Jdk1.6
  22. * @copyright Copyright (c) 2016
  23. */
  24. public class BaseSSH {
  25. private static final Logger logger = LogManager.getLogger(BaseSSH.class.getName());
  26. private SshClient client;
  27. private ClientSession session;
  28. private ClientChannel channel;
  29. private Expect expect;
  30. public String account;
  31. public String password;
  32. public String enablepassword;
  33. public String host;
  34. public int port = 22;
  35. public int timeout = 3000;
  36. public BaseSSH(String host) {
  37. super();
  38. this.host = host;
  39. }
  40. public BaseSSH(String host, int port) {
  41. this.host = host;
  42. this.port = port;
  43. }
  44. public BaseSSH(String host, int port, int timeout) {
  45. this.host = host;
  46. this.port = port;
  47. this.timeout = timeout;
  48. }
  49. public String getAccount() {
  50. return account;
  51. }
  52. public void setAccount(String account) {
  53. this.account = account;
  54. }
  55. public String getPassword() {
  56. return password;
  57. }
  58. public void setPassword(String password) {
  59. this.password = password;
  60. }
  61. public String getEnablepassword() {
  62. return enablepassword;
  63. }
  64. public void setEnablepassword(String enablepassword) {
  65. this.enablepassword = enablepassword;
  66. }
  67. /**
  68. * SSH连接
  69. * @author Joyce.Luo
  70. * @date 2016-8-8 上午10:13:16
  71. * @version V3.0
  72. * @since Tomcat6.0,Jdk1.6
  73. * @copyright Copyright (c) 2016
  74. */
  75. public boolean connect(){
  76. client = SshClient.setUpDefaultClient();
  77. try {
  78. client.start();
  79. ConnectFuture cf = client.connect(account, host, port);
  80. if(cf.awaitUninterruptibly(timeout, TimeUnit.MILLISECONDS) && cf.isConnected()){
  81. session = cf.getSession();
  82. session.addPasswordIdentity(password);
  83. return session.auth().awaitUninterruptibly(timeout, TimeUnit.MILLISECONDS);
  84. }
  85. } catch (Exception e) {
  86. logger.error("SSH Connect Error --> {}", e.getMessage(), e);
  87. }
  88. return false;
  89. }
  90. /**
  91. * 获得Expect对象,该对用可以往SSH发送命令请求
  92. * @author Joyce.Luo
  93. * @date 2016-8-16 上午10:17:03
  94. * @version V3.0
  95. * @since Tomcat6.0,Jdk1.6
  96. * @copyright Copyright (c) 2016
  97. */
  98. public void getExpect(){
  99. try {
  100. if (null == channel || channel.isClosed() || channel.isClosing()) {
  101. channel = session.createShellChannel();
  102. channel.open().awaitUninterruptibly();
  103. }
  104. if (channel.isOpen()) {
  105. expect = new ExpectBuilder()
  106. .withOutput(channel.getInvertedIn())
  107. .withInputs(channel.getInvertedOut(), channel.getInvertedErr())
  108. .withInputFilters(removeColors(), removeNonPrintable())
  109. .withExceptionOnFailure()
  110. .build();
  111. }
  112. } catch (Exception e) {
  113. logger.error("getExpect Error ---> {}", e.getMessage(), e);
  114. }
  115. }
  116. /**
  117. * 是否连接登录成功
  118. * @return 是否登录成功;成功:true,失败:false
  119. * @author Joyce.Luo
  120. * @date 2016-8-16 上午10:48:53
  121. * @version V3.0
  122. * @since Tomcat6.0,Jdk1.6
  123. * @copyright Copyright (c) 2016
  124. */
  125. public boolean login(){
  126. return true;
  127. }
  128. /**
  129. * 向终端发送命令
  130. * @author Joyce.Luo
  131. * @date 2016-8-16 上午10:48:53
  132. * @version V3.0
  133. * @throws IOException
  134. * @since Tomcat6.0,Jdk1.6
  135. * @copyright Copyright (c) 2016
  136. */
  137. public void write(String value) throws IOException {
  138. if (null == expect) {
  139. return;
  140. }
  141. try {
  142. expect.sendLine(value);
  143. } catch (Exception e) {
  144. logger.error("发命令异常:write({}){}", value, e.getMessage(), e);
  145. }
  146. }
  147. /**
  148. * 向终端发送命令
  149. * @author Joyce.Luo
  150. * @date 2016-8-16 上午10:25:29
  151. * @version V3.0
  152. * @since Tomcat6.0,Jdk1.6
  153. * @copyright Copyright (c) 2016
  154. */
  155. public String write(String value, String sprompt) {
  156. if (null == expect) {
  157. return StringUtil.EMPTY;
  158. }
  159. try {
  160. expect.sendLine(value);
  161. return expect.expect(regexp(sprompt)).getInput();
  162. } catch (Exception e) {
  163. logger.error("发命令异常:write({}){}", value, e.getMessage(), e);
  164. }
  165. return StringUtil.EMPTY;
  166. }
  167. /**
  168. * 读取
  169. * @author Joyce.Luo
  170. * @date 2016-8-16 上午10:48:53
  171. * @version V3.0
  172. * @since Tomcat6.0,Jdk1.6
  173. * @copyright Copyright (c) 2016
  174. */
  175. public String read() {
  176. try {
  177. } catch (Exception e) {
  178. logger.error("读取回显信息异常!{}", e.getMessage(), e);
  179. }
  180. return null;
  181. }
  182. /**
  183. * 关闭连接
  184. * @author Joyce.Luo
  185. * @date 2016-8-8 上午10:30:10
  186. * @version V3.0
  187. * @since Tomcat6.0,Jdk1.6
  188. * @copyright Copyright (c) 2016
  189. */
  190. public void close(){
  191. try {
  192. if (null != expect) {
  193. expect.close();
  194. }
  195. if (channel.isOpen() || !channel.isClosing()) {
  196. channel.close(true);
  197. }
  198. if (null != session && session.isOpen()) {
  199. session.close(true);
  200. }
  201. if (null != client && client.isOpen()) {
  202. client.close(true);
  203. }
  204. } catch (Exception e) {
  205. logger.error("Close Error ---> {}", e.getMessage(), e);
  206. }
  207. }
  208. public static void main(String[] args) throws IOException {
  209. String host = "10.10.2.252", account = "cisco", password = "cisco", enpwd = "cisco";
  210. String cmd_one = "show arp", cmd_two = "show mac address-table";
  211. BaseSSH base = new BaseSSH(host);
  212. base.setAccount(account);
  213. base.setPassword(password);
  214. base.setEnablepassword(enpwd);
  215. base.connect();
  216. base.getExpect();
  217. base.login();
  218. System.out.println(base.write("terminal length 0", ">"));
  219. System.out.println(base.write(cmd_one, ">"));
  220. System.out.println(base.write(cmd_two, ">"));
  221. System.out.println(base.write("en", "word:"));
  222. System.out.println(base.write("cisco", "#"));
  223. System.out.println(base.write("show running-config", "#"));
  224. base.close();
  225. }
  226. }

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


声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/863320
推荐阅读
相关标签
  

闽ICP备14008679号