2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Copyright (C) 2017 Amdocs
8 * =============================================================================
9 * Licensed under the Apache License, Version 2.0 (the "License");
10 * you may not use this file except in compliance with the License.
11 * You may obtain a copy of the License at
13 * http://www.apache.org/licenses/LICENSE-2.0
15 * Unless required by applicable law or agreed to in writing, software
16 * distributed under the License is distributed on an "AS IS" BASIS,
17 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 * See the License for the specific language governing permissions and
19 * limitations under the License.
21 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 * ============LICENSE_END=========================================================
25 package org.onap.appc.ccadaptor;
27 import com.jcraft.jsch.Channel;
28 import com.jcraft.jsch.ChannelSftp;
29 import com.jcraft.jsch.ChannelShell;
30 import com.jcraft.jsch.ChannelSubsystem;
31 import com.jcraft.jsch.JSch;
32 import com.jcraft.jsch.JSchException;
33 import com.jcraft.jsch.Session;
34 import com.jcraft.jsch.SftpException;
35 import com.jcraft.jsch.UIKeyboardInteractive;
36 import com.jcraft.jsch.UserInfo;
37 import java.io.BufferedInputStream;
38 import java.io.BufferedReader;
39 import java.io.BufferedWriter;
40 import java.io.ByteArrayInputStream;
41 import java.io.ByteArrayOutputStream;
42 import java.io.DataInputStream;
43 import java.io.DataOutputStream;
45 import java.io.FileNotFoundException;
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 int BUFFER_SIZE = 4000000;
72 private DataInputStream dis = null;
73 private BufferedReader reader = null;
74 private BufferedWriter out = null;
75 private File _tmpFile = null;
76 private JSch jsch = null;
77 private Session session = null;
78 private Channel channel = null;
79 private String tId = "";
80 private String aggregatedReceivedString = "";
81 private File extraDebugFile = new File("/tmp/sshJcraftWrapperDEBUG");
82 private String routerCmdType = "XML";
83 private String routerFileName = null;
84 private File jcraftReadSwConfigFileFromDisk = new File("/tmp/jcraftReadSwConfigFileFromDisk");
85 private String equipNameCode = null;
86 private String hostName = null;
87 private String userName = null;
88 private String passWord = null;
89 private StringBuffer charactersFromBufferFlush = new StringBuffer();
90 private Runtime runtime = Runtime.getRuntime();
91 private DebugLog dbLog = new DebugLog();
93 public void SshJcraftWrapper() {
94 String fn = "SshJcraftWrapper.SshJcraftWrapper";
95 debugLog.printRTAriDebug(fn, "SshJcraftWrapper has been instantated");
96 routerLogFileName = "/tmp/" + host;
100 public void connect(String hostname, String username, String password, String prompt, int timeOut)
102 String fn = "SshJcraftWrapper.connect";
104 debugLog.printRTAriDebug(fn,
105 "Attempting to connect to " + hostname + " username=" + username + " password=" + password + " prompt='"
106 + prompt + "' timeOut=" + timeOut);
107 debugLog.printRTAriDebug(fn, "Trace A");
108 RouterName = hostname;
113 session = jsch.getSession(username, hostname, 22);
114 UserInfo ui = new MyUserInfo();
115 session.setPassword(password);
116 session.setUserInfo(ui);
117 session.connect(timeOut);
118 channel = session.openChannel("shell");
119 session.setServerAliveCountMax(
120 0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
121 ((ChannelShell) channel).setPtyType("vt102");
122 inputStream = channel.getInputStream();
123 dis = new DataInputStream(inputStream);
124 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
126 debugLog.printRTAriDebug(fn, "Successfully connected.");
127 debugLog.printRTAriDebug(fn, "Flushing input buffer");
129 receiveUntil(prompt, 3000, "No cmd was sent, just waiting");
130 } catch (Exception e) {
131 debugLog.printRTAriDebug(fn, "Caught an Exception: Nothing to flush out.");
133 } catch (Exception e) {
134 debugLog.printRTAriDebug(fn, "Caught an Exception. e=" + e);
135 // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostname +" "+e);
136 throw new IOException(e.toString());
140 // User specifies the port number.
141 public void connect(String hostname, String username, String password, String prompt, int timeOut, int portNum)
143 String fn = "SshJcraftWrapper.connect";
144 debugLog.printRTAriDebug(fn,
145 ":Attempting to connect to " + hostname + " username=" + username + " password=" + password + " prompt='"
146 + prompt + "' timeOut=" + timeOut + " portNum=" + portNum);
147 RouterName = hostname;
151 RouterName = hostname;
154 session = jsch.getSession(username, hostname, portNum);
155 UserInfo ui = new MyUserInfo();
156 session.setPassword(password);
157 session.setUserInfo(ui);
158 session.setConfig("StrictHostKeyChecking", "no");
159 debugLog.printRTAriDebug(fn, ":StrictHostKeyChecking set to 'no'");
161 session.connect(timeOut);
162 session.setServerAliveCountMax(
163 0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
164 channel = session.openChannel("shell");
165 ((ChannelShell) channel).setPtyType("vt102");
166 inputStream = channel.getInputStream();
167 dis = new DataInputStream(inputStream);
168 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
170 debugLog.printRTAriDebug(fn, ":Successfully connected.");
171 debugLog.printRTAriDebug(fn, ":Flushing input buffer");
173 if (prompt.equals("]]>]]>")) {
174 receiveUntil("]]>]]>", 10000, "No cmd was sent, just waiting");
176 receiveUntil(":~#", 5000, "No cmd was sent, just waiting");
178 } catch (Exception e) {
179 debugLog.printRTAriDebug(fn, "Caught an Exception::: Nothing to flush out.");
181 } catch (Exception e) {
182 debugLog.printRTAriDebug(fn, ":Caught an Exception. e=" + e);
183 dbLog.outputStackTrace(e);
185 // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostname +" "+e);
186 throw new IOException(e.toString());
191 public String receiveUntil(String delimeters, int timeout, String cmdThatWasSent)
192 throws TimedOutException, IOException {
193 String fn = "SshJcraftWrapper.receiveUntil";
194 boolean match = false;
195 boolean cliPromptCmd = false;
196 StringBuffer sb2 = new StringBuffer();
197 StringBuffer sbReceive = new StringBuffer();
198 debugLog.printRTAriDebug(fn,
199 "delimeters='" + delimeters + "' timeout=" + timeout + " cmdThatWasSent='" + cmdThatWasSent + "'");
200 appendToFile(debugLogFileName,
201 fn + " delimeters='" + delimeters + "' timeout=" + timeout + " cmdThatWasSent='" + cmdThatWasSent + "'\n");
202 String CmdThatWasSent = removeWhiteSpaceAndNewLineCharactersAroundString(cmdThatWasSent);
204 aggregatedReceivedString = "";
206 long deadline = new Date().getTime() + timeout;
208 session.setTimeout(timeout); // This is the socket timeout value.
210 if (new Date().getTime() > deadline) {
211 debugLog.printRTAriDebug(fn,
212 "Throwing a TimedOutException: time in routine has exceed our deadline: RouterName:"
213 + RouterName + " CmdThatWasSent=" + CmdThatWasSent);
214 throw new TimedOutException("Timeout: time in routine has exceed our deadline");
218 } catch (java.lang.InterruptedException ee) {
219 boolean ignore = true;
221 int len = reader.read(charBuffer, 0, BUFFER_SIZE);
222 appendToFile(debugLogFileName, fn + " After reader.read cmd: len=" + len + "\n");
224 debugLog.printRTAriDebug(fn,
225 "Reader read " + len + " bytes. Looks like we timed out, router=" + RouterName);
226 throw new TimedOutException("Received a SocketTimeoutException router=" + RouterName);
229 if (cmdThatWasSent.indexOf("IOS_XR_uploadedSwConfigCmd") != -1) {
231 // This is a IOS XR sw config file. We will write it to the disk.
232 timeout = timeout * 2;
233 deadline = new Date().getTime() + timeout;
234 debugLog.printRTAriDebug(fn, "IOS XR upload for software config: timeout=" + timeout);
235 StringTokenizer st = new StringTokenizer(cmdThatWasSent);
237 routerFileName = st.nextToken();
238 out = new BufferedWriter(new FileWriter(routerFileName));
239 routerLogFileName = "/tmp/" + RouterName;
240 _tmpFile = new File(routerLogFileName);
241 debugLog.printRTAriDebug(fn,
242 "Will write the swConfigFile to disk, routerFileName=" + routerFileName);
245 out.write(charBuffer, 0, len);
247 appendToFile(debugLogFileName, fn + " Wrote " + len + " bytes to the disk\n");
248 if (_tmpFile.exists()) {
249 appendToRouterFile(routerLogFileName, len);
251 match = checkIfReceivedStringMatchesDelimeter(len, "\nXML>");
260 appendToFile(debugLogFileName,
261 fn + " readCounts=" + readCounts + " Reader read " + len + " of data\n");
264 for (int i = 0; i < len; i++) {
266 if ((c != 7) && (c != 13) && (c != 0) && (c != 27)) {
267 sbReceive.append((char) charBuffer[i]);
268 sb2.append((char) charBuffer[i]);
271 appendToRouterFile("/tmp/" + RouterName, len);
272 if (listener != null) {
273 listener.receivedString(sb2.toString());
276 appendToFile(debugLogFileName, fn + " Trace 1\n");
277 match = checkIfReceivedStringMatchesDelimeter(delimeters, sb2.toString(), cmdThatWasSent);
278 appendToFile(debugLogFileName, fn + " Trace 2\n");
280 appendToFile(debugLogFileName, fn + " Match was true, breaking...\n");
285 debugLog.printRTAriDebug(fn, "cliPromptCmd, Trace 2");
287 for (int i = 0; i < len; i++) {
288 sbReceive.append((char) charBuffer[i]);
289 sb2.append((char) charBuffer[i]);
291 appendToRouterFile("/tmp/" + RouterName, sb2);
292 if (listener != null) {
293 listener.receivedString(sb2.toString());
295 debugLog.printRTAriDebug(fn, "sb2='" + sb2.toString() + "' delimeters='" + delimeters + "'");
296 if (sb2.toString().indexOf("\nariPrompt>") != -1) {
297 debugLog.printRTAriDebug(fn, "Found our prompt");
303 } catch (JSchException e) {
304 debugLog.printRTAriDebug(fn, "Caught an JSchException e=" + e.toString());
305 dbLog.outputStackTrace(e);
306 throw new TimedOutException(e.toString());
307 } catch (IOException ee) {
308 debugLog.printRTAriDebug(fn, "Caught an IOException: ee=" + ee.toString());
309 dbLog.outputStackTrace(ee);
310 throw new TimedOutException(ee.toString());
312 String result = stripOffCmdFromRouterResponse(sbReceive.toString());
313 debugLog.printRTAriDebug(fn, "Leaving method successfully");
317 public boolean checkIfReceivedStringMatchesDelimeter(String delimeters, String receivedString,
318 String cmdThatWasSent) {
319 // The delimeters are in a '|' seperated string. Return true on the first match.
320 String fn = "SshJcraftWrapper.checkIfReceivedStringMatchesDelimeter";
321 appendToFile(debugLogFileName,
322 fn + " Entered: delimeters='" + delimeters + " cmdThatWasSent='" + cmdThatWasSent + "' receivedString='"
323 + receivedString + "'\n");
324 StringTokenizer st = new StringTokenizer(delimeters, "|");
326 if ((delimeters.indexOf("#$") != -1) || (routerCmdType.equals("CLI"))) // This would be an IOS XR, CLI command.
328 int x = receivedString.lastIndexOf("#");
329 int y = receivedString.length() - 1;
330 appendToFile(debugLogFileName, fn + " IOS XR, CLI command\n");
331 if (extraDebugFile.exists()) {
332 appendToFile(debugLogFileName,
333 fn + " :::cmdThatWasSent='" + cmdThatWasSent + "' x=" + x + " y=" + y + "\n");
335 if ((x != -1) && (y == x)) {
341 if (cmdThatWasSent.indexOf("show config") != -1) {
342 appendToFile(debugLogFileName, fn + "In the block for 'show config'\n");
343 while (st.hasMoreTokens()) {
344 String delimeter = st.nextToken();
345 // Make sure we don't get faked out by a response of " #".
347 // # signaling-local-address ipv6 FD00:F4D5:EA06:1::110:136:254
349 int x = receivedString.lastIndexOf(delimeter);
350 if ((receivedString.lastIndexOf(delimeter) != -1) && (receivedString.lastIndexOf(" #") != x - 1)) {
351 appendToFile(debugLogFileName, fn + "receivedString=\n'" + receivedString + "'\n");
352 appendToFile(debugLogFileName,
353 fn + "Returning true for the 'show config' command. We found our real delmeter. \n\n");
358 aggregatedReceivedString = aggregatedReceivedString + receivedString;
359 _appendToFile("/tmp/aggregatedReceivedString.debug", aggregatedReceivedString);
361 while (st.hasMoreTokens()) {
362 String delimeter = st.nextToken();
363 appendToFile(debugLogFileName, fn + " Looking for an delimeter of:'" + delimeter + "'\n");
364 appendToFile(debugLogFileName, fn + " receivedString='" + receivedString);
365 if (aggregatedReceivedString.indexOf(delimeter) != -1) {
366 debugLog.printRTAriDebug(fn, "Found our delimeter, which was: '" + delimeter + "'");
367 aggregatedReceivedString = "";
375 public boolean checkIfReceivedStringMatchesDelimeter(int len, String delimeter) {
376 String fnName = "SshJcraftWrapper.checkIfReceivedStringMatchesDelimeter:::";
379 String str = StringUtils.EMPTY;
381 if (jcraftReadSwConfigFileFromDisk()) {
382 DebugLog.printAriDebug(fnName, "jcraftReadSwConfigFileFromDisk block");
383 File fileName = new File(routerFileName);
384 appendToFile(debugLogFileName,
385 fnName + " jcraftReadSwConfigFileFromDisk::: Will read the tail end of the file from the disk");
387 str = getLastFewLinesOfFile(fileName, 3);
388 } catch (IOException e) {
389 DebugLog.printAriDebug(fnName, "Caught an Exception, e=" + e);
390 dbLog.outputStackTrace(e);
394 // DebugLog.printAriDebug(fnName, "TRACE 1: ******************************");
395 // When looking at the end of the charBuffer, don't include any linefeeds or spaces. We only want to make the smallest string possible.
396 for (x = len - 1; x >= 0; x--) {
398 if (extraDebugFile.exists()) {
399 appendToFile(debugLogFileName, fnName + " x=" + x + " c=" + c + "\n");
401 if ((c != 10) && (c != 32)) // Not a line feed nor a space.
406 if ((x + 1 - 13) >= 0) {
407 str = new String(charBuffer, (x + 1 - 13), 13);
408 appendToFile(debugLogFileName, fnName + " str:'" + str + "'\n");
410 File fileName = new File(routerFileName);
411 appendToFile(debugLogFileName,
412 fnName + " Will read the tail end of the file from the disk, x=" + x + " len=" + len + " str::'"
413 + str + "' routerFileName='" + routerFileName + "'\n");
414 DebugLog.printAriDebug(fnName,
415 "Will read the tail end of the file from the disk, x=" + x + " len=" + len + " str::'" + str
416 + "' routerFileName='" + routerFileName + "'");
418 str = getLastFewLinesOfFile(fileName, 3);
419 } catch (IOException e) {
420 DebugLog.printAriDebug(fnName, "Caught an Exception, e=" + e);
421 dbLog.outputStackTrace(e);
427 if (str.indexOf(delimeter) != -1) {
428 DebugLog.printAriDebug(fnName, "str in break is:'" + str + "'" + " delimeter='" + delimeter + "'");
429 appendToFile(debugLogFileName,
430 fnName + " str in break is:'" + str + " delimeter='" + delimeter + "'" + "'\n");
433 appendToFile(debugLogFileName, fnName + " Returning false");
439 public void closeConnection() {
440 String fn = "SshJcraftWrapper.closeConnection";
441 debugLog.printRTAriDebug(fn, "Executing the closeConnection....");
446 session.disconnect();
450 public void send(String cmd) throws IOException {
451 String fn = "SshJcraftWrapper.send";
452 OutputStream out = channel.getOutputStream();
453 DataOutputStream dos = new DataOutputStream(out);
455 if ((cmd.charAt(cmd.length() - 1) != '\n') && (cmd.charAt(cmd.length() - 1) != '\r')) {
458 int length = cmd.length();
461 int ncharsTotalSent = 0;
464 appendToFile(debugLogFileName, fn + ": Sending: '" + cmd);
465 // debugLog.printRTAriDebug (fn, "cmd = "+cmd);
466 debugLog.printRTAriDebug(fn, "Length of cmd is:" + length); // 2,937,706
468 if (length > 600000) {
470 for (i = 0; i < length; i += nchars) {
471 String Cmd = cmd.substring(i, Math.min(length, i + nchars));
472 ncharsSent = Cmd.length();
473 ncharsTotalSent = ncharsTotalSent + Cmd.length();
474 debugLog.printRTAriDebug(fn, "i=" + i + " Sending Cmd: ncharsSent=" + ncharsSent);
478 debugLog.printRTAriDebug(fn, ":::i=" + i + " length=" + length);
479 if (ncharsSent < length) {
480 receiveUntilBufferFlush(ncharsSent, timeout, "buffer flush i=" + i);
482 debugLog.printRTAriDebug(fn, "i=" + i + " No Waiting this time....");
485 } catch (Exception e) {
486 debugLog.printRTAriDebug(fn, "Caught an Exception: Nothing to flush out.");
490 debugLog.printRTAriDebug(fn, "Before executing the dos.writeBytes");
494 debugLog.printRTAriDebug(fn, "Leaving method");
495 appendToFile(debugLogFileName, fn + ": Leaving method\n");
496 } catch (IOException e) {
497 debugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e);
498 dbLog.outputStackTrace(e);
499 throw new IOException(e.toString());
504 public void sendChar(int v) throws IOException {
505 String fn = "SshJcraftWrapper.sendChar";
506 OutputStream out = channel.getOutputStream();
507 DataOutputStream dos = new DataOutputStream(out);
509 debugLog.printRTAriDebug(fn, "Sending: '" + v + "'");
512 } catch (IOException e) {
513 debugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e);
514 throw new IOException(e.toString());
518 public void send(byte[] b, int off, int len) throws IOException {
519 String fn = "SshJcraftWrapper.send:byte[]";
520 OutputStream out = channel.getOutputStream();
521 DataOutputStream dos = new DataOutputStream(out);
523 dos.write(b, off, len);
525 } catch (IOException e) {
526 debugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e);
527 throw new IOException(e.toString());
531 public static class MyUserInfo implements UserInfo, UIKeyboardInteractive {
533 public String getPassword() {
537 public boolean promptYesNo(String str) {
541 public String getPassphrase() {
545 public boolean promptPassphrase(String message) {
549 public boolean promptPassword(String message) {
553 public void showMessage(String message) {
556 public String[] promptKeyboardInteractive(String destination,
565 public void addListener(TelnetListener listener) {
566 this.listener = listener;
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 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
578 // out.write(dataToWrite);
579 // out.write(getTheDate() +": " +Thread.currentThread().getName() +": "+dataToWrite);
580 out.write(getTheDate() + ": " + tId + ": " + dataToWrite);
583 } catch (IOException e) {
584 debugLog.printRTAriDebug(fn, "Caught an IOException: e=" + e);
585 } catch (Exception e) {
586 debugLog.printRTAriDebug(fn, "Caught an Exception: e=" + e);
590 public void _appendToFile(String fileName, String dataToWrite) {
591 String fn = "SshJcraftWrapper.appendToFile";
594 // First check to see if a file 'fileName' exist, if it does
595 // write to it. If it does not exist, don't write to it.
596 File tmpFile = new File(fileName);
597 if (tmpFile.exists()) {
598 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
599 out.write(dataToWrite);
602 } catch (IOException e) {
603 debugLog.printRTAriDebug(fn, "Caught an IOException: e=" + e);
604 } catch (Exception e) {
605 debugLog.printRTAriDebug(fn, "Caught an Exception: e=" + e);
610 public String getTheDate() {
611 Calendar cal = Calendar.getInstance();
612 java.util.Date today = cal.getTime();
613 DateFormat df1 = DateFormat.getDateInstance();
614 DateFormat df3 = new SimpleDateFormat("MM/dd/yyyy H:mm:ss ");
615 return (df3.format(today));
619 public void appendToRouterFile(String fileName, StringBuffer dataToWrite) {
620 String fnName = "SshJcraftWrapper.appendToRouterFile";
621 debugLog.printRTAriDebug(fnName, "Entered.... ");
623 // First check to see if a file 'fileName' exist, if it does
624 // write to it. If it does not exist, don't write to it.
625 File tmpFile = new File(fileName);
627 // if ((tmpFile.exists()) && (tmpFile.setWritable(true, true)))
628 if (tmpFile.exists()) {
629 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
630 // out.write("<!-- "+getTheDate() +": " +tId +" -->\n");
631 out.write(dataToWrite.toString());
635 } catch (IOException e) {
636 System.err.println("writeToFile() exception: " + e);
641 public void appendToRouterFile(String fileName, int len) {
642 String fnName = "SshJcraftWrapper.appendToFile";
643 // debugLog.printRTAriDebug (fnName, "Entered.... len="+len);
645 // First check to see if a file 'fileName' exist, if it does
646 // write to it. If it does not exist, don't write to it.
647 File tmpFile = new File(fileName);
648 // if ((tmpFile.exists()) && (tmpFile.setWritable(true, true)))
649 if (tmpFile.exists()) {
650 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
651 // out.write("<!-- "+getTheDate() +": " +tId +" -->\n");
652 out.write(charBuffer, 0, len);
655 } catch (IOException e) {
656 System.err.println("writeToFile() exception: " + e);
661 public String removeWhiteSpaceAndNewLineCharactersAroundString(String str) {
663 StringTokenizer strTok = new StringTokenizer(str, "\n");
664 StringBuffer sb = new StringBuffer();
666 while (strTok.hasMoreTokens()) {
667 String line = strTok.nextToken();
670 return (sb.toString().trim());
676 public String stripOffCmdFromRouterResponse(String routerResponse) {
677 String fn = "SshJcraftWrapper.stripOffCmdFromRouterResponse";
678 // appendToFile(debugLogFileName, fn+": routerResponse='"+routerResponse +"'\n");
680 // The session of SSH will echo the command sent to the router, in the router's response.
681 // Since all our commands are terminated by a '\n', strip off the first line
682 // of the response from the router. This first line contains the orginal command.
684 StringTokenizer rr = new StringTokenizer(routerResponse, "\n");
685 StringBuffer sb = new StringBuffer();
687 int numTokens = rr.countTokens();
688 // debugLog.printRTAriDebug (fn, "Number of lines in the response from the router is:" +numTokens);
690 rr.nextToken(); //Skip the first line.
691 while (rr.hasMoreTokens()) {
692 sb.append(rr.nextToken() + '\n');
695 return (sb.toString());
698 public void setRouterCommandType(String type) {
699 String fn = "SshJcraftWrapper.setRouterCommandType";
700 this.routerCmdType = type;
701 debugLog.printRTAriDebug(fn, "Setting routerCmdType to a value of '" + type + "'");
704 public String getLastFewLinesOfFile(File file, int linesToRead) throws FileNotFoundException, IOException {
705 String fn = "SshJcraftWrapper.getLastFewLinesOfFile";
706 RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
708 StringBuilder builder = new StringBuilder();
710 long length = file.length();
712 randomAccessFile.seek(length);
713 for (long seek = length; seek >= 0; --seek) {
714 randomAccessFile.seek(seek);
715 char c = (char) randomAccessFile.read();
718 builder = builder.reverse();
719 // System.out.println(builder.toString());
720 tail = builder.toString() + tail;
722 builder.setLength(0);
723 if (lines == linesToRead) {
728 randomAccessFile.close();
729 if (!jcraftReadSwConfigFileFromDisk()) {
730 debugLog.printRTAriDebug(fn, "tail='" + tail + "'");
732 appendToFile(debugLogFileName, "tail='" + tail + "'\n");
736 public boolean jcraftReadSwConfigFileFromDisk() {
737 if (jcraftReadSwConfigFileFromDisk.exists()) {
744 public String getEquipNameCode() {
745 return (equipNameCode);
749 public void setEquipNameCode(String equipNameCode) {
750 this.equipNameCode = equipNameCode;
753 public String getRouterName() {
757 // Routine does reads until it has read 'nchars' or times out.
758 public void receiveUntilBufferFlush(int ncharsSent, int timeout, String message)
759 throws TimedOutException, IOException {
760 String fn = "SshJcraftWrapper.receiveUntilBufferFlush";
761 StringBuffer sb2 = new StringBuffer();
762 StringBuffer sbReceive = new StringBuffer();
763 debugLog.printRTAriDebug(fn, "ncharsSent=" + ncharsSent + " timeout=" + timeout + " " + message);
764 int ncharsTotalReceived = 0;
766 boolean flag = false;
767 charactersFromBufferFlush.setLength(0);
769 long deadline = new Date().getTime() + timeout;
772 session.setTimeout(timeout); // This is the socket timeout value.
774 if (new Date().getTime() > deadline) {
775 debugLog.printRTAriDebug(fn,
776 "Throwing a TimedOutException: time in routine has exceed our deadline: ncharsSent="
777 + ncharsSent + " ncharsTotalReceived=" + ncharsTotalReceived);
779 throw new TimedOutException("Timeout: time in routine has exceed our deadline");
781 ncharsRead = reader.read(charBuffer, 0, BUFFER_SIZE);
782 if (listener != null) {
783 listener.receivedString(String.copyValueOf(charBuffer, 0, ncharsRead));
785 appendToRouterFile("/tmp/" + RouterName, ncharsRead);
786 ncharsTotalReceived = ncharsTotalReceived + ncharsRead;
787 // debugLog.printRTAriDebug (fn, "::ncharsSent="+ncharsSent+" ncharsTotalReceived="+ncharsTotalReceived +" ncharsRead="+ncharsRead);
788 if (ncharsTotalReceived >= ncharsSent) {
789 debugLog.printRTAriDebug(fn,
790 "Received the correct number of characters, ncharsSent=" + ncharsSent + " ncharsTotalReceived="
791 + ncharsTotalReceived);
796 } catch (JSchException e) {
797 debugLog.printRTAriDebug(fn, "Caught an JSchException e=" + e.toString());
798 debugLog.printRTAriDebug(fn,
799 "ncharsSent=" + ncharsSent + " ncharsTotalReceived=" + ncharsTotalReceived + " ncharsRead="
801 throw new TimedOutException(e.toString());
805 public String getHostName() {
809 public String getUserName() {
813 public String getPassWord() {
817 public void sftpPut(String sourcePath, String destDirectory) throws IOException {
818 String fn = "SshJcraftWrapper.sftp";
820 Session sftpSession = jsch.getSession(userName, hostName, 22);
821 UserInfo ui = new MyUserInfo();
822 sftpSession.setPassword(passWord);
823 sftpSession.setUserInfo(ui);
824 sftpSession.connect(30 * 1000);
825 debugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
826 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
827 debugLog.printRTAriDebug(fn, "Connecting....");
829 debugLog.printRTAriDebug(fn, "Sending " + sourcePath + " --> " + destDirectory);
830 sftp.put(sourcePath, destDirectory, ChannelSftp.OVERWRITE);
831 debugLog.printRTAriDebug(fn, "Sent successfully");
832 sftpSession.disconnect();
833 } catch (Exception e) {
834 debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
835 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
836 throw new IOException(e.toString());
841 public void SftpPut(String stringOfData, String fullPathDest) throws IOException {
842 String fn = "SshJcraftWrapper.Sftp";
844 Session sftpSession = jsch.getSession(userName, hostName, 22);
845 UserInfo ui = new MyUserInfo();
846 sftpSession.setPassword(passWord);
847 sftpSession.setUserInfo(ui);
848 sftpSession.connect(30 * 1000);
849 debugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
850 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
851 debugLog.printRTAriDebug(fn, "Connecting....");
853 InputStream is = new ByteArrayInputStream(stringOfData.getBytes());
854 debugLog.printRTAriDebug(fn, "Sending stringOfData --> " + fullPathDest);
855 sftp.put(is, fullPathDest, ChannelSftp.OVERWRITE);
856 debugLog.printRTAriDebug(fn, "Sent successfully");
857 sftpSession.disconnect();
858 } catch (Exception e) {
859 debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
860 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
861 throw new IOException(e.toString());
865 public String sftpGet(String fullFilePathName) throws IOException {
866 String fn = "SshJcraftWrapper.Sftp";
868 Session sftpSession = jsch.getSession(userName, hostName, 22);
869 UserInfo ui = new MyUserInfo();
870 sftpSession.setPassword(passWord);
871 sftpSession.setUserInfo(ui);
872 sftpSession.connect(30 * 1000);
873 debugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
874 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
875 debugLog.printRTAriDebug(fn, "Connecting....");
877 InputStream in = null;
878 in = sftp.get(fullFilePathName);
879 String sftpFileString = readInputStreamAsString(in);
880 debugLog.printRTAriDebug(fn, "Retreived successfully");
881 // debugLog.printRTAriDebug (fn, "sftpFileString="+sftpFileString);
882 sftpSession.disconnect();
883 return (sftpFileString);
884 } catch (Exception e) {
885 debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
886 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
887 throw new IOException(e.toString());
891 public static String readInputStreamAsString(InputStream in) throws IOException {
892 BufferedInputStream bis = new BufferedInputStream(in);
893 ByteArrayOutputStream buf = new ByteArrayOutputStream();
894 int result = bis.read();
895 while (result != -1) {
896 byte b = (byte) result;
900 return buf.toString();
904 public void logMemoryUsage() {
905 String fn = "SshJcraftWrapper.logMemoryUsage";
906 int mb = 1024 * 1024;
908 long maxMemoryAdvailable;
909 long memoryLetfOnHeap;
910 maxMemoryAdvailable = (runtime.maxMemory() / mb);
911 usedMemory = ((runtime.totalMemory() / mb) - (runtime.freeMemory() / mb));
912 memoryLetfOnHeap = maxMemoryAdvailable - usedMemory;
913 DebugLog.printAriDebug(fn,
914 "maxMemoryAdvailable=" + maxMemoryAdvailable + " usedMemory=" + usedMemory + " memoryLetfOnHeap="
918 // ----------------------------------------------------------------------------
919 // ----------------------------------------------------------------------------
920 // ----------------------------------------------------------------------------
921 // ----------------------------------------------------------------------------
924 // User specifies the port number, and the subsystem
925 public void connect(String hostname, String username, String password, String prompt, int timeOut, int portNum,
926 String subsystem) throws IOException {
927 String fn = "SshJcraftWrapper.connect";
929 debugLog.printRTAriDebug(fn,
930 ":::Attempting to connect to " + hostname + " username=" + username + " password=" + password + " prompt='"
931 + prompt + "' timeOut=" + timeOut + " portNum=" + portNum + " subsystem=" + subsystem);
932 RouterName = hostname;
935 session = jsch.getSession(username, hostname, portNum);
936 UserInfo ui = new MyUserInfo();
937 session.setPassword(password);
938 session.setUserInfo(ui);
939 session.setConfig("StrictHostKeyChecking", "no");
940 session.connect(timeOut);
941 session.setServerAliveCountMax(
942 0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
943 channel = session.openChannel("subsystem");
944 ((ChannelSubsystem) channel).setSubsystem(subsystem);
945 // ((ChannelSubsystem)channel).setPtyType("vt102");
946 ((ChannelSubsystem) channel).setPty(true);
948 inputStream = channel.getInputStream();
949 dis = new DataInputStream(inputStream);
950 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
952 debugLog.printRTAriDebug(fn, "Successfully connected.");
953 debugLog.printRTAriDebug(fn, "Five second sleep....");
956 } catch (java.lang.InterruptedException ee) {
957 boolean ignore = true;
959 } catch (Exception e) {
960 debugLog.printRTAriDebug(fn, "Caught an Exception. e=" + e);
961 throw new IOException(e.toString());
965 public void connect(String hostName, String username, String password, int portNumber) throws IOException {
966 String fn = "SshJcraftWrapper.connect";
968 debugLog.printRTAriDebug(fn,
969 "::Attempting to connect to " + hostName + " username=" + username + " password=" + password
970 + " portNumber=" + portNumber);
971 debugLog.printRTAriDebug(fn, "Trace C");
972 RouterName = hostName;
973 this.hostName = hostName;
977 java.util.Properties config = new java.util.Properties();
978 config.put("StrictHostKeyChecking", "no");
979 session = jsch.getSession(username, hostName, 22);
980 // session = jsch.getSession(username, hostName, portNumber);
981 UserInfo ui = new MyUserInfo();
982 session.setConfig(config);
983 session.setPassword(password);
984 session.setUserInfo(ui);
985 session.connect(30000);
986 channel = session.openChannel("shell");
987 session.setServerAliveCountMax(
988 0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
989 ((ChannelShell) channel).setPtyType("vt102");
990 inputStream = channel.getInputStream();
991 dis = new DataInputStream(inputStream);
992 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
994 debugLog.printRTAriDebug(fn, "::Successfully connected.");
995 debugLog.printRTAriDebug(fn, "::Flushing input buffer");
997 receiveUntil(":~#", 9000, "No cmd was sent, just waiting, but we can stop on a '~#'");
998 } catch (Exception e) {
999 debugLog.printRTAriDebug(fn, "Caught an Exception::: Nothing to flush out.");
1002 } catch (Exception e) {
1003 debugLog.printRTAriDebug(fn, "Caught an Exception. e=" + e);
1004 // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostName +" "+e);
1005 throw new IOException(e.toString());
1010 public void put(String sourcePath, String destDirectory) throws IOException {
1011 String fn = "SshJcraftWrapper.sftp";
1013 Session sftpSession = jsch.getSession(userName, hostName, 22);
1014 UserInfo ui = new MyUserInfo();
1015 sftpSession.setPassword(passWord);
1016 sftpSession.setUserInfo(ui);
1017 sftpSession.connect(30 * 1000);
1018 debugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
1019 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
1020 debugLog.printRTAriDebug(fn, "Connecting....");
1022 debugLog.printRTAriDebug(fn, "Sending " + sourcePath + " --> " + destDirectory);
1023 sftp.put(sourcePath, destDirectory, ChannelSftp.OVERWRITE);
1024 debugLog.printRTAriDebug(fn, "Sent successfully");
1025 sftpSession.disconnect();
1026 } catch (Exception e) {
1027 debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
1028 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
1029 throw new IOException(e.toString());
1033 public void put(InputStream is, String fullPathDest, String hostName, String userName, String passWord)
1034 throws IOException {
1035 String fn = "SshJcraftWrapper.put";
1036 Session sftpSession = null;
1038 debugLog.printRTAriDebug(fn, "userName=" + userName + " hostName=" + hostName + " passWord=" + passWord);
1040 java.util.Properties config = new java.util.Properties();
1041 config.put("StrictHostKeyChecking", "no");
1042 sftpSession = jsch.getSession(userName, hostName, 22);
1043 UserInfo ui = new MyUserInfo();
1044 sftpSession.setPassword(passWord);
1045 sftpSession.setUserInfo(ui);
1046 sftpSession.setConfig(config);
1047 sftpSession.connect(30 * 1000);
1048 debugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
1049 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
1050 debugLog.printRTAriDebug(fn, "Connecting....");
1052 String oldFiles = fullPathDest + "*";
1053 debugLog.printRTAriDebug(fn, "Deleting old files --> " + oldFiles);
1056 debugLog.printRTAriDebug(fn, "Sending stringOfData --> " + fullPathDest);
1057 } catch (SftpException sft) {
1058 String exp = "No such file";
1059 if (sft.getMessage() != null && sft.getMessage().contains(exp)) {
1060 debugLog.printRTAriDebug(fn, "No files found -- Continue");
1062 debugLog.printRTAriDebug(fn, "Exception while sftp.rm " + sft.getMessage());
1063 sft.printStackTrace();
1067 sftp.put(is, fullPathDest, ChannelSftp.OVERWRITE);
1068 debugLog.printRTAriDebug(fn, "Sent successfully");
1069 } catch (Exception e) {
1070 debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
1071 throw new IOException(e.toString());
1073 if(sftpSession != null) {
1074 sftpSession.disconnect();
1080 public String get(String fullFilePathName, String hostName, String userName, String passWord) throws IOException {
1081 String fn = "SshJcraftWrapper.get";
1082 Session sftpSession = null;
1084 debugLog.printRTAriDebug(fn, "userName=" + userName + " hostName=" + hostName + " passWord=" + passWord);
1086 sftpSession = jsch.getSession(userName, hostName, 22);
1087 java.util.Properties config = new java.util.Properties();
1088 config.put("StrictHostKeyChecking", "no");
1089 UserInfo ui = new MyUserInfo();
1090 sftpSession.setPassword(passWord);
1091 sftpSession.setUserInfo(ui);
1092 sftpSession.setConfig(config);
1093 sftpSession.connect(30 * 1000);
1094 debugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
1095 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
1096 debugLog.printRTAriDebug(fn, "Connecting....");
1098 InputStream in = null;
1099 in = sftp.get(fullFilePathName);
1100 String sftpFileString = readInputStreamAsString(in);
1101 debugLog.printRTAriDebug(fn, "Retreived successfully");
1102 // debugLog.printRTAriDebug (fn, "sftpFileString="+sftpFileString);
1103 sftpSession.disconnect();
1105 return (sftpFileString);
1106 } catch (Exception e) {
1107 debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
1108 sftpSession.disconnect();
1110 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
1111 throw new IOException(e.toString());
1115 public String send(String cmd, String delimiter) throws IOException {
1116 String fn = "SshJcraftWrapper.send";
1117 OutputStream out = channel.getOutputStream();
1118 DataOutputStream dos = new DataOutputStream(out);
1120 if ((cmd.charAt(cmd.length() - 1) != '\n') && (cmd.charAt(cmd.length() - 1) != '\r')) {
1123 int length = cmd.length();
1125 int nchars = 300000;
1126 int ncharsTotalSent = 0;
1129 debugLog.printRTAriDebug(fn, "Length of cmd is:" + length); // 2,937,706
1130 debugLog.printRTAriDebug(fn, "Length of cmd is:" + length); // 2,937,706
1132 if (length > 600000) {
1134 for (i = 0; i < length; i += nchars) {
1135 String Cmd = cmd.substring(i, Math.min(length, i + nchars));
1136 ncharsSent = Cmd.length();
1137 ncharsTotalSent = ncharsTotalSent + Cmd.length();
1138 debugLog.printRTAriDebug(fn, "i=" + i + " Sending Cmd: ncharsSent=" + ncharsSent);
1139 dos.writeBytes(Cmd);
1142 debugLog.printRTAriDebug(fn, ":::i=" + i + " length=" + length);
1143 if (ncharsSent < length) {
1144 receiveUntilBufferFlush(ncharsSent, timeout, "buffer flush i=" + i);
1146 debugLog.printRTAriDebug(fn, "i=" + i + " No Waiting this time....");
1149 } catch (Exception e) {
1150 debugLog.printRTAriDebug(fn, "Caught an Exception: Nothing to flush out.");
1154 debugLog.printRTAriDebug(fn, "Before executing the dos.writeBytes");
1155 dos.writeBytes(cmd);
1158 // Now lets get the response.
1159 String response = receiveUntil(delimiter, 300000, cmd);
1160 debugLog.printRTAriDebug(fn, "Leaving method");
1162 } catch (IOException e) {
1163 debugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e);
1164 throw new IOException(e.toString());