2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Copyright (C) 2017 Amdocs
8 * ================================================================================
9 * Modifications Copyright (C) 2018 Ericsson
10 * =============================================================================
11 * Licensed under the Apache License, Version 2.0 (the "License");
12 * you may not use this file except in compliance with the License.
13 * You may obtain a copy of the License at
15 * http://www.apache.org/licenses/LICENSE-2.0
17 * Unless required by applicable law or agreed to in writing, software
18 * distributed under the License is distributed on an "AS IS" BASIS,
19 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20 * See the License for the specific language governing permissions and
21 * limitations under the License.
23 * ============LICENSE_END=========================================================
26 package org.onap.appc.ccadaptor;
28 import com.jcraft.jsch.Channel;
29 import com.jcraft.jsch.ChannelSftp;
30 import com.jcraft.jsch.ChannelShell;
31 import com.jcraft.jsch.ChannelSubsystem;
32 import com.jcraft.jsch.JSch;
33 import com.jcraft.jsch.JSchException;
34 import com.jcraft.jsch.Session;
35 import com.jcraft.jsch.SftpException;
36 import com.jcraft.jsch.UIKeyboardInteractive;
37 import com.jcraft.jsch.UserInfo;
38 import java.io.BufferedInputStream;
39 import java.io.BufferedReader;
40 import java.io.BufferedWriter;
41 import java.io.ByteArrayInputStream;
42 import java.io.ByteArrayOutputStream;
43 import java.io.DataInputStream;
44 import java.io.DataOutputStream;
46 import java.io.FileWriter;
47 import java.io.IOException;
48 import java.io.InputStream;
49 import java.io.InputStreamReader;
50 import java.io.OutputStream;
51 import java.io.RandomAccessFile;
52 import java.text.DateFormat;
53 import java.text.SimpleDateFormat;
54 import java.util.Calendar;
55 import java.util.Date;
56 import java.util.StringTokenizer;
57 import org.apache.commons.lang.StringUtils;
59 public class SshJcraftWrapper {
61 InputStream inputStream = null;
62 OutputStream outputStream = null;
63 DebugLog debugLog = new DebugLog();
64 private String debugLogFileName = "/tmp/sshJcraftWrapperDebug";
65 private TelnetListener listener = null;
66 private String routerLogFileName = null;
67 private String host = null;
68 private String RouterName = null;
69 private int BUFFER_SIZE = 512000;
70 char[] charBuffer = new char[BUFFER_SIZE];
71 private DataInputStream dis = null;
72 private BufferedReader reader = null;
73 private BufferedWriter out = null;
74 private File _tmpFile = null;
75 private JSch jsch = null;
76 private Session session = null;
77 private Channel channel = null;
78 private String tId = "";
79 private String aggregatedReceivedString = "";
80 private File extraDebugFile = new File("/tmp/sshJcraftWrapperDEBUG");
81 private String routerCmdType = "XML";
82 private String routerFileName = null;
83 private File jcraftReadSwConfigFileFromDisk = new File("/tmp/jcraftReadSwConfigFileFromDisk");
84 private String equipNameCode = null;
85 private String hostName = null;
86 private String userName = null;
87 private String passWord = null;
88 private StringBuffer charactersFromBufferFlush = new StringBuffer();
89 private Runtime runtime = Runtime.getRuntime();
90 private DebugLog dbLog = new DebugLog();
92 public SshJcraftWrapper() {
93 String fn = "SshJcraftWrapper.SshJcraftWrapper";
94 DebugLog.printRTAriDebug(fn, "SshJcraftWrapper has been instantated");
95 routerLogFileName = "/tmp/" + host;
98 public void connect(String hostname, String username, String password, String prompt, int timeOut)
100 String fn = "SshJcraftWrapper.connect";
102 DebugLog.printRTAriDebug(fn,
103 "Attempting to connect to " + hostname + " username=" + username + " prompt='"
104 + prompt + "' timeOut=" + timeOut);
105 DebugLog.printRTAriDebug(fn, "Trace A");
106 RouterName = hostname;
111 session = jsch.getSession(username, hostname, 22);
112 UserInfo ui = new MyUserInfo();
113 session.setPassword(password);
114 session.setUserInfo(ui);
115 session.connect(timeOut);
116 channel = session.openChannel("shell");
117 session.setServerAliveCountMax(
118 0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
119 ((ChannelShell) channel).setPtyType("vt102");
120 inputStream = channel.getInputStream();
121 dis = new DataInputStream(inputStream);
122 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
124 DebugLog.printRTAriDebug(fn, "Successfully connected.");
125 DebugLog.printRTAriDebug(fn, "Flushing input buffer");
127 receiveUntil(prompt, 3000, "No cmd was sent, just waiting");
128 } catch (Exception e) {
129 DebugLog.printRTAriDebug(fn, "Caught an Exception: Nothing to flush out.");
131 } catch (Exception e) {
132 DebugLog.printRTAriDebug(fn, "Caught an Exception. e=" + e);
133 throw new IOException(e.toString());
137 // User specifies the port number.
138 public void connect(String hostname, String username, String password, String prompt, int timeOut, int portNum)
140 String fn = "SshJcraftWrapper.connect";
141 DebugLog.printRTAriDebug(fn,
142 ":Attempting to connect to " + hostname + " username=" + username + " prompt='"
143 + prompt + "' timeOut=" + timeOut + " portNum=" + portNum);
144 RouterName = hostname;
148 RouterName = hostname;
151 session = jsch.getSession(username, hostname, portNum);
152 UserInfo ui = new MyUserInfo();
153 session.setPassword(password);
154 session.setUserInfo(ui);
155 session.setConfig("StrictHostKeyChecking", "no");
156 DebugLog.printRTAriDebug(fn, ":StrictHostKeyChecking set to 'no'");
158 session.connect(timeOut);
159 session.setServerAliveCountMax(
160 0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
161 channel = session.openChannel("shell");
162 ((ChannelShell) channel).setPtyType("vt102");
163 inputStream = channel.getInputStream();
164 dis = new DataInputStream(inputStream);
165 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
167 DebugLog.printRTAriDebug(fn, ":Successfully connected.");
168 DebugLog.printRTAriDebug(fn, ":Flushing input buffer");
170 if (prompt.equals("]]>]]>")) {
171 receiveUntil("]]>]]>", 10000, "No cmd was sent, just waiting");
173 receiveUntil(":~#", 5000, "No cmd was sent, just waiting");
175 } catch (Exception e) {
176 DebugLog.printRTAriDebug(fn, "Caught an Exception::: Nothing to flush out.");
178 } catch (Exception e) {
179 DebugLog.printRTAriDebug(fn, ":Caught an Exception. e=" + e);
180 dbLog.outputStackTrace(e);
182 throw new IOException(e.toString());
187 public String receiveUntil(String delimeters, int timeout, String cmdThatWasSent)
188 throws TimedOutException, IOException {
189 String fn = "SshJcraftWrapper.receiveUntil";
190 boolean match = false;
191 boolean cliPromptCmd = false;
192 StringBuffer sb2 = new StringBuffer();
193 StringBuffer sbReceive = new StringBuffer();
194 DebugLog.printRTAriDebug(fn,
195 "delimeters='" + delimeters + "' timeout=" + timeout + " cmdThatWasSent='" + cmdThatWasSent + "'");
196 appendToFile(debugLogFileName,
197 fn + " delimeters='" + delimeters + "' timeout=" + timeout + " cmdThatWasSent='" + cmdThatWasSent + "'\n");
198 String CmdThatWasSent = removeWhiteSpaceAndNewLineCharactersAroundString(cmdThatWasSent);
200 aggregatedReceivedString = "";
201 FileWriter fileWriter = null;
203 long deadline = new Date().getTime() + timeout;
205 session.setTimeout(timeout); // This is the socket timeout value.
207 if (new Date().getTime() > deadline) {
208 DebugLog.printRTAriDebug(fn,
209 "Throwing a TimedOutException: time in routine has exceed our deadline: RouterName:"
210 + RouterName + " CmdThatWasSent=" + CmdThatWasSent);
211 throw new TimedOutException("Timeout: time in routine has exceed our deadline");
215 } catch (java.lang.InterruptedException ee) {
216 Thread.currentThread().interrupt();
218 int len = reader.read(charBuffer, 0, BUFFER_SIZE);
219 appendToFile(debugLogFileName, fn + " After reader.read cmd: len=" + len + "\n");
221 DebugLog.printRTAriDebug(fn,
222 "Reader read " + len + " bytes. Looks like we timed out, router=" + RouterName);
223 throw new TimedOutException("Received a SocketTimeoutException router=" + RouterName);
226 if (cmdThatWasSent.indexOf("IOS_XR_uploadedSwConfigCmd") != -1) {
228 // This is a IOS XR sw config file. We will write it to the disk.
229 timeout = timeout * 2;
230 deadline = new Date().getTime() + timeout;
231 DebugLog.printRTAriDebug(fn, "IOS XR upload for software config: timeout=" + timeout);
232 StringTokenizer st = new StringTokenizer(cmdThatWasSent);
234 routerFileName = st.nextToken();
235 fileWriter = new FileWriter(routerFileName);
236 out = new BufferedWriter(fileWriter);
237 routerLogFileName = "/tmp/" + RouterName;
238 _tmpFile = new File(routerLogFileName);
239 DebugLog.printRTAriDebug(fn,
240 "Will write the swConfigFile to disk, routerFileName=" + routerFileName);
242 out.write(charBuffer, 0, len);
244 appendToFile(debugLogFileName, fn + " Wrote " + len + " bytes to the disk\n");
245 if (_tmpFile.exists()) {
246 appendToRouterFile(routerLogFileName, len);
248 match = checkIfReceivedStringMatchesDelimeter(len, "\nXML>");
257 appendToFile(debugLogFileName,
258 fn + " readCounts=" + readCounts + " Reader read " + len + " of data\n");
261 for (int i = 0; i < len; i++) {
263 if ((c != 7) && (c != 13) && (c != 0) && (c != 27)) {
264 sbReceive.append((char) charBuffer[i]);
265 sb2.append((char) charBuffer[i]);
268 appendToRouterFile("/tmp/" + RouterName, len);
269 if (listener != null) {
270 listener.receivedString(sb2.toString());
273 appendToFile(debugLogFileName, fn + " Trace 1\n");
274 match = checkIfReceivedStringMatchesDelimeter(delimeters, sb2.toString(), cmdThatWasSent);
275 appendToFile(debugLogFileName, fn + " Trace 2\n");
277 appendToFile(debugLogFileName, fn + " Match was true, breaking...\n");
283 } catch (JSchException e) {
284 DebugLog.printRTAriDebug(fn, "Caught an JSchException e=" + e.toString());
285 dbLog.outputStackTrace(e);
286 throw new TimedOutException(e.toString());
287 } catch (IOException ee) {
288 DebugLog.printRTAriDebug(fn, "Caught an IOException: ee=" + ee.toString());
289 dbLog.outputStackTrace(ee);
290 throw new TimedOutException(ee.toString());
293 if (fileWriter != null) {
296 } catch(IOException ex) {
297 DebugLog.printRTAriDebug(fn, "Failed to close fileWriter output stream: ex=" + ex);
300 String result = stripOffCmdFromRouterResponse(sbReceive.toString());
301 DebugLog.printRTAriDebug(fn, "Leaving method successfully");
305 public boolean checkIfReceivedStringMatchesDelimeter(String delimeters, String receivedString,
306 String cmdThatWasSent) {
307 // The delimeters are in a '|' seperated string. Return true on the first match.
308 String fn = "SshJcraftWrapper.checkIfReceivedStringMatchesDelimeter";
309 appendToFile(debugLogFileName,
310 fn + " Entered: delimeters='" + delimeters + " cmdThatWasSent='" + cmdThatWasSent + "' receivedString='"
311 + receivedString + "'\n");
312 StringTokenizer st = new StringTokenizer(delimeters, "|");
314 if ((delimeters.indexOf("#$") != -1) || (routerCmdType.equals("CLI"))) // This would be an IOS XR, CLI command.
316 int x = receivedString.lastIndexOf("#");
317 int y = receivedString.length() - 1;
318 appendToFile(debugLogFileName, fn + " IOS XR, CLI command\n");
319 if (extraDebugFile.exists()) {
320 appendToFile(debugLogFileName,
321 fn + " :::cmdThatWasSent='" + cmdThatWasSent + "' x=" + x + " y=" + y + "\n");
323 return (x != -1) && (y == x);
325 if (cmdThatWasSent.indexOf("show config") != -1) {
326 appendToFile(debugLogFileName, fn + "In the block for 'show config'\n");
327 while (st.hasMoreTokens()) {
328 String delimeter = st.nextToken();
329 // Make sure we don't get faked out by a response of " #".
331 // # signaling-local-address ipv6 FD00:F4D5:EA06:1::110:136:254
333 int x = receivedString.lastIndexOf(delimeter);
334 if ((receivedString.lastIndexOf(delimeter) != -1) && (receivedString.lastIndexOf(" #") != x - 1)) {
335 appendToFile(debugLogFileName, fn + "receivedString=\n'" + receivedString + "'\n");
336 appendToFile(debugLogFileName,
337 fn + "Returning true for the 'show config' command. We found our real delmeter. \n\n");
342 aggregatedReceivedString = aggregatedReceivedString + receivedString;
343 _appendToFile("/tmp/aggregatedReceivedString.debug", aggregatedReceivedString);
345 while (st.hasMoreTokens()) {
346 String delimeter = st.nextToken();
347 appendToFile(debugLogFileName, fn + " Looking for an delimeter of:'" + delimeter + "'\n");
348 appendToFile(debugLogFileName, fn + " receivedString='" + receivedString);
349 if (aggregatedReceivedString.indexOf(delimeter) != -1) {
350 DebugLog.printRTAriDebug(fn, "Found our delimeter, which was: '" + delimeter + "'");
351 aggregatedReceivedString = "";
359 public boolean checkIfReceivedStringMatchesDelimeter(int len, String delimeter) {
360 String fnName = "SshJcraftWrapper.checkIfReceivedStringMatchesDelimeter:::";
363 String str = StringUtils.EMPTY;
365 if (jcraftReadSwConfigFileFromDisk()) {
366 DebugLog.printAriDebug(fnName, "jcraftReadSwConfigFileFromDisk block");
367 File fileName = new File(routerFileName);
368 appendToFile(debugLogFileName,
369 fnName + " jcraftReadSwConfigFileFromDisk::: Will read the tail end of the file from the disk");
371 str = getLastFewLinesOfFile(fileName, 3);
372 } catch (IOException e) {
373 DebugLog.printAriDebug(fnName, "Caught an Exception, e=" + e);
374 dbLog.outputStackTrace(e);
378 // When looking at the end of the charBuffer, don't include any linefeeds or spaces. We only want to make the smallest string possible.
379 for (x = len - 1; x >= 0; x--) {
381 if (extraDebugFile.exists()) {
382 appendToFile(debugLogFileName, fnName + " x=" + x + " c=" + c + "\n");
384 if ((c != 10) && (c != 32)) // Not a line feed nor a space.
389 if ((x + 1 - 13) >= 0) {
390 str = new String(charBuffer, (x + 1 - 13), 13);
391 appendToFile(debugLogFileName, fnName + " str:'" + str + "'\n");
393 File fileName = new File(routerFileName);
394 appendToFile(debugLogFileName,
395 fnName + " Will read the tail end of the file from the disk, x=" + x + " len=" + len + " str::'"
396 + str + "' routerFileName='" + routerFileName + "'\n");
397 DebugLog.printAriDebug(fnName,
398 "Will read the tail end of the file from the disk, x=" + x + " len=" + len + " str::'" + str
399 + "' routerFileName='" + routerFileName + "'");
401 str = getLastFewLinesOfFile(fileName, 3);
402 } catch (IOException e) {
403 DebugLog.printAriDebug(fnName, "Caught an Exception, e=" + e);
404 dbLog.outputStackTrace(e);
410 if (str.indexOf(delimeter) != -1) {
411 DebugLog.printAriDebug(fnName, "str in break is:'" + str + "'" + " delimeter='" + delimeter + "'");
412 appendToFile(debugLogFileName,
413 fnName + " str in break is:'" + str + " delimeter='" + delimeter + "'" + "'\n");
416 appendToFile(debugLogFileName, fnName + " Returning false");
422 public void closeConnection() {
423 String fn = "SshJcraftWrapper.closeConnection";
424 DebugLog.printRTAriDebug(fn, "Executing the closeConnection....");
429 session.disconnect();
433 public void send(String cmd) throws IOException {
434 String fn = "SshJcraftWrapper.send";
435 OutputStream out = channel.getOutputStream();
436 DataOutputStream dos = getDataOutputStream(out);
437 if ((cmd.charAt(cmd.length() - 1) != '\n') && (cmd.charAt(cmd.length() - 1) != '\r')) {
440 int length = cmd.length();
443 int ncharsTotalSent = 0;
446 appendToFile(debugLogFileName, fn + ": Sending: '" + cmd);
447 DebugLog.printRTAriDebug(fn, "Length of cmd is:" + length); // 2,937,706
449 if (length > 600000) {
451 for (i = 0; i < length; i += nchars) {
452 String Cmd = cmd.substring(i, Math.min(length, i + nchars));
453 ncharsSent = Cmd.length();
454 ncharsTotalSent = ncharsTotalSent + Cmd.length();
455 DebugLog.printRTAriDebug(fn, "i=" + i + " Sending Cmd: ncharsSent=" + ncharsSent);
459 DebugLog.printRTAriDebug(fn, ":::i=" + i + " length=" + length);
460 if (ncharsSent < length) {
461 receiveUntilBufferFlush(ncharsSent, timeout, "buffer flush i=" + i);
463 DebugLog.printRTAriDebug(fn, "i=" + i + " No Waiting this time....");
466 } catch (Exception e) {
467 DebugLog.printRTAriDebug(fn, "Caught an Exception: Nothing to flush out.");
471 DebugLog.printRTAriDebug(fn, "Before executing the dos.writeBytes");
475 DebugLog.printRTAriDebug(fn, "Leaving method");
476 appendToFile(debugLogFileName, fn + ": Leaving method\n");
477 } catch (IOException e) {
478 DebugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e);
479 dbLog.outputStackTrace(e);
480 throw new IOException(e.toString());
485 public void sendChar(int v) throws IOException {
486 String fn = "SshJcraftWrapper.sendChar";
487 OutputStream out = channel.getOutputStream();
488 DataOutputStream dos = getDataOutputStream(out);
490 DebugLog.printRTAriDebug(fn, "Sending: '" + v + "'");
493 } catch (IOException e) {
494 DebugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e);
495 throw new IOException(e.toString());
499 public void send(byte[] b, int off, int len) throws IOException {
500 String fn = "SshJcraftWrapper.send:byte[]";
501 OutputStream out = channel.getOutputStream();
502 DataOutputStream dos = getDataOutputStream(out);
504 dos.write(b, off, len);
506 } catch (IOException e) {
507 DebugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e);
508 throw new IOException(e.toString());
512 public static class MyUserInfo implements UserInfo, UIKeyboardInteractive {
514 public String getPassword() {
518 public boolean promptYesNo(String str) {
522 public String getPassphrase() {
526 public boolean promptPassphrase(String message) {
530 public boolean promptPassword(String message) {
534 public void showMessage(String message) {
537 public String[] promptKeyboardInteractive(String destination,
546 public void addListener(TelnetListener listener) {
547 this.listener = listener;
550 public void appendToFile(String fileName, String dataToWrite) {
551 String fn = "SshJcraftWrapper.appendToFile";
554 // First check to see if a file 'fileName' exist, if it does
555 // write to it. If it does not exist, don't write to it.
556 File tmpFile = new File(fileName);
557 if (tmpFile.exists()) {
558 try(BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true))) {
559 out.write(getTheDate() + ": " + tId + ": " + dataToWrite);
562 } catch (IOException e) {
563 DebugLog.printRTAriDebug(fn, "Caught an IOException: e=" + e);
564 } catch (Exception e) {
565 DebugLog.printRTAriDebug(fn, "Caught an Exception: e=" + e);
569 public void _appendToFile(String fileName, String dataToWrite) {
570 String fn = "SshJcraftWrapper.appendToFile";
573 // First check to see if a file 'fileName' exist, if it does
574 // write to it. If it does not exist, don't write to it.
575 File tmpFile = new File(fileName);
576 if (tmpFile.exists()) {
577 try(BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true))) {
578 out.write(dataToWrite);
581 } catch (IOException e) {
582 DebugLog.printRTAriDebug(fn, "Caught an IOException: e=" + e);
583 } catch (Exception e) {
584 DebugLog.printRTAriDebug(fn, "Caught an Exception: e=" + e);
589 public String getTheDate() {
590 Calendar cal = Calendar.getInstance();
591 java.util.Date today = cal.getTime();
592 DateFormat df3 = new SimpleDateFormat("MM/dd/yyyy H:mm:ss ");
593 return (df3.format(today));
597 public void appendToRouterFile(String fileName, StringBuffer dataToWrite) {
598 String fnName = "SshJcraftWrapper.appendToRouterFile";
599 DebugLog.printRTAriDebug(fnName, "Entered.... ");
601 // First check to see if a file 'fileName' exist, if it does
602 // write to it. If it does not exist, don't write to it.
603 File tmpFile = new File(fileName);
605 if (tmpFile.exists()) {
606 try(BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true))) {
607 out.write(dataToWrite.toString());
611 } catch (IOException e) {
612 System.err.println("writeToFile() exception: " + e);
617 public void appendToRouterFile(String fileName, int len) {
619 // First check to see if a file 'fileName' exist, if it does
620 // write to it. If it does not exist, don't write to it.
621 File tmpFile = new File(fileName);
622 if (tmpFile.exists()) {
623 try(BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true))) {
624 out.write(charBuffer, 0, len);
627 } catch (IOException e) {
628 System.err.println("writeToFile() exception: " + e);
633 public String removeWhiteSpaceAndNewLineCharactersAroundString(String str) {
635 StringTokenizer strTok = new StringTokenizer(str, "\n");
636 StringBuffer sb = new StringBuffer();
638 while (strTok.hasMoreTokens()) {
639 String line = strTok.nextToken();
642 return (sb.toString().trim());
648 public String stripOffCmdFromRouterResponse(String routerResponse) {
649 // The session of SSH will echo the command sent to the router, in the router's response.
650 // Since all our commands are terminated by a '\n', strip off the first line
651 // of the response from the router. This first line contains the original command.
653 StringTokenizer rr = new StringTokenizer(routerResponse, "\n");
654 StringBuffer sb = new StringBuffer();
656 int numTokens = rr.countTokens();
658 rr.nextToken(); //Skip the first line.
659 while (rr.hasMoreTokens()) {
660 sb.append(rr.nextToken() + '\n');
663 return (sb.toString());
666 public void setRouterCommandType(String type) {
667 String fn = "SshJcraftWrapper.setRouterCommandType";
668 this.routerCmdType = type;
669 DebugLog.printRTAriDebug(fn, "Setting routerCmdType to a value of '" + type + "'");
672 public String getLastFewLinesOfFile(File file, int linesToRead) throws IOException {
673 String fn = "SshJcraftWrapper.getLastFewLinesOfFile";
675 try(RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r")) {
677 StringBuilder builder = new StringBuilder();
678 long length = file.length();
680 randomAccessFile.seek(length);
681 for (long seek = length; seek >= 0; --seek) {
682 randomAccessFile.seek(seek);
683 char c = (char) randomAccessFile.read();
686 builder = builder.reverse();
687 tail = builder.toString() + tail;
689 builder.setLength(0);
690 if (lines == linesToRead) {
696 if (!jcraftReadSwConfigFileFromDisk()) {
697 DebugLog.printRTAriDebug(fn, "tail='" + tail + "'");
699 appendToFile(debugLogFileName, "tail='" + tail + "'\n");
703 public boolean jcraftReadSwConfigFileFromDisk() {
704 if (jcraftReadSwConfigFileFromDisk.exists()) {
711 public String getEquipNameCode() {
712 return (equipNameCode);
716 public void setEquipNameCode(String equipNameCode) {
717 this.equipNameCode = equipNameCode;
720 public String getRouterName() {
724 // Routine does reads until it has read 'nchars' or times out.
725 public void receiveUntilBufferFlush(int ncharsSent, int timeout, String message)
726 throws TimedOutException, IOException {
727 String fn = "SshJcraftWrapper.receiveUntilBufferFlush";
728 DebugLog.printRTAriDebug(fn, "ncharsSent=" + ncharsSent + " timeout=" + timeout + " " + message);
729 int ncharsTotalReceived = 0;
731 charactersFromBufferFlush.setLength(0);
733 long deadline = new Date().getTime() + timeout;
736 session.setTimeout(timeout); // This is the socket timeout value.
738 if (new Date().getTime() > deadline) {
739 DebugLog.printRTAriDebug(fn,
740 "Throwing a TimedOutException: time in routine has exceed our deadline: ncharsSent="
741 + ncharsSent + " ncharsTotalReceived=" + ncharsTotalReceived);
742 throw new TimedOutException("Timeout: time in routine has exceed our deadline");
744 ncharsRead = reader.read(charBuffer, 0, BUFFER_SIZE);
745 if (listener != null) {
746 listener.receivedString(String.copyValueOf(charBuffer, 0, ncharsRead));
748 appendToRouterFile("/tmp/" + RouterName, ncharsRead);
749 ncharsTotalReceived = ncharsTotalReceived + ncharsRead;
750 if (ncharsTotalReceived >= ncharsSent) {
751 DebugLog.printRTAriDebug(fn,
752 "Received the correct number of characters, ncharsSent=" + ncharsSent + " ncharsTotalReceived="
753 + ncharsTotalReceived);
758 } catch (JSchException e) {
759 DebugLog.printRTAriDebug(fn, "Caught an JSchException e=" + e);
760 DebugLog.printRTAriDebug(fn,
761 "ncharsSent=" + ncharsSent + " ncharsTotalReceived=" + ncharsTotalReceived + " ncharsRead="
763 throw new TimedOutException(e.toString());
767 public String getHostName() {
771 public String getUserName() {
775 public String getPassWord() {
779 public void sftpPut(String sourcePath, String destDirectory) throws IOException {
780 // delegate to duplicate method
781 put(sourcePath, destDirectory);
785 public void SftpPut(String stringOfData, String fullPathDest) throws IOException {
786 String fn = "SshJcraftWrapper.Sftp";
788 Session sftpSession = jsch.getSession(userName, hostName, 22);
789 UserInfo ui = new MyUserInfo();
790 sftpSession.setPassword(passWord);
791 sftpSession.setUserInfo(ui);
792 sftpSession.connect(30 * 1000);
793 DebugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
794 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
795 DebugLog.printRTAriDebug(fn, "Connecting....");
797 InputStream is = new ByteArrayInputStream(stringOfData.getBytes());
798 DebugLog.printRTAriDebug(fn, "Sending stringOfData --> " + fullPathDest);
799 sftp.put(is, fullPathDest, ChannelSftp.OVERWRITE);
800 DebugLog.printRTAriDebug(fn, "Sent successfully");
801 sftpSession.disconnect();
802 } catch (Exception e) {
803 DebugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
804 throw new IOException(e.toString());
808 public String sftpGet(String fullFilePathName) throws IOException {
809 String fn = "SshJcraftWrapper.Sftp";
811 Session sftpSession = jsch.getSession(userName, hostName, 22);
812 UserInfo ui = new MyUserInfo();
813 sftpSession.setPassword(passWord);
814 sftpSession.setUserInfo(ui);
815 sftpSession.connect(30 * 1000);
816 DebugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
817 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
818 DebugLog.printRTAriDebug(fn, "Connecting....");
820 InputStream in = null;
821 in = sftp.get(fullFilePathName);
822 String sftpFileString = readInputStreamAsString(in);
823 DebugLog.printRTAriDebug(fn, "Retreived successfully");
824 sftpSession.disconnect();
825 return (sftpFileString);
826 } catch (Exception e) {
827 DebugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
828 throw new IOException(e.toString());
832 public static String readInputStreamAsString(InputStream in) throws IOException {
833 BufferedInputStream bis = new BufferedInputStream(in);
834 ByteArrayOutputStream buf = new ByteArrayOutputStream();
835 int result = bis.read();
836 while (result != -1) {
837 byte b = (byte) result;
841 return buf.toString();
845 public void logMemoryUsage() {
846 String fn = "SshJcraftWrapper.logMemoryUsage";
847 int mb = 1024 * 1024;
849 long maxMemoryAdvailable;
850 long memoryLetfOnHeap;
851 maxMemoryAdvailable = (runtime.maxMemory() / mb);
852 usedMemory = ((runtime.totalMemory() / mb) - (runtime.freeMemory() / mb));
853 memoryLetfOnHeap = maxMemoryAdvailable - usedMemory;
854 DebugLog.printAriDebug(fn,
855 "maxMemoryAdvailable=" + maxMemoryAdvailable + " usedMemory=" + usedMemory + " memoryLetfOnHeap="
859 // ----------------------------------------------------------------------------
860 // ----------------------------------------------------------------------------
861 // ----------------------------------------------------------------------------
862 // ----------------------------------------------------------------------------
865 // User specifies the port number, and the subsystem
866 public void connect(String hostname, String username, String password, String prompt, int timeOut, int portNum,
867 String subsystem) throws IOException {
868 String fn = "SshJcraftWrapper.connect";
870 DebugLog.printRTAriDebug(fn,
871 ":::Attempting to connect to " + hostname + " username=" + username + " prompt='"
872 + prompt + "' timeOut=" + timeOut + " portNum=" + portNum + " subsystem=" + subsystem);
873 RouterName = hostname;
876 session = jsch.getSession(username, hostname, portNum);
877 UserInfo ui = new MyUserInfo();
878 session.setPassword(password);
879 session.setUserInfo(ui);
880 session.setConfig("StrictHostKeyChecking", "no");
881 session.connect(timeOut);
882 session.setServerAliveCountMax(
883 0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
884 channel = session.openChannel("subsystem");
885 ((ChannelSubsystem) channel).setSubsystem(subsystem);
886 ((ChannelSubsystem) channel).setPty(true);
888 inputStream = channel.getInputStream();
889 dis = new DataInputStream(inputStream);
890 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
892 DebugLog.printRTAriDebug(fn, "Successfully connected.");
893 DebugLog.printRTAriDebug(fn, "Five second sleep....");
896 } catch (java.lang.InterruptedException ee) {
897 Thread.currentThread().interrupt();
899 } catch (Exception e) {
900 DebugLog.printRTAriDebug(fn, "Caught an Exception. e=" + e);
901 throw new IOException(e.toString());
905 public void connect(String hostName, String username, String password, int portNumber) throws IOException {
906 String fn = "SshJcraftWrapper.connect";
908 DebugLog.printRTAriDebug(fn,
909 "::Attempting to connect to " + hostName + " username=" + username + " portNumber=" + portNumber);
910 DebugLog.printRTAriDebug(fn, "Trace C");
911 RouterName = hostName;
912 this.hostName = hostName;
916 java.util.Properties config = new java.util.Properties();
917 config.put("StrictHostKeyChecking", "no");
918 session = jsch.getSession(username, hostName, 22);
919 UserInfo ui = new MyUserInfo();
920 session.setConfig(config);
921 session.setPassword(password);
922 session.setUserInfo(ui);
923 session.connect(30000);
924 channel = session.openChannel("shell");
925 session.setServerAliveCountMax(
926 0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
927 ((ChannelShell) channel).setPtyType("vt102");
928 inputStream = channel.getInputStream();
929 dis = new DataInputStream(inputStream);
930 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
932 DebugLog.printRTAriDebug(fn, "::Successfully connected.");
933 DebugLog.printRTAriDebug(fn, "::Flushing input buffer");
935 receiveUntil(":~#", 9000, "No cmd was sent, just waiting, but we can stop on a '~#'");
936 } catch (Exception e) {
937 DebugLog.printRTAriDebug(fn, "Caught an Exception::: Nothing to flush out.");
940 } catch (Exception e) {
941 DebugLog.printRTAriDebug(fn, "Caught an Exception. e=" + e);
942 throw new IOException(e.toString());
947 public void put(String sourcePath, String destDirectory) throws IOException {
948 String fn = "SshJcraftWrapper.sftp";
950 Session sftpSession = jsch.getSession(userName, hostName, 22);
951 UserInfo ui = new MyUserInfo();
952 sftpSession.setPassword(passWord);
953 sftpSession.setUserInfo(ui);
954 sftpSession.connect(30 * 1000);
955 DebugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
956 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
957 DebugLog.printRTAriDebug(fn, "Connecting....");
959 DebugLog.printRTAriDebug(fn, "Sending " + sourcePath + " --> " + destDirectory);
960 sftp.put(sourcePath, destDirectory, ChannelSftp.OVERWRITE);
961 DebugLog.printRTAriDebug(fn, "Sent successfully");
962 sftpSession.disconnect();
963 } catch (Exception e) {
964 DebugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
965 throw new IOException(e.toString());
969 public void put(InputStream is, String fullPathDest, String hostName, String userName, String passWord)
971 String fn = "SshJcraftWrapper.put";
972 Session sftpSession = null;
974 DebugLog.printRTAriDebug(fn, "userName=" + userName + " hostName=" + hostName);
976 java.util.Properties config = new java.util.Properties();
977 config.put("StrictHostKeyChecking", "no");
978 sftpSession = jsch.getSession(userName, hostName, 22);
979 UserInfo ui = new MyUserInfo();
980 sftpSession.setPassword(passWord);
981 sftpSession.setUserInfo(ui);
982 sftpSession.setConfig(config);
983 sftpSession.connect(30 * 1000);
984 DebugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
985 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
986 DebugLog.printRTAriDebug(fn, "Connecting....");
988 String oldFiles = fullPathDest + "*";
989 DebugLog.printRTAriDebug(fn, "Deleting old files --> " + oldFiles);
992 DebugLog.printRTAriDebug(fn, "Sending stringOfData --> " + fullPathDest);
993 } catch (SftpException sft) {
994 String exp = "No such file";
995 if (sft.getMessage() != null && sft.getMessage().contains(exp)) {
996 DebugLog.printRTAriDebug(fn, "No files found -- Continue");
998 DebugLog.printRTAriDebug(fn, "Exception while sftp.rm " + sft.getMessage());
1002 sftp.put(is, fullPathDest, ChannelSftp.OVERWRITE);
1003 DebugLog.printRTAriDebug(fn, "Sent successfully");
1004 } catch (Exception e) {
1005 DebugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
1006 throw new IOException(e.toString());
1008 if(sftpSession != null) {
1009 sftpSession.disconnect();
1015 public String get(String fullFilePathName, String hostName, String userName, String passWord) throws IOException {
1016 String fn = "SshJcraftWrapper.get";
1017 Session sftpSession = null;
1019 DebugLog.printRTAriDebug(fn, "userName=" + userName + " hostName=" + hostName);
1021 sftpSession = jsch.getSession(userName, hostName, 22);
1022 java.util.Properties config = new java.util.Properties();
1023 config.put("StrictHostKeyChecking", "no");
1024 UserInfo ui = new MyUserInfo();
1025 sftpSession.setPassword(passWord);
1026 sftpSession.setUserInfo(ui);
1027 sftpSession.setConfig(config);
1028 sftpSession.connect(30 * 1000);
1029 DebugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
1030 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
1031 DebugLog.printRTAriDebug(fn, "Connecting....");
1033 InputStream in = sftp.get(fullFilePathName);
1034 String sftpFileString = readInputStreamAsString(in);
1035 DebugLog.printRTAriDebug(fn, "Retreived successfully");
1036 return sftpFileString;
1037 } catch (Exception e) {
1038 DebugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
1039 throw new IOException(e.toString());
1041 if(sftpSession != null) {
1042 sftpSession.disconnect();
1047 public String send(String cmd, String delimiter) throws IOException {
1048 String fn = "SshJcraftWrapper.send";
1049 OutputStream out = channel.getOutputStream();
1050 DataOutputStream dos = getDataOutputStream(out);
1052 if ((cmd.charAt(cmd.length() - 1) != '\n') && (cmd.charAt(cmd.length() - 1) != '\r')) {
1055 int length = cmd.length();
1057 int nchars = 300000;
1058 int ncharsTotalSent = 0;
1061 DebugLog.printRTAriDebug(fn, "Length of cmd is:" + length); // 2,937,706
1063 if (length > 600000) {
1065 for (i = 0; i < length; i += nchars) {
1066 String Cmd = cmd.substring(i, Math.min(length, i + nchars));
1067 ncharsSent = Cmd.length();
1068 ncharsTotalSent = ncharsTotalSent + Cmd.length();
1069 DebugLog.printRTAriDebug(fn, "i=" + i + " Sending Cmd: ncharsSent=" + ncharsSent);
1070 dos.writeBytes(Cmd);
1073 DebugLog.printRTAriDebug(fn, ":::i=" + i + " length=" + length);
1074 if (ncharsSent < length) {
1075 receiveUntilBufferFlush(ncharsSent, timeout, "buffer flush i=" + i);
1077 DebugLog.printRTAriDebug(fn, "i=" + i + " No Waiting this time....");
1080 } catch (Exception e) {
1081 DebugLog.printRTAriDebug(fn, "Caught an Exception: Nothing to flush out.");
1085 DebugLog.printRTAriDebug(fn, "Before executing the dos.writeBytes");
1086 dos.writeBytes(cmd);
1089 // Now lets get the response.
1090 String response = receiveUntil(delimiter, 300000, cmd);
1091 DebugLog.printRTAriDebug(fn, "Leaving method");
1093 } catch (IOException e) {
1094 DebugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e);
1095 throw new IOException(e.toString());
1099 protected JSch getJSch() {
1103 protected DataOutputStream getDataOutputStream(OutputStream out) {
1104 return new DataOutputStream(out);
1107 protected void delay(int milliseconds) throws InterruptedException {