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;
58 public class SshJcraftWrapper {
60 InputStream inputStream = null;
61 OutputStream outputStream = null;
62 DebugLog debugLog = new DebugLog();
63 private String debugLogFileName = "/tmp/sshJcraftWrapperDebug";
64 private TelnetListener listener = null;
65 private String routerLogFileName = null;
66 private String host = null;
67 private String RouterName = null;
68 private int BUFFER_SIZE = 512000;
69 char[] charBuffer = new char[BUFFER_SIZE];
70 // private int BUFFER_SIZE = 4000000;
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 void SshJcraftWrapper() {
93 String fn = "SshJcraftWrapper.SshJcraftWrapper";
94 debugLog.printRTAriDebug(fn, "SshJcraftWrapper has been instantated");
95 routerLogFileName = "/tmp/" + host;
99 public void connect(String hostname, String username, String password, String prompt, int timeOut)
101 String fn = "SshJcraftWrapper.connect";
103 debugLog.printRTAriDebug(fn,
104 "Attempting to connect to " + hostname + " username=" + username + " password=" + password + " prompt='"
105 + prompt + "' timeOut=" + timeOut);
106 debugLog.printRTAriDebug(fn, "Trace A");
107 RouterName = hostname;
112 session = jsch.getSession(username, hostname, 22);
113 UserInfo ui = new MyUserInfo();
114 session.setPassword(password);
115 session.setUserInfo(ui);
116 session.connect(timeOut);
117 channel = session.openChannel("shell");
118 session.setServerAliveCountMax(
119 0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
120 ((ChannelShell) channel).setPtyType("vt102");
121 inputStream = channel.getInputStream();
122 dis = new DataInputStream(inputStream);
123 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
125 debugLog.printRTAriDebug(fn, "Successfully connected.");
126 debugLog.printRTAriDebug(fn, "Flushing input buffer");
128 receiveUntil(prompt, 3000, "No cmd was sent, just waiting");
129 } catch (Exception e) {
130 debugLog.printRTAriDebug(fn, "Caught an Exception: Nothing to flush out.");
132 } catch (Exception e) {
133 debugLog.printRTAriDebug(fn, "Caught an Exception. e=" + e);
134 // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostname +" "+e);
135 throw new IOException(e.toString());
139 // User specifies the port number.
140 public void connect(String hostname, String username, String password, String prompt, int timeOut, int portNum)
142 String fn = "SshJcraftWrapper.connect";
143 debugLog.printRTAriDebug(fn,
144 ":Attempting to connect to " + hostname + " username=" + username + " password=" + password + " prompt='"
145 + prompt + "' timeOut=" + timeOut + " portNum=" + portNum);
146 RouterName = hostname;
150 RouterName = hostname;
153 session = jsch.getSession(username, hostname, portNum);
154 UserInfo ui = new MyUserInfo();
155 session.setPassword(password);
156 session.setUserInfo(ui);
157 session.setConfig("StrictHostKeyChecking", "no");
158 debugLog.printRTAriDebug(fn, ":StrictHostKeyChecking set to 'no'");
160 session.connect(timeOut);
161 session.setServerAliveCountMax(
162 0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
163 channel = session.openChannel("shell");
164 ((ChannelShell) channel).setPtyType("vt102");
165 inputStream = channel.getInputStream();
166 dis = new DataInputStream(inputStream);
167 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
169 debugLog.printRTAriDebug(fn, ":Successfully connected.");
170 debugLog.printRTAriDebug(fn, ":Flushing input buffer");
172 if (prompt.equals("]]>]]>")) {
173 receiveUntil("]]>]]>", 10000, "No cmd was sent, just waiting");
175 receiveUntil(":~#", 5000, "No cmd was sent, just waiting");
177 } catch (Exception e) {
178 debugLog.printRTAriDebug(fn, "Caught an Exception::: Nothing to flush out.");
180 } catch (Exception e) {
181 debugLog.printRTAriDebug(fn, ":Caught an Exception. e=" + e);
182 dbLog.outputStackTrace(e);
184 // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostname +" "+e);
185 throw new IOException(e.toString());
190 public String receiveUntil(String delimeters, int timeout, String cmdThatWasSent)
191 throws TimedOutException, IOException {
192 String fn = "SshJcraftWrapper.receiveUntil";
193 boolean match = false;
194 boolean cliPromptCmd = false;
195 StringBuffer sb2 = new StringBuffer();
196 StringBuffer sbReceive = new StringBuffer();
197 debugLog.printRTAriDebug(fn,
198 "delimeters='" + delimeters + "' timeout=" + timeout + " cmdThatWasSent='" + cmdThatWasSent + "'");
199 appendToFile(debugLogFileName,
200 fn + " delimeters='" + delimeters + "' timeout=" + timeout + " cmdThatWasSent='" + cmdThatWasSent + "'\n");
201 String CmdThatWasSent = removeWhiteSpaceAndNewLineCharactersAroundString(cmdThatWasSent);
203 aggregatedReceivedString = "";
205 long deadline = new Date().getTime() + timeout;
207 session.setTimeout(timeout); // This is the socket timeout value.
209 if (new Date().getTime() > deadline) {
210 debugLog.printRTAriDebug(fn,
211 "Throwing a TimedOutException: time in routine has exceed our deadline: RouterName:"
212 + RouterName + " CmdThatWasSent=" + CmdThatWasSent);
213 throw new TimedOutException("Timeout: time in routine has exceed our deadline");
217 } catch (java.lang.InterruptedException ee) {
218 boolean ignore = true;
220 int len = reader.read(charBuffer, 0, BUFFER_SIZE);
221 appendToFile(debugLogFileName, fn + " After reader.read cmd: len=" + len + "\n");
223 debugLog.printRTAriDebug(fn,
224 "Reader read " + len + " bytes. Looks like we timed out, router=" + RouterName);
225 throw new TimedOutException("Received a SocketTimeoutException router=" + RouterName);
228 if (cmdThatWasSent.indexOf("IOS_XR_uploadedSwConfigCmd") != -1) {
230 // This is a IOS XR sw config file. We will write it to the disk.
231 timeout = timeout * 2;
232 deadline = new Date().getTime() + timeout;
233 debugLog.printRTAriDebug(fn, "IOS XR upload for software config: timeout=" + timeout);
234 StringTokenizer st = new StringTokenizer(cmdThatWasSent);
236 routerFileName = st.nextToken();
237 out = new BufferedWriter(new FileWriter(routerFileName));
238 routerLogFileName = "/tmp/" + RouterName;
239 _tmpFile = new File(routerLogFileName);
240 debugLog.printRTAriDebug(fn,
241 "Will write the swConfigFile to disk, routerFileName=" + routerFileName);
244 out.write(charBuffer, 0, len);
246 appendToFile(debugLogFileName, fn + " Wrote " + len + " bytes to the disk\n");
247 if (_tmpFile.exists()) {
248 appendToRouterFile(routerLogFileName, len);
250 match = checkIfReceivedStringMatchesDelimeter(len, "\nXML>");
259 appendToFile(debugLogFileName,
260 fn + " readCounts=" + readCounts + " Reader read " + len + " of data\n");
263 for (int i = 0; i < len; i++) {
265 if ((c != 7) && (c != 13) && (c != 0) && (c != 27)) {
266 sbReceive.append((char) charBuffer[i]);
267 sb2.append((char) charBuffer[i]);
270 appendToRouterFile("/tmp/" + RouterName, len);
271 if (listener != null) {
272 listener.receivedString(sb2.toString());
275 appendToFile(debugLogFileName, fn + " Trace 1\n");
276 match = checkIfReceivedStringMatchesDelimeter(delimeters, sb2.toString(), cmdThatWasSent);
277 appendToFile(debugLogFileName, fn + " Trace 2\n");
279 appendToFile(debugLogFileName, fn + " Match was true, breaking...\n");
284 debugLog.printRTAriDebug(fn, "cliPromptCmd, Trace 2");
286 for (int i = 0; i < len; i++) {
287 sbReceive.append((char) charBuffer[i]);
288 sb2.append((char) charBuffer[i]);
290 appendToRouterFile("/tmp/" + RouterName, sb2);
291 if (listener != null) {
292 listener.receivedString(sb2.toString());
294 debugLog.printRTAriDebug(fn, "sb2='" + sb2.toString() + "' delimeters='" + delimeters + "'");
295 if (sb2.toString().indexOf("\nariPrompt>") != -1) {
296 debugLog.printRTAriDebug(fn, "Found our prompt");
302 } catch (JSchException e) {
303 debugLog.printRTAriDebug(fn, "Caught an JSchException e=" + e.toString());
304 dbLog.outputStackTrace(e);
305 throw new TimedOutException(e.toString());
306 } catch (IOException ee) {
307 debugLog.printRTAriDebug(fn, "Caught an IOException: ee=" + ee.toString());
308 dbLog.outputStackTrace(ee);
309 throw new TimedOutException(ee.toString());
311 String result = stripOffCmdFromRouterResponse(sbReceive.toString());
312 debugLog.printRTAriDebug(fn, "Leaving method successfully");
316 public boolean checkIfReceivedStringMatchesDelimeter(String delimeters, String receivedString,
317 String cmdThatWasSent) {
318 // The delimeters are in a '|' seperated string. Return true on the first match.
319 String fn = "SshJcraftWrapper.checkIfReceivedStringMatchesDelimeter";
320 appendToFile(debugLogFileName,
321 fn + " Entered: delimeters='" + delimeters + " cmdThatWasSent='" + cmdThatWasSent + "' receivedString='"
322 + receivedString + "'\n");
323 StringTokenizer st = new StringTokenizer(delimeters, "|");
325 if ((delimeters.indexOf("#$") != -1) || (routerCmdType.equals("CLI"))) // This would be an IOS XR, CLI command.
327 int x = receivedString.lastIndexOf("#");
328 int y = receivedString.length() - 1;
329 appendToFile(debugLogFileName, fn + " IOS XR, CLI command\n");
330 if (extraDebugFile.exists()) {
331 appendToFile(debugLogFileName,
332 fn + " :::cmdThatWasSent='" + cmdThatWasSent + "' x=" + x + " y=" + y + "\n");
334 if ((x != -1) && (y == x)) {
340 if (cmdThatWasSent.indexOf("show config") != -1) {
341 appendToFile(debugLogFileName, fn + "In the block for 'show config'\n");
342 while (st.hasMoreTokens()) {
343 String delimeter = st.nextToken();
344 // Make sure we don't get faked out by a response of " #".
346 // # signaling-local-address ipv6 FD00:F4D5:EA06:1::110:136:254
348 int x = receivedString.lastIndexOf(delimeter);
349 if ((receivedString.lastIndexOf(delimeter) != -1) && (receivedString.lastIndexOf(" #") != x - 1)) {
350 appendToFile(debugLogFileName, fn + "receivedString=\n'" + receivedString + "'\n");
351 appendToFile(debugLogFileName,
352 fn + "Returning true for the 'show config' command. We found our real delmeter. \n\n");
357 aggregatedReceivedString = aggregatedReceivedString + receivedString;
358 _appendToFile("/tmp/aggregatedReceivedString.debug", aggregatedReceivedString);
360 while (st.hasMoreTokens()) {
361 String delimeter = st.nextToken();
362 appendToFile(debugLogFileName, fn + " Looking for an delimeter of:'" + delimeter + "'\n");
363 appendToFile(debugLogFileName, fn + " receivedString='" + receivedString);
364 if (aggregatedReceivedString.indexOf(delimeter) != -1) {
365 debugLog.printRTAriDebug(fn, "Found our delimeter, which was: '" + delimeter + "'");
366 aggregatedReceivedString = "";
374 public boolean checkIfReceivedStringMatchesDelimeter(int len, String delimeter) {
375 String fnName = "SshJcraftWrapper.checkIfReceivedStringMatchesDelimeter:::";
380 if (jcraftReadSwConfigFileFromDisk()) {
381 DebugLog.printAriDebug(fnName, "jcraftReadSwConfigFileFromDisk block");
382 File fileName = new File(routerFileName);
383 appendToFile(debugLogFileName,
384 fnName + " jcraftReadSwConfigFileFromDisk::: Will read the tail end of the file from the disk");
386 str = getLastFewLinesOfFile(fileName, 3);
387 } catch (IOException e) {
388 DebugLog.printAriDebug(fnName, "Caught an Exception, e=" + e);
389 dbLog.outputStackTrace(e);
393 // DebugLog.printAriDebug(fnName, "TRACE 1: ******************************");
394 // When looking at the end of the charBuffer, don't include any linefeeds or spaces. We only want to make the smallest string possible.
395 for (x = len - 1; x >= 0; x--) {
397 if (extraDebugFile.exists()) {
398 appendToFile(debugLogFileName, fnName + " x=" + x + " c=" + c + "\n");
400 if ((c != 10) && (c != 32)) // Not a line feed nor a space.
405 if ((x + 1 - 13) >= 0) {
406 str = new String(charBuffer, (x + 1 - 13), 13);
407 appendToFile(debugLogFileName, fnName + " str:'" + str + "'\n");
409 File fileName = new File(routerFileName);
410 appendToFile(debugLogFileName,
411 fnName + " Will read the tail end of the file from the disk, x=" + x + " len=" + len + " str::'"
412 + str + "' routerFileName='" + routerFileName + "'\n");
413 DebugLog.printAriDebug(fnName,
414 "Will read the tail end of the file from the disk, x=" + x + " len=" + len + " str::'" + str
415 + "' routerFileName='" + routerFileName + "'");
417 str = getLastFewLinesOfFile(fileName, 3);
418 } catch (IOException e) {
419 DebugLog.printAriDebug(fnName, "Caught an Exception, e=" + e);
420 dbLog.outputStackTrace(e);
426 if (str.indexOf(delimeter) != -1) {
427 DebugLog.printAriDebug(fnName, "str in break is:'" + str + "'" + " delimeter='" + delimeter + "'");
428 appendToFile(debugLogFileName,
429 fnName + " str in break is:'" + str + " delimeter='" + delimeter + "'" + "'\n");
432 appendToFile(debugLogFileName, fnName + " Returning false");
438 public void closeConnection() {
439 String fn = "SshJcraftWrapper.closeConnection";
440 debugLog.printRTAriDebug(fn, "Executing the closeConnection....");
445 session.disconnect();
449 public void send(String cmd) throws IOException {
450 String fn = "SshJcraftWrapper.send";
451 OutputStream out = channel.getOutputStream();
452 DataOutputStream dos = new DataOutputStream(out);
454 if ((cmd.charAt(cmd.length() - 1) != '\n') && (cmd.charAt(cmd.length() - 1) != '\r')) {
457 int length = cmd.length();
460 int ncharsTotalSent = 0;
463 appendToFile(debugLogFileName, fn + ": Sending: '" + cmd);
464 // debugLog.printRTAriDebug (fn, "cmd = "+cmd);
465 debugLog.printRTAriDebug(fn, "Length of cmd is:" + length); // 2,937,706
467 if (length > 600000) {
469 for (i = 0; i < length; i += nchars) {
470 String Cmd = cmd.substring(i, Math.min(length, i + nchars));
471 ncharsSent = Cmd.length();
472 ncharsTotalSent = ncharsTotalSent + Cmd.length();
473 debugLog.printRTAriDebug(fn, "i=" + i + " Sending Cmd: ncharsSent=" + ncharsSent);
477 debugLog.printRTAriDebug(fn, ":::i=" + i + " length=" + length);
478 if (ncharsSent < length) {
479 receiveUntilBufferFlush(ncharsSent, timeout, "buffer flush i=" + i);
481 debugLog.printRTAriDebug(fn, "i=" + i + " No Waiting this time....");
484 } catch (Exception e) {
485 debugLog.printRTAriDebug(fn, "Caught an Exception: Nothing to flush out.");
489 debugLog.printRTAriDebug(fn, "Before executing the dos.writeBytes");
493 debugLog.printRTAriDebug(fn, "Leaving method");
494 appendToFile(debugLogFileName, fn + ": Leaving method\n");
495 } catch (IOException e) {
496 debugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e);
497 dbLog.outputStackTrace(e);
498 throw new IOException(e.toString());
503 public void sendChar(int v) throws IOException {
504 String fn = "SshJcraftWrapper.sendChar";
505 OutputStream out = channel.getOutputStream();
506 DataOutputStream dos = new DataOutputStream(out);
508 debugLog.printRTAriDebug(fn, "Sending: '" + v + "'");
511 } catch (IOException e) {
512 debugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e);
513 throw new IOException(e.toString());
517 public void send(byte[] b, int off, int len) throws IOException {
518 String fn = "SshJcraftWrapper.send:byte[]";
519 OutputStream out = channel.getOutputStream();
520 DataOutputStream dos = new DataOutputStream(out);
522 dos.write(b, off, len);
524 } catch (IOException e) {
525 debugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e);
526 throw new IOException(e.toString());
530 public static class MyUserInfo implements UserInfo, UIKeyboardInteractive {
532 public String getPassword() {
536 public boolean promptYesNo(String str) {
540 public String getPassphrase() {
544 public boolean promptPassphrase(String message) {
548 public boolean promptPassword(String message) {
552 public void showMessage(String message) {
555 public String[] promptKeyboardInteractive(String destination,
564 public void addListener(TelnetListener listener) {
565 this.listener = listener;
568 public void appendToFile(String fileName, String dataToWrite) {
569 String fn = "SshJcraftWrapper.appendToFile";
572 // First check to see if a file 'fileName' exist, if it does
573 // write to it. If it does not exist, don't write to it.
574 File tmpFile = new File(fileName);
575 if (tmpFile.exists()) {
576 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
577 // out.write(dataToWrite);
578 // out.write(getTheDate() +": " +Thread.currentThread().getName() +": "+dataToWrite);
579 out.write(getTheDate() + ": " + tId + ": " + dataToWrite);
582 } catch (IOException e) {
583 debugLog.printRTAriDebug(fn, "Caught an IOException: e=" + e);
584 } catch (Exception e) {
585 debugLog.printRTAriDebug(fn, "Caught an Exception: e=" + e);
589 public void _appendToFile(String fileName, String dataToWrite) {
590 String fn = "SshJcraftWrapper.appendToFile";
593 // First check to see if a file 'fileName' exist, if it does
594 // write to it. If it does not exist, don't write to it.
595 File tmpFile = new File(fileName);
596 if (tmpFile.exists()) {
597 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
598 out.write(dataToWrite);
601 } catch (IOException e) {
602 debugLog.printRTAriDebug(fn, "Caught an IOException: e=" + e);
603 } catch (Exception e) {
604 debugLog.printRTAriDebug(fn, "Caught an Exception: e=" + e);
609 public String getTheDate() {
610 Calendar cal = Calendar.getInstance();
611 java.util.Date today = cal.getTime();
612 DateFormat df1 = DateFormat.getDateInstance();
613 DateFormat df3 = new SimpleDateFormat("MM/dd/yyyy H:mm:ss ");
614 return (df3.format(today));
618 public void appendToRouterFile(String fileName, StringBuffer dataToWrite) {
619 String fnName = "SshJcraftWrapper.appendToRouterFile";
620 debugLog.printRTAriDebug(fnName, "Entered.... ");
622 // First check to see if a file 'fileName' exist, if it does
623 // write to it. If it does not exist, don't write to it.
624 File tmpFile = new File(fileName);
626 // if ((tmpFile.exists()) && (tmpFile.setWritable(true, true)))
627 if (tmpFile.exists()) {
628 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
629 // out.write("<!-- "+getTheDate() +": " +tId +" -->\n");
630 out.write(dataToWrite.toString());
634 } catch (IOException e) {
635 System.err.println("writeToFile() exception: " + e);
640 public void appendToRouterFile(String fileName, int len) {
641 String fnName = "SshJcraftWrapper.appendToFile";
642 // debugLog.printRTAriDebug (fnName, "Entered.... len="+len);
644 // First check to see if a file 'fileName' exist, if it does
645 // write to it. If it does not exist, don't write to it.
646 File tmpFile = new File(fileName);
647 // if ((tmpFile.exists()) && (tmpFile.setWritable(true, true)))
648 if (tmpFile.exists()) {
649 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
650 // out.write("<!-- "+getTheDate() +": " +tId +" -->\n");
651 out.write(charBuffer, 0, len);
654 } catch (IOException e) {
655 System.err.println("writeToFile() exception: " + e);
660 public String removeWhiteSpaceAndNewLineCharactersAroundString(String str) {
662 StringTokenizer strTok = new StringTokenizer(str, "\n");
663 StringBuffer sb = new StringBuffer();
665 while (strTok.hasMoreTokens()) {
666 String line = strTok.nextToken();
669 return (sb.toString().trim());
675 public String stripOffCmdFromRouterResponse(String routerResponse) {
676 String fn = "SshJcraftWrapper.stripOffCmdFromRouterResponse";
677 // appendToFile(debugLogFileName, fn+": routerResponse='"+routerResponse +"'\n");
679 // The session of SSH will echo the command sent to the router, in the router's response.
680 // Since all our commands are terminated by a '\n', strip off the first line
681 // of the response from the router. This first line contains the orginal command.
683 StringTokenizer rr = new StringTokenizer(routerResponse, "\n");
684 StringBuffer sb = new StringBuffer();
686 int numTokens = rr.countTokens();
687 // debugLog.printRTAriDebug (fn, "Number of lines in the response from the router is:" +numTokens);
689 rr.nextToken(); //Skip the first line.
690 while (rr.hasMoreTokens()) {
691 sb.append(rr.nextToken() + '\n');
694 return (sb.toString());
697 public void setRouterCommandType(String type) {
698 String fn = "SshJcraftWrapper.setRouterCommandType";
699 this.routerCmdType = type;
700 debugLog.printRTAriDebug(fn, "Setting routerCmdType to a value of '" + type + "'");
703 public String getLastFewLinesOfFile(File file, int linesToRead) throws FileNotFoundException, IOException {
704 String fn = "SshJcraftWrapper.getLastFewLinesOfFile";
705 RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
707 StringBuilder builder = new StringBuilder();
709 long length = file.length();
711 randomAccessFile.seek(length);
712 for (long seek = length; seek >= 0; --seek) {
713 randomAccessFile.seek(seek);
714 char c = (char) randomAccessFile.read();
717 builder = builder.reverse();
718 // System.out.println(builder.toString());
719 tail = builder.toString() + tail;
721 builder.setLength(0);
722 if (lines == linesToRead) {
727 randomAccessFile.close();
728 if (!jcraftReadSwConfigFileFromDisk()) {
729 debugLog.printRTAriDebug(fn, "tail='" + tail + "'");
731 appendToFile(debugLogFileName, "tail='" + tail + "'\n");
735 public boolean jcraftReadSwConfigFileFromDisk() {
736 if (jcraftReadSwConfigFileFromDisk.exists()) {
743 public String getEquipNameCode() {
744 return (equipNameCode);
748 public void setEquipNameCode(String equipNameCode) {
749 this.equipNameCode = equipNameCode;
752 public String getRouterName() {
756 // Routine does reads until it has read 'nchars' or times out.
757 public void receiveUntilBufferFlush(int ncharsSent, int timeout, String message)
758 throws TimedOutException, IOException {
759 String fn = "SshJcraftWrapper.receiveUntilBufferFlush";
760 StringBuffer sb2 = new StringBuffer();
761 StringBuffer sbReceive = new StringBuffer();
762 debugLog.printRTAriDebug(fn, "ncharsSent=" + ncharsSent + " timeout=" + timeout + " " + message);
763 int ncharsTotalReceived = 0;
765 boolean flag = false;
766 charactersFromBufferFlush.setLength(0);
768 long deadline = new Date().getTime() + timeout;
771 session.setTimeout(timeout); // This is the socket timeout value.
773 if (new Date().getTime() > deadline) {
774 debugLog.printRTAriDebug(fn,
775 "Throwing a TimedOutException: time in routine has exceed our deadline: ncharsSent="
776 + ncharsSent + " ncharsTotalReceived=" + ncharsTotalReceived);
778 throw new TimedOutException("Timeout: time in routine has exceed our deadline");
780 ncharsRead = reader.read(charBuffer, 0, BUFFER_SIZE);
781 if (listener != null) {
782 listener.receivedString(String.copyValueOf(charBuffer, 0, ncharsRead));
784 appendToRouterFile("/tmp/" + RouterName, ncharsRead);
785 ncharsTotalReceived = ncharsTotalReceived + ncharsRead;
786 // debugLog.printRTAriDebug (fn, "::ncharsSent="+ncharsSent+" ncharsTotalReceived="+ncharsTotalReceived +" ncharsRead="+ncharsRead);
787 if (ncharsTotalReceived >= ncharsSent) {
788 debugLog.printRTAriDebug(fn,
789 "Received the correct number of characters, ncharsSent=" + ncharsSent + " ncharsTotalReceived="
790 + ncharsTotalReceived);
795 } catch (JSchException e) {
796 debugLog.printRTAriDebug(fn, "Caught an JSchException e=" + e.toString());
797 debugLog.printRTAriDebug(fn,
798 "ncharsSent=" + ncharsSent + " ncharsTotalReceived=" + ncharsTotalReceived + " ncharsRead="
800 throw new TimedOutException(e.toString());
804 public String getHostName() {
808 public String getUserName() {
812 public String getPassWord() {
816 public void sftpPut(String sourcePath, String destDirectory) throws IOException {
817 String fn = "SshJcraftWrapper.sftp";
819 Session sftpSession = jsch.getSession(userName, hostName, 22);
820 UserInfo ui = new MyUserInfo();
821 sftpSession.setPassword(passWord);
822 sftpSession.setUserInfo(ui);
823 sftpSession.connect(30 * 1000);
824 debugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
825 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
826 debugLog.printRTAriDebug(fn, "Connecting....");
828 debugLog.printRTAriDebug(fn, "Sending " + sourcePath + " --> " + destDirectory);
829 sftp.put(sourcePath, destDirectory, ChannelSftp.OVERWRITE);
830 debugLog.printRTAriDebug(fn, "Sent successfully");
831 sftpSession.disconnect();
832 } catch (Exception e) {
833 debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
834 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
835 throw new IOException(e.toString());
840 public void SftpPut(String stringOfData, String fullPathDest) throws IOException {
841 String fn = "SshJcraftWrapper.Sftp";
843 Session sftpSession = jsch.getSession(userName, hostName, 22);
844 UserInfo ui = new MyUserInfo();
845 sftpSession.setPassword(passWord);
846 sftpSession.setUserInfo(ui);
847 sftpSession.connect(30 * 1000);
848 debugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
849 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
850 debugLog.printRTAriDebug(fn, "Connecting....");
852 InputStream is = new ByteArrayInputStream(stringOfData.getBytes());
853 debugLog.printRTAriDebug(fn, "Sending stringOfData --> " + fullPathDest);
854 sftp.put(is, fullPathDest, ChannelSftp.OVERWRITE);
855 debugLog.printRTAriDebug(fn, "Sent successfully");
856 sftpSession.disconnect();
857 } catch (Exception e) {
858 debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
859 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
860 throw new IOException(e.toString());
864 public String sftpGet(String fullFilePathName) throws IOException {
865 String fn = "SshJcraftWrapper.Sftp";
867 Session sftpSession = jsch.getSession(userName, hostName, 22);
868 UserInfo ui = new MyUserInfo();
869 sftpSession.setPassword(passWord);
870 sftpSession.setUserInfo(ui);
871 sftpSession.connect(30 * 1000);
872 debugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
873 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
874 debugLog.printRTAriDebug(fn, "Connecting....");
876 InputStream in = null;
877 in = sftp.get(fullFilePathName);
878 String sftpFileString = readInputStreamAsString(in);
879 debugLog.printRTAriDebug(fn, "Retreived successfully");
880 // debugLog.printRTAriDebug (fn, "sftpFileString="+sftpFileString);
881 sftpSession.disconnect();
882 return (sftpFileString);
883 } catch (Exception e) {
884 debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
885 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
886 throw new IOException(e.toString());
890 public static String readInputStreamAsString(InputStream in) throws IOException {
891 BufferedInputStream bis = new BufferedInputStream(in);
892 ByteArrayOutputStream buf = new ByteArrayOutputStream();
893 int result = bis.read();
894 while (result != -1) {
895 byte b = (byte) result;
899 return buf.toString();
903 public void logMemoryUsage() {
904 String fn = "SshJcraftWrapper.logMemoryUsage";
905 int mb = 1024 * 1024;
907 long maxMemoryAdvailable;
908 long memoryLetfOnHeap;
909 maxMemoryAdvailable = (runtime.maxMemory() / mb);
910 usedMemory = ((runtime.totalMemory() / mb) - (runtime.freeMemory() / mb));
911 memoryLetfOnHeap = maxMemoryAdvailable - usedMemory;
912 DebugLog.printAriDebug(fn,
913 "maxMemoryAdvailable=" + maxMemoryAdvailable + " usedMemory=" + usedMemory + " memoryLetfOnHeap="
917 // ----------------------------------------------------------------------------
918 // ----------------------------------------------------------------------------
919 // ----------------------------------------------------------------------------
920 // ----------------------------------------------------------------------------
923 // User specifies the port number, and the subsystem
924 public void connect(String hostname, String username, String password, String prompt, int timeOut, int portNum,
925 String subsystem) throws IOException {
926 String fn = "SshJcraftWrapper.connect";
928 debugLog.printRTAriDebug(fn,
929 ":::Attempting to connect to " + hostname + " username=" + username + " password=" + password + " prompt='"
930 + prompt + "' timeOut=" + timeOut + " portNum=" + portNum + " subsystem=" + subsystem);
931 RouterName = hostname;
934 session = jsch.getSession(username, hostname, portNum);
935 UserInfo ui = new MyUserInfo();
936 session.setPassword(password);
937 session.setUserInfo(ui);
938 session.setConfig("StrictHostKeyChecking", "no");
939 session.connect(timeOut);
940 session.setServerAliveCountMax(
941 0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
942 channel = session.openChannel("subsystem");
943 ((ChannelSubsystem) channel).setSubsystem(subsystem);
944 // ((ChannelSubsystem)channel).setPtyType("vt102");
945 ((ChannelSubsystem) channel).setPty(true);
947 inputStream = channel.getInputStream();
948 dis = new DataInputStream(inputStream);
949 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
951 debugLog.printRTAriDebug(fn, "Successfully connected.");
952 debugLog.printRTAriDebug(fn, "Five second sleep....");
955 } catch (java.lang.InterruptedException ee) {
956 boolean ignore = true;
958 } catch (Exception e) {
959 debugLog.printRTAriDebug(fn, "Caught an Exception. e=" + e);
960 throw new IOException(e.toString());
964 public void connect(String hostName, String username, String password, int portNumber) throws IOException {
965 String fn = "SshJcraftWrapper.connect";
967 debugLog.printRTAriDebug(fn,
968 "::Attempting to connect to " + hostName + " username=" + username + " password=" + password
969 + " portNumber=" + portNumber);
970 debugLog.printRTAriDebug(fn, "Trace C");
971 RouterName = hostName;
972 this.hostName = hostName;
976 java.util.Properties config = new java.util.Properties();
977 config.put("StrictHostKeyChecking", "no");
978 session = jsch.getSession(username, hostName, 22);
979 // session = jsch.getSession(username, hostName, portNumber);
980 UserInfo ui = new MyUserInfo();
981 session.setConfig(config);
982 session.setPassword(password);
983 session.setUserInfo(ui);
984 session.connect(30000);
985 channel = session.openChannel("shell");
986 session.setServerAliveCountMax(
987 0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
988 ((ChannelShell) channel).setPtyType("vt102");
989 inputStream = channel.getInputStream();
990 dis = new DataInputStream(inputStream);
991 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
993 debugLog.printRTAriDebug(fn, "::Successfully connected.");
994 debugLog.printRTAriDebug(fn, "::Flushing input buffer");
996 receiveUntil(":~#", 9000, "No cmd was sent, just waiting, but we can stop on a '~#'");
997 } catch (Exception e) {
998 debugLog.printRTAriDebug(fn, "Caught an Exception::: Nothing to flush out.");
1001 } catch (Exception e) {
1002 debugLog.printRTAriDebug(fn, "Caught an Exception. e=" + e);
1003 // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostName +" "+e);
1004 throw new IOException(e.toString());
1009 public void put(String sourcePath, String destDirectory) throws IOException {
1010 String fn = "SshJcraftWrapper.sftp";
1012 Session sftpSession = jsch.getSession(userName, hostName, 22);
1013 UserInfo ui = new MyUserInfo();
1014 sftpSession.setPassword(passWord);
1015 sftpSession.setUserInfo(ui);
1016 sftpSession.connect(30 * 1000);
1017 debugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
1018 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
1019 debugLog.printRTAriDebug(fn, "Connecting....");
1021 debugLog.printRTAriDebug(fn, "Sending " + sourcePath + " --> " + destDirectory);
1022 sftp.put(sourcePath, destDirectory, ChannelSftp.OVERWRITE);
1023 debugLog.printRTAriDebug(fn, "Sent successfully");
1024 sftpSession.disconnect();
1025 } catch (Exception e) {
1026 debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
1027 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
1028 throw new IOException(e.toString());
1032 public void put(InputStream is, String fullPathDest, String hostName, String userName, String passWord)
1033 throws IOException {
1034 String fn = "SshJcraftWrapper.put";
1035 Session sftpSession = null;
1037 debugLog.printRTAriDebug(fn, "userName=" + userName + " hostName=" + hostName + " passWord=" + passWord);
1039 java.util.Properties config = new java.util.Properties();
1040 config.put("StrictHostKeyChecking", "no");
1041 sftpSession = jsch.getSession(userName, hostName, 22);
1042 UserInfo ui = new MyUserInfo();
1043 sftpSession.setPassword(passWord);
1044 sftpSession.setUserInfo(ui);
1045 sftpSession.setConfig(config);
1046 sftpSession.connect(30 * 1000);
1047 debugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
1048 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
1049 debugLog.printRTAriDebug(fn, "Connecting....");
1051 String oldFiles = fullPathDest + "*";
1052 debugLog.printRTAriDebug(fn, "Deleting old files --> " + oldFiles);
1055 debugLog.printRTAriDebug(fn, "Sending stringOfData --> " + fullPathDest);
1056 } catch (SftpException sft) {
1057 String exp = "No such file";
1058 if (sft.getMessage() != null && sft.getMessage().contains(exp)) {
1059 debugLog.printRTAriDebug(fn, "No files found -- Continue");
1061 debugLog.printRTAriDebug(fn, "Exception while sftp.rm " + sft.getMessage());
1062 sft.printStackTrace();
1066 sftp.put(is, fullPathDest, ChannelSftp.OVERWRITE);
1067 debugLog.printRTAriDebug(fn, "Sent successfully");
1068 sftpSession.disconnect();
1070 } catch (Exception e) {
1071 debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
1072 sftpSession.disconnect();
1074 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
1075 throw new IOException(e.toString());
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());