ssh登陆程序

ゞ 浴缸里的玫瑰 2022-05-22 08:57 322阅读 0赞
  1. <dependency>
  2. <groupId>ch.ethz.ganymed</groupId>
  3. <artifactId>ganymed-ssh2</artifactId>
  4. <version>build210</version>
  5. </dependency>
  6. package cn.tisson.ipran.gdcsgcf.driver.client;
  7. import ch.ethz.ssh2.Connection;
  8. import ch.ethz.ssh2.ServerHostKeyVerifier;
  9. import ch.ethz.ssh2.Session;
  10. import org.slf4j.Logger;
  11. import org.slf4j.LoggerFactory;
  12. import java.io.InputStreamReader;
  13. import java.io.OutputStreamWriter;
  14. public class SshCommandDriver extends CommandDriver{
  15. protected Logger log = LoggerFactory.getLogger(SshCommandDriver.class);
  16. private Connection conn = null;
  17. //SSH会话
  18. private Session sess = null;
  19. @Override
  20. public int open(String ip, int port, String loginPrompt, String userName,
  21. String pwdPrompt, String pwd, String commandPrompt,StringBuffer resultBuf) {
  22. if (isOpen) {
  23. log.debug("SSH 连接已经打开 ");
  24. return 0;
  25. }
  26. if (ip == null || ip.equals("") || port < -1) {
  27. log.error("需要ssh连接的ip 或端口不正确,请校验");
  28. resultBuf.append("需要ssh连接的ip 或端口不正确,请校验");
  29. return -101;
  30. }
  31. try {
  32. this.ip=ip;
  33. conn = new Connection(ip, port);
  34. conn.connect(new ServerHostKeyVerifier() {
  35. @Override
  36. public boolean verifyServerHostKey(String hostname, int port,
  37. String serverHostKeyAlgorithm, byte[] serverHostKey)
  38. throws Exception {
  39. return true;
  40. }
  41. }, 5000, 30000);
  42. } catch (Exception e) {
  43. resultBuf.append(e.getMessage());
  44. log.error(ip + " 打开SSH 连接出现异常,连接ip端口为" + port, e);
  45. close();
  46. return -102;
  47. }
  48. boolean isAuthentication = false;
  49. try {
  50. isAuthentication = conn.authenticateWithPassword(userName,pwd);
  51. } catch (Exception e) {
  52. resultBuf.append(e.getMessage());
  53. log.error(ip + " SSH授权出现异常,连接ip端口为"+ port, e);
  54. close();
  55. return -103;
  56. }
  57. if (!isAuthentication) {
  58. resultBuf.append(ip + " SSH授权失败,连接ip端口为" + port);
  59. log.error(ip + " SSH授权失败,连接ip端口为" + port);
  60. close();
  61. return -104;
  62. }
  63. try {
  64. sess = conn.openSession();
  65. sess.requestPTY("dumb", 132, 90, 0, 0, null);
  66. sess.startShell();
  67. } catch (Exception e) {
  68. resultBuf.append(e.getMessage());
  69. close();
  70. log.error(ip + "获取session出现异常,连接ip端口为" + port,e);
  71. return -105;
  72. }
  73. try {
  74. isr = new InputStreamReader(sess.getStdout(), charsetName);
  75. osr = new OutputStreamWriter(sess.getStdin(), charsetName);
  76. } catch (Exception e) {
  77. resultBuf.append(e.getMessage());
  78. close();
  79. log.error(ip + "获取输入/出流出现异常,连接ip端口为" + port,e);
  80. return -106;
  81. }
  82. try {
  83. String result=read(commandPrompt);
  84. resultBuf.append(result);
  85. if(this.isAutoAnswer){
  86. this.write("N");
  87. result=read(commandPrompt);
  88. resultBuf.append(result);
  89. }
  90. log.debug(result);
  91. this.commandPrompt=result.substring(result.lastIndexOf("\n")+1);
  92. } catch (Exception e) {
  93. resultBuf.append(e.getMessage());
  94. log.error("读取数据出现异常",e);
  95. }
  96. this.isOpen = true;
  97. return 0;
  98. }
  99. public void close(){
  100. super.close();
  101. try {
  102. if (sess != null) {
  103. sess.close();
  104. }
  105. if (conn != null) {
  106. conn.close();
  107. }
  108. } catch (Exception e) {
  109. log.error(ip+" closed sshClient exception", e);
  110. }finally{
  111. sess=null;
  112. conn = null;
  113. }
  114. }
  115. public static void main(String [] args) throws Exception{
  116. SshCommandDriver d=new SshCommandDriver();
  117. StringBuffer buf = new StringBuffer();
  118. int result=d.open("*.*.*.*", 22, ":", "admin", ":", "123@abc", ">",buf);
  119. System.out.println(result);
  120. if(result==0){
  121. d.write("display version");
  122. String temp=d.read();
  123. System.out.println(temp);
  124. }
  125. d.close();
  126. }
  127. }
  128. package cn.tisson.ipran.gdcsgcf.driver.client;
  129. import org.slf4j.Logger;
  130. import org.slf4j.LoggerFactory;
  131. import java.io.BufferedReader;
  132. import java.io.IOException;
  133. import java.io.InputStreamReader;
  134. import java.io.OutputStreamWriter;
  135. public abstract class CommandDriver implements ICommandDriver{
  136. protected Logger log = LoggerFactory.getLogger(CommandDriver.class);
  137. protected InputStreamReader isr;// 输入流
  138. protected OutputStreamWriter osr;// 输出流
  139. protected boolean isOpen = false;// 是否已经打开连接,防止打开多次
  140. protected String ip;
  141. protected String userName;
  142. protected String pwd;
  143. protected String commandPrompt;
  144. protected String loginPrompt;
  145. protected String pwdPrompt;
  146. protected int outTime=10000;
  147. protected String charsetName="iso8859-1";
  148. protected String neName;
  149. protected boolean isAutoAnswer = false;
  150. public boolean isAutoAnswer() {
  151. return isAutoAnswer;
  152. }
  153. @Override
  154. public abstract int open(String ip, int port, String loginPrompt, String userName,
  155. String pwdPrompt, String pwd, String commandPrompt,StringBuffer resultBuf);
  156. @Override
  157. public void close() {
  158. this.isOpen = false;
  159. try {
  160. if (isr != null) {
  161. isr.close();
  162. }
  163. } catch (IOException e) {
  164. log.error(this.ip + "closed inputStreamRead failed", e);
  165. } finally {
  166. isr = null;
  167. }
  168. try {
  169. if (osr != null) {
  170. osr.close();
  171. }
  172. } catch (IOException e) {
  173. log.error(this.ip + "closed outputStramRead failed", e);
  174. } finally {
  175. osr = null;
  176. }
  177. }
  178. @Override
  179. public void write(String command) throws Exception {
  180. log.debug(ip+" 发送的命令为"+command);
  181. clearReadBuffer();
  182. osr.write(command+ getTerminalSendPostfix());
  183. osr.flush();
  184. }
  185. @Override
  186. public void write(String command,String terminalSendPostfix) throws Exception {
  187. log.debug(ip+" 发送的命令为"+command);
  188. clearReadBuffer();
  189. osr.write(command+ terminalSendPostfix);
  190. osr.flush();
  191. }
  192. @Override
  193. public String read() throws Exception {
  194. return this.read(new StringResponseEndChecker() {
  195. @Override
  196. public boolean isResponseEnd(StringBuffer data) {
  197. if (data!=null&&data.toString().trim().endsWith(commandPrompt)) {
  198. return true;
  199. }
  200. return false;
  201. }
  202. }, this.outTime);
  203. }
  204. @Override
  205. public String read(String terminator) throws Exception {
  206. return this.read(terminator, this.outTime);
  207. }
  208. @Override
  209. public String read(final String terminator,int timeout) throws Exception {
  210. return this.read(new StringResponseEndChecker() {
  211. @Override
  212. public boolean isResponseEnd(StringBuffer data) {
  213. if (data!=null&&data.toString().trim().endsWith(terminator)) {
  214. return true;
  215. }else if(data!=null&&data.toString().trim().endsWith("[Y/N]:")){
  216. isAutoAnswer=true;
  217. return true;
  218. }
  219. return false;
  220. }
  221. }, timeout);
  222. }
  223. public boolean isOpen(){
  224. return this.isOpen;
  225. }
  226. @Override
  227. public void setCharsetName(String charsetName) {
  228. if(charsetName!=null)
  229. this.charsetName=charsetName;
  230. }
  231. @Override
  232. public String getUsername() {
  233. return this.userName;
  234. }
  235. @Override
  236. public String getPassword() {
  237. return this.pwd;
  238. }
  239. @Override
  240. public String getNeName() {
  241. return this.neName;
  242. }
  243. /** * 清空接受 */ private void clearReadBuffer() {
  244. BufferedReader br = null;
  245. try {
  246. if (isr!=null) {
  247. br = new BufferedReader(isr);
  248. while (br.ready()) {
  249. br.read();
  250. }
  251. }
  252. } catch (Exception e) {
  253. log.error("清空read buffer 出现异常", e);
  254. }
  255. }
  256. /** * 命令发送结尾符 * @return */ protected String getTerminalSendPostfix() {
  257. return "\r\n";
  258. }
  259. @Override
  260. public String read(StringResponseEndChecker checker, long timeout) throws IOException{
  261. long time = System.currentTimeMillis() + timeout;
  262. StringBuffer sb = new StringBuffer();
  263. BufferedReader br = null;
  264. boolean readed = false;
  265. boolean isClose=true;//用来判断网络是否正常 true不正常 false正常
  266. br = new BufferedReader(isr);
  267. while (System.currentTimeMillis() < time) {
  268. try {
  269. if (br.ready()) {
  270. int brchar = br.read();
  271. if((32<=brchar&&brchar<=127)||brchar==10||brchar==13) {
  272. sb.append((char) brchar);
  273. }
  274. readed = true;
  275. isClose=false;
  276. } else {
  277. if ((checker != null) && (readed == true)) {
  278. readed = false;
  279. if (checker.isResponseEnd(sb))
  280. break;
  281. }
  282. Thread.sleep(150);
  283. }
  284. } catch (InterruptedException e) {
  285. log.error("读取数据出现异常",e);
  286. }
  287. }
  288. if(isClose&&sb.length()==0){
  289. this.isOpen=false;
  290. throw new IOException("网络已经中断.....");
  291. }
  292. String temp=sb.toString();
  293. // temp=temp.substring(temp.indexOf("\n")+1);//删除命令回显
  294. log.debug(ip+" 接受到的数据为"+temp);
  295. return temp;
  296. }
  297. @Override
  298. public void setOutTime(int outTime) {
  299. if(outTime>5000)
  300. this.outTime = outTime;
  301. }
  302. @Override
  303. public int getOutTime() {
  304. return outTime;
  305. }
  306. }
  307. package cn.tisson.ipran.gdcsgcf.driver.client;
  308. public interface ICommandDriver {
  309. public boolean isAutoAnswer();
  310. /** * 打开连接 * @param ip telnet ip地址 如127.0.0.1 * @param port telnet 端口号 如23 * @param loginPrompt 用户名输入提示符 如userName: * @param userName 用户名 如who * @param pwdPrompt 输入密码提示符 如Password: * @param pwd 密码 如who * @param commandPrompt 登陆成功提示符 如> * @return 0成功,-1数据可是不对 -2没有接到输入用户名提示符 -3没有接收到密码提示符 -4没有接到登陆成功提示符 -5出现异常 */ public abstract int open(String ip, int port, String loginPrompt,String userName, String pwdPrompt, String pwd, String commandPrompt,StringBuffer resultBuf);
  311. /** * 关闭连接 */ public void close();
  312. /** * 获取登录用户名 * @return */ public String getUsername();
  313. /** * 获取登录密码 * @return */ public String getPassword();
  314. /** * 获取网元名称 * @return */ public String getNeName();
  315. /** * 发送命令 * @param command * @throws Exception */ public void write(String command) throws Exception;
  316. /** * 发送命令 * @param command * @param terminalSendPostfix \r\n \r * @throws Exception */ public void write(String command,String terminalSendPostfix) throws Exception;
  317. /** * 接受命令结果 * @return * @throws Exception */ public String read() throws Exception;
  318. /** * 接受命令结果直到结束 * @param terminator * @return * @throws Exception */ public String read(String terminator)throws Exception;
  319. /** * 设置字符集 * @param charsetName */ public void setCharsetName(String charsetName);
  320. /** * @param terminator * @param timeout * @return * @throws Exception */ String read(String terminator, int timeout) throws Exception;
  321. /** * 返回连接状态 主要是主动关闭 */ public boolean isOpen();
  322. /** * 设置默认超时时间单位毫秒 * @param outTime */ public void setOutTime(int outTime);
  323. public int getOutTime();
  324. String read(StringResponseEndChecker checker, long timeout) throws Exception;
  325. }

发表评论

表情:
评论列表 (有 0 条评论,322人围观)

还没有评论,来说两句吧...

相关阅读

    相关 ssh 别名登陆

    此方法配合ssh 免密码登录 密钥登录可以快速登录服务器 通常我们在 Termianl 下用 ssh 链接远程主机的时候,每次都需要输入一长串的用户名加主机地址,是不是觉得很

    相关 配置ssh登陆

    \生成ssh免登陆密钥 \进入到我的home目录 cd ~/.ssh   ssh-keygen -t rsa (四个回车) 执行完这个命令后,会生成两个文件id\_r

    相关 远程登陆ssh

    远程登陆ssh 以下操作需要一个客户端和服务端两个虚拟机来完成。 打开两个虚拟机,可输入“nm-connectiong-editor”来修改ip 示例: 服务端

    相关 ssh 无密码登陆

    本文引用自:[Linux大神博客的博文][Linux]  SSH无密码登录:只需两个简单步骤 (Linux) 如果你管理一台Linux服务器,那么你就会知道每次SSH登

    相关 ssh登陆

    之前在windows下有putty,xshell,mobaXterm 工具可以选择。 现在用mac,暂时没怎么找到好到软件,直接用ssh好了。 ssh -p 22 user