2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 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 * ============LICENSE_END=========================================================
24 package org.onap.appc.ccadaptor;
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
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 java.util.concurrent.TimeUnit;
58 import javax.annotation.Nonnull;
59 import org.apache.commons.lang.StringUtils;
60 import org.onap.appc.i18n.Msg;
62 public class SshJcraftWrapper {
64 InputStream inputStream = null;
65 OutputStream outputStream = null;
66 DebugLog debugLog = new DebugLog();
67 private String debugLogFileName = "/tmp/sshJcraftWrapperDebug";
68 private TelnetListener listener = null;
69 private String routerLogFileName = null;
70 private String host = null;
71 private String RouterName = null;
72 private int BUFFER_SIZE = 512000;
73 char[] charBuffer = new char[BUFFER_SIZE];
74 // private int BUFFER_SIZE = 4000000;
75 private DataInputStream dis = null;
76 private BufferedReader reader = null;
77 private BufferedWriter out = null;
78 private File _tmpFile = null;
79 private JSch jsch = null;
80 private Session session = null;
81 private Channel channel = null;
82 private String tId = "";
83 private String aggregatedReceivedString = "";
84 private File extraDebugFile = new File("/tmp/sshJcraftWrapperDEBUG");
85 private String routerCmdType = "XML";
86 private String routerFileName = null;
87 private File jcraftReadSwConfigFileFromDisk = new File("/tmp/jcraftReadSwConfigFileFromDisk");
88 private String equipNameCode = null;
89 private String hostName = null;
90 private String userName = null;
91 private String passWord = null;
92 private StringBuffer charactersFromBufferFlush = new StringBuffer();
93 private Runtime runtime = Runtime.getRuntime();
94 private DebugLog dbLog = new DebugLog();
96 public void SshJcraftWrapper() {
97 String fn = "SshJcraftWrapper.SshJcraftWrapper";
98 debugLog.printRTAriDebug(fn, "SshJcraftWrapper has been instantated");
99 routerLogFileName = "/tmp/" + host;
103 public void connect(String hostname, String username, String password, String prompt, int timeOut)
105 String fn = "SshJcraftWrapper.connect";
107 debugLog.printRTAriDebug(fn,
108 "Attempting to connect to " + hostname + " username=" + username + " prompt='"
109 + prompt + "' timeOut=" + timeOut);
110 debugLog.printRTAriDebug(fn, "Trace A");
111 RouterName = hostname;
116 session = jsch.getSession(username, hostname, 22);
117 UserInfo ui = new MyUserInfo();
118 session.setPassword(password);
119 session.setUserInfo(ui);
120 session.connect(timeOut);
121 channel = session.openChannel("shell");
122 session.setServerAliveCountMax(
123 0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
124 ((ChannelShell) channel).setPtyType("vt102");
125 inputStream = channel.getInputStream();
126 dis = new DataInputStream(inputStream);
127 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
129 debugLog.printRTAriDebug(fn, "Successfully connected.");
130 debugLog.printRTAriDebug(fn, "Flushing input buffer");
132 receiveUntil(prompt, 3000, "No cmd was sent, just waiting");
133 } catch (Exception e) {
134 debugLog.printRTAriDebug(fn, "Caught an Exception: Nothing to flush out.");
136 } catch (Exception e) {
137 debugLog.printRTAriDebug(fn, "Caught an Exception. e=" + e);
138 // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostname +" "+e);
139 throw new IOException(e.toString());
143 // User specifies the port number.
144 public void connect(String hostname, String username, String password, String prompt, int timeOut, int portNum)
146 String fn = "SshJcraftWrapper.connect";
147 debugLog.printRTAriDebug(fn,
148 ":Attempting to connect to " + hostname + " username=" + username + " prompt='"
149 + prompt + "' timeOut=" + timeOut + " portNum=" + portNum);
150 RouterName = hostname;
154 RouterName = hostname;
157 session = jsch.getSession(username, hostname, portNum);
158 UserInfo ui = new MyUserInfo();
159 session.setPassword(password);
160 session.setUserInfo(ui);
161 session.setConfig("StrictHostKeyChecking", "no");
162 debugLog.printRTAriDebug(fn, ":StrictHostKeyChecking set to 'no'");
164 session.connect(timeOut);
165 session.setServerAliveCountMax(
166 0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
167 channel = session.openChannel("shell");
168 ((ChannelShell) channel).setPtyType("vt102");
169 inputStream = channel.getInputStream();
170 dis = new DataInputStream(inputStream);
171 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
173 debugLog.printRTAriDebug(fn, ":Successfully connected.");
174 debugLog.printRTAriDebug(fn, ":Flushing input buffer");
176 if (prompt.equals("]]>]]>")) {
177 receiveUntil("]]>]]>", 10000, "No cmd was sent, just waiting");
179 receiveUntil(":~#", 5000, "No cmd was sent, just waiting");
181 } catch (Exception e) {
182 debugLog.printRTAriDebug(fn, "Caught an Exception::: Nothing to flush out.");
184 } catch (Exception e) {
185 debugLog.printRTAriDebug(fn, ":Caught an Exception. e=" + e);
186 dbLog.outputStackTrace(e);
188 // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostname +" "+e);
189 throw new IOException(e.toString());
194 public String receiveUntil(String delimeters, int timeout, String cmdThatWasSent)
195 throws TimedOutException, IOException {
196 String fn = "SshJcraftWrapper.receiveUntil";
197 boolean match = false;
198 boolean cliPromptCmd = false;
199 StringBuffer sb2 = new StringBuffer();
200 StringBuffer sbReceive = new StringBuffer();
201 debugLog.printRTAriDebug(fn,
202 "delimeters='" + delimeters + "' timeout=" + timeout + " cmdThatWasSent='" + cmdThatWasSent + "'");
203 appendToFile(debugLogFileName,
204 fn + " delimeters='" + delimeters + "' timeout=" + timeout + " cmdThatWasSent='" + cmdThatWasSent + "'\n");
205 String CmdThatWasSent = removeWhiteSpaceAndNewLineCharactersAroundString(cmdThatWasSent);
207 aggregatedReceivedString = "";
208 FileWriter fileWriter = null;
210 long deadline = new Date().getTime() + timeout;
212 session.setTimeout(timeout); // This is the socket timeout value.
214 if (new Date().getTime() > deadline) {
215 debugLog.printRTAriDebug(fn,
216 "Throwing a TimedOutException: time in routine has exceed our deadline: RouterName:"
217 + RouterName + " CmdThatWasSent=" + CmdThatWasSent);
218 throw new TimedOutException("Timeout: time in routine has exceed our deadline");
222 } catch (java.lang.InterruptedException ee) {
223 boolean ignore = true;
225 int len = reader.read(charBuffer, 0, BUFFER_SIZE);
226 appendToFile(debugLogFileName, fn + " After reader.read cmd: len=" + len + "\n");
228 debugLog.printRTAriDebug(fn,
229 "Reader read " + len + " bytes. Looks like we timed out, router=" + RouterName);
230 throw new TimedOutException("Received a SocketTimeoutException router=" + RouterName);
233 if (cmdThatWasSent.indexOf("IOS_XR_uploadedSwConfigCmd") != -1) {
235 // This is a IOS XR sw config file. We will write it to the disk.
236 timeout = timeout * 2;
237 deadline = new Date().getTime() + timeout;
238 debugLog.printRTAriDebug(fn, "IOS XR upload for software config: timeout=" + timeout);
239 StringTokenizer st = new StringTokenizer(cmdThatWasSent);
241 routerFileName = st.nextToken();
242 fileWriter = new FileWriter(routerFileName);
243 out = new BufferedWriter(fileWriter);
244 routerLogFileName = "/tmp/" + RouterName;
245 _tmpFile = new File(routerLogFileName);
246 debugLog.printRTAriDebug(fn,
247 "Will write the swConfigFile to disk, routerFileName=" + routerFileName);
250 out.write(charBuffer, 0, len);
252 appendToFile(debugLogFileName, fn + " Wrote " + len + " bytes to the disk\n");
253 if (_tmpFile.exists()) {
254 appendToRouterFile(routerLogFileName, len);
256 match = checkIfReceivedStringMatchesDelimeter(len, "\nXML>");
265 appendToFile(debugLogFileName,
266 fn + " readCounts=" + readCounts + " Reader read " + len + " of data\n");
269 for (int i = 0; i < len; i++) {
271 if ((c != 7) && (c != 13) && (c != 0) && (c != 27)) {
272 sbReceive.append((char) charBuffer[i]);
273 sb2.append((char) charBuffer[i]);
276 appendToRouterFile("/tmp/" + RouterName, len);
277 if (listener != null) {
278 listener.receivedString(sb2.toString());
281 appendToFile(debugLogFileName, fn + " Trace 1\n");
282 match = checkIfReceivedStringMatchesDelimeter(delimeters, sb2.toString(), cmdThatWasSent);
283 appendToFile(debugLogFileName, fn + " Trace 2\n");
285 appendToFile(debugLogFileName, fn + " Match was true, breaking...\n");
290 debugLog.printRTAriDebug(fn, "cliPromptCmd, Trace 2");
292 for (int i = 0; i < len; i++) {
293 sbReceive.append((char) charBuffer[i]);
294 sb2.append((char) charBuffer[i]);
296 appendToRouterFile("/tmp/" + RouterName, sb2);
297 if (listener != null) {
298 listener.receivedString(sb2.toString());
300 debugLog.printRTAriDebug(fn, "sb2='" + sb2.toString() + "' delimeters='" + delimeters + "'");
301 if (sb2.toString().indexOf("\nariPrompt>") != -1) {
302 debugLog.printRTAriDebug(fn, "Found our prompt");
308 } catch (JSchException e) {
309 debugLog.printRTAriDebug(fn, "Caught an JSchException e=" + e.toString());
310 dbLog.outputStackTrace(e);
311 throw new TimedOutException(e.toString());
312 } catch (IOException ee) {
313 debugLog.printRTAriDebug(fn, "Caught an IOException: ee=" + ee.toString());
314 dbLog.outputStackTrace(ee);
315 throw new TimedOutException(ee.toString());
318 if (fileWriter != null) {
321 } catch(IOException ex) {
322 debugLog.printRTAriDebug(fn, "Failed to close fileWriter output stream: ex=" + ex);
325 String result = stripOffCmdFromRouterResponse(sbReceive.toString());
326 debugLog.printRTAriDebug(fn, "Leaving method successfully");
330 public boolean checkIfReceivedStringMatchesDelimeter(String delimeters, String receivedString,
331 String cmdThatWasSent) {
332 // The delimeters are in a '|' seperated string. Return true on the first match.
333 String fn = "SshJcraftWrapper.checkIfReceivedStringMatchesDelimeter";
334 appendToFile(debugLogFileName,
335 fn + " Entered: delimeters='" + delimeters + " cmdThatWasSent='" + cmdThatWasSent + "' receivedString='"
336 + receivedString + "'\n");
337 StringTokenizer st = new StringTokenizer(delimeters, "|");
339 if ((delimeters.indexOf("#$") != -1) || (routerCmdType.equals("CLI"))) // This would be an IOS XR, CLI command.
341 int x = receivedString.lastIndexOf("#");
342 int y = receivedString.length() - 1;
343 appendToFile(debugLogFileName, fn + " IOS XR, CLI command\n");
344 if (extraDebugFile.exists()) {
345 appendToFile(debugLogFileName,
346 fn + " :::cmdThatWasSent='" + cmdThatWasSent + "' x=" + x + " y=" + y + "\n");
348 return (x != -1) && (y == x);
350 if (cmdThatWasSent.indexOf("show config") != -1) {
351 appendToFile(debugLogFileName, fn + "In the block for 'show config'\n");
352 while (st.hasMoreTokens()) {
353 String delimeter = st.nextToken();
354 // Make sure we don't get faked out by a response of " #".
356 // # signaling-local-address ipv6 FD00:F4D5:EA06:1::110:136:254
358 int x = receivedString.lastIndexOf(delimeter);
359 if ((receivedString.lastIndexOf(delimeter) != -1) && (receivedString.lastIndexOf(" #") != x - 1)) {
360 appendToFile(debugLogFileName, fn + "receivedString=\n'" + receivedString + "'\n");
361 appendToFile(debugLogFileName,
362 fn + "Returning true for the 'show config' command. We found our real delmeter. \n\n");
367 aggregatedReceivedString = aggregatedReceivedString + receivedString;
368 _appendToFile("/tmp/aggregatedReceivedString.debug", aggregatedReceivedString);
370 while (st.hasMoreTokens()) {
371 String delimeter = st.nextToken();
372 appendToFile(debugLogFileName, fn + " Looking for an delimeter of:'" + delimeter + "'\n");
373 appendToFile(debugLogFileName, fn + " receivedString='" + receivedString);
374 if (aggregatedReceivedString.indexOf(delimeter) != -1) {
375 debugLog.printRTAriDebug(fn, "Found our delimeter, which was: '" + delimeter + "'");
376 aggregatedReceivedString = "";
384 public boolean checkIfReceivedStringMatchesDelimeter(int len, String delimeter) {
385 String fnName = "SshJcraftWrapper.checkIfReceivedStringMatchesDelimeter:::";
388 String str = StringUtils.EMPTY;
390 if (jcraftReadSwConfigFileFromDisk()) {
391 DebugLog.printAriDebug(fnName, "jcraftReadSwConfigFileFromDisk block");
392 File fileName = new File(routerFileName);
393 appendToFile(debugLogFileName,
394 fnName + " jcraftReadSwConfigFileFromDisk::: Will read the tail end of the file from the disk");
396 str = getLastFewLinesOfFile(fileName, 3);
397 } catch (IOException e) {
398 DebugLog.printAriDebug(fnName, "Caught an Exception, e=" + e);
399 dbLog.outputStackTrace(e);
403 // DebugLog.printAriDebug(fnName, "TRACE 1: ******************************");
404 // When looking at the end of the charBuffer, don't include any linefeeds or spaces. We only want to make the smallest string possible.
405 for (x = len - 1; x >= 0; x--) {
407 if (extraDebugFile.exists()) {
408 appendToFile(debugLogFileName, fnName + " x=" + x + " c=" + c + "\n");
410 if ((c != 10) && (c != 32)) // Not a line feed nor a space.
415 if ((x + 1 - 13) >= 0) {
416 str = new String(charBuffer, (x + 1 - 13), 13);
417 appendToFile(debugLogFileName, fnName + " str:'" + str + "'\n");
419 File fileName = new File(routerFileName);
420 appendToFile(debugLogFileName,
421 fnName + " Will read the tail end of the file from the disk, x=" + x + " len=" + len + " str::'"
422 + str + "' routerFileName='" + routerFileName + "'\n");
423 DebugLog.printAriDebug(fnName,
424 "Will read the tail end of the file from the disk, x=" + x + " len=" + len + " str::'" + str
425 + "' routerFileName='" + routerFileName + "'");
427 str = getLastFewLinesOfFile(fileName, 3);
428 } catch (IOException e) {
429 DebugLog.printAriDebug(fnName, "Caught an Exception, e=" + e);
430 dbLog.outputStackTrace(e);
436 if (str.indexOf(delimeter) != -1) {
437 DebugLog.printAriDebug(fnName, "str in break is:'" + str + "'" + " delimeter='" + delimeter + "'");
438 appendToFile(debugLogFileName,
439 fnName + " str in break is:'" + str + " delimeter='" + delimeter + "'" + "'\n");
442 appendToFile(debugLogFileName, fnName + " Returning false");
448 public void closeConnection() {
449 String fn = "SshJcraftWrapper.closeConnection";
450 debugLog.printRTAriDebug(fn, "Executing the closeConnection....");
455 session.disconnect();
459 public void send(String cmd) throws IOException {
460 String fn = "SshJcraftWrapper.send";
461 OutputStream out = channel.getOutputStream();
462 DataOutputStream dos = new DataOutputStream(out);
464 if ((cmd.charAt(cmd.length() - 1) != '\n') && (cmd.charAt(cmd.length() - 1) != '\r')) {
467 int length = cmd.length();
470 int ncharsTotalSent = 0;
473 appendToFile(debugLogFileName, fn + ": Sending: '" + cmd);
474 // debugLog.printRTAriDebug (fn, "cmd = "+cmd);
475 debugLog.printRTAriDebug(fn, "Length of cmd is:" + length); // 2,937,706
477 if (length > 600000) {
479 for (i = 0; i < length; i += nchars) {
480 String Cmd = cmd.substring(i, Math.min(length, i + nchars));
481 ncharsSent = Cmd.length();
482 ncharsTotalSent = ncharsTotalSent + Cmd.length();
483 debugLog.printRTAriDebug(fn, "i=" + i + " Sending Cmd: ncharsSent=" + ncharsSent);
487 debugLog.printRTAriDebug(fn, ":::i=" + i + " length=" + length);
488 if (ncharsSent < length) {
489 receiveUntilBufferFlush(ncharsSent, timeout, "buffer flush i=" + i);
491 debugLog.printRTAriDebug(fn, "i=" + i + " No Waiting this time....");
494 } catch (Exception e) {
495 debugLog.printRTAriDebug(fn, "Caught an Exception: Nothing to flush out.");
499 debugLog.printRTAriDebug(fn, "Before executing the dos.writeBytes");
503 debugLog.printRTAriDebug(fn, "Leaving method");
504 appendToFile(debugLogFileName, fn + ": Leaving method\n");
505 } catch (IOException e) {
506 debugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e);
507 dbLog.outputStackTrace(e);
508 throw new IOException(e.toString());
513 public void sendChar(int v) throws IOException {
514 String fn = "SshJcraftWrapper.sendChar";
515 OutputStream out = channel.getOutputStream();
516 DataOutputStream dos = new DataOutputStream(out);
518 debugLog.printRTAriDebug(fn, "Sending: '" + v + "'");
521 } catch (IOException e) {
522 debugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e);
523 throw new IOException(e.toString());
527 public void send(byte[] b, int off, int len) throws IOException {
528 String fn = "SshJcraftWrapper.send:byte[]";
529 OutputStream out = channel.getOutputStream();
530 DataOutputStream dos = new DataOutputStream(out);
532 dos.write(b, off, len);
534 } catch (IOException e) {
535 debugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e);
536 throw new IOException(e.toString());
540 public static class MyUserInfo implements UserInfo, UIKeyboardInteractive {
542 public String getPassword() {
546 public boolean promptYesNo(String str) {
550 public String getPassphrase() {
554 public boolean promptPassphrase(String message) {
558 public boolean promptPassword(String message) {
562 public void showMessage(String message) {
565 public String[] promptKeyboardInteractive(String destination,
574 public void addListener(TelnetListener listener) {
575 this.listener = listener;
578 public void appendToFile(String fileName, String dataToWrite) {
579 String fn = "SshJcraftWrapper.appendToFile";
582 // First check to see if a file 'fileName' exist, if it does
583 // write to it. If it does not exist, don't write to it.
584 File tmpFile = new File(fileName);
585 if (tmpFile.exists()) {
586 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
587 // out.write(dataToWrite);
588 // out.write(getTheDate() +": " +Thread.currentThread().getName() +": "+dataToWrite);
589 out.write(getTheDate() + ": " + tId + ": " + dataToWrite);
592 } catch (IOException e) {
593 debugLog.printRTAriDebug(fn, "Caught an IOException: e=" + e);
594 } catch (Exception e) {
595 debugLog.printRTAriDebug(fn, "Caught an Exception: e=" + e);
599 public void _appendToFile(String fileName, String dataToWrite) {
600 String fn = "SshJcraftWrapper.appendToFile";
603 // First check to see if a file 'fileName' exist, if it does
604 // write to it. If it does not exist, don't write to it.
605 File tmpFile = new File(fileName);
606 if (tmpFile.exists()) {
607 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
608 out.write(dataToWrite);
611 } catch (IOException e) {
612 debugLog.printRTAriDebug(fn, "Caught an IOException: e=" + e);
613 } catch (Exception e) {
614 debugLog.printRTAriDebug(fn, "Caught an Exception: e=" + e);
619 public String getTheDate() {
620 Calendar cal = Calendar.getInstance();
621 java.util.Date today = cal.getTime();
622 DateFormat df1 = DateFormat.getDateInstance();
623 DateFormat df3 = new SimpleDateFormat("MM/dd/yyyy H:mm:ss ");
624 return (df3.format(today));
628 public void appendToRouterFile(String fileName, StringBuffer dataToWrite) {
629 String fnName = "SshJcraftWrapper.appendToRouterFile";
630 debugLog.printRTAriDebug(fnName, "Entered.... ");
632 // First check to see if a file 'fileName' exist, if it does
633 // write to it. If it does not exist, don't write to it.
634 File tmpFile = new File(fileName);
636 // if ((tmpFile.exists()) && (tmpFile.setWritable(true, true)))
637 if (tmpFile.exists()) {
638 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
639 // out.write("<!-- "+getTheDate() +": " +tId +" -->\n");
640 out.write(dataToWrite.toString());
644 } catch (IOException e) {
645 System.err.println("writeToFile() exception: " + e);
650 public void appendToRouterFile(String fileName, int len) {
651 String fnName = "SshJcraftWrapper.appendToFile";
652 // debugLog.printRTAriDebug (fnName, "Entered.... len="+len);
654 // First check to see if a file 'fileName' exist, if it does
655 // write to it. If it does not exist, don't write to it.
656 File tmpFile = new File(fileName);
657 // if ((tmpFile.exists()) && (tmpFile.setWritable(true, true)))
658 if (tmpFile.exists()) {
659 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
660 // out.write("<!-- "+getTheDate() +": " +tId +" -->\n");
661 out.write(charBuffer, 0, len);
664 } catch (IOException e) {
665 System.err.println("writeToFile() exception: " + e);
670 public String removeWhiteSpaceAndNewLineCharactersAroundString(String str) {
672 StringTokenizer strTok = new StringTokenizer(str, "\n");
673 StringBuffer sb = new StringBuffer();
675 while (strTok.hasMoreTokens()) {
676 String line = strTok.nextToken();
679 return (sb.toString().trim());
685 public String stripOffCmdFromRouterResponse(String routerResponse) {
686 String fn = "SshJcraftWrapper.stripOffCmdFromRouterResponse";
687 // appendToFile(debugLogFileName, fn+": routerResponse='"+routerResponse +"'\n");
689 // The session of SSH will echo the command sent to the router, in the router's response.
690 // Since all our commands are terminated by a '\n', strip off the first line
691 // of the response from the router. This first line contains the orginal command.
693 StringTokenizer rr = new StringTokenizer(routerResponse, "\n");
694 StringBuffer sb = new StringBuffer();
696 int numTokens = rr.countTokens();
697 // debugLog.printRTAriDebug (fn, "Number of lines in the response from the router is:" +numTokens);
699 rr.nextToken(); //Skip the first line.
700 while (rr.hasMoreTokens()) {
701 sb.append(rr.nextToken() + '\n');
704 return (sb.toString());
707 public void setRouterCommandType(String type) {
708 String fn = "SshJcraftWrapper.setRouterCommandType";
709 this.routerCmdType = type;
710 debugLog.printRTAriDebug(fn, "Setting routerCmdType to a value of '" + type + "'");
713 public String getLastFewLinesOfFile(File file, int linesToRead) throws IOException {
714 String fn = "SshJcraftWrapper.getLastFewLinesOfFile";
715 RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
717 StringBuilder builder = new StringBuilder();
719 long length = file.length();
721 randomAccessFile.seek(length);
722 for (long seek = length; seek >= 0; --seek) {
723 randomAccessFile.seek(seek);
724 char c = (char) randomAccessFile.read();
727 builder = builder.reverse();
728 // System.out.println(builder.toString());
729 tail = builder.toString() + tail;
731 builder.setLength(0);
732 if (lines == linesToRead) {
737 randomAccessFile.close();
738 if (!jcraftReadSwConfigFileFromDisk()) {
739 debugLog.printRTAriDebug(fn, "tail='" + tail + "'");
741 appendToFile(debugLogFileName, "tail='" + tail + "'\n");
745 public boolean jcraftReadSwConfigFileFromDisk() {
746 if (jcraftReadSwConfigFileFromDisk.exists()) {
753 public String getEquipNameCode() {
754 return (equipNameCode);
758 public void setEquipNameCode(String equipNameCode) {
759 this.equipNameCode = equipNameCode;
762 public String getRouterName() {
766 // Routine does reads until it has read 'nchars' or times out.
767 public void receiveUntilBufferFlush(int ncharsSent, int timeout, String message)
768 throws TimedOutException, IOException {
769 String fn = "SshJcraftWrapper.receiveUntilBufferFlush";
770 StringBuffer sb2 = new StringBuffer();
771 StringBuffer sbReceive = new StringBuffer();
772 debugLog.printRTAriDebug(fn, "ncharsSent=" + ncharsSent + " timeout=" + timeout + " " + message);
773 int ncharsTotalReceived = 0;
775 boolean flag = false;
776 charactersFromBufferFlush.setLength(0);
778 long deadline = new Date().getTime() + timeout;
781 session.setTimeout(timeout); // This is the socket timeout value.
783 if (new Date().getTime() > deadline) {
784 debugLog.printRTAriDebug(fn,
785 "Throwing a TimedOutException: time in routine has exceed our deadline: ncharsSent="
786 + ncharsSent + " ncharsTotalReceived=" + ncharsTotalReceived);
788 throw new TimedOutException("Timeout: time in routine has exceed our deadline");
790 ncharsRead = reader.read(charBuffer, 0, BUFFER_SIZE);
791 if (listener != null) {
792 listener.receivedString(String.copyValueOf(charBuffer, 0, ncharsRead));
794 appendToRouterFile("/tmp/" + RouterName, ncharsRead);
795 ncharsTotalReceived = ncharsTotalReceived + ncharsRead;
796 // debugLog.printRTAriDebug (fn, "::ncharsSent="+ncharsSent+" ncharsTotalReceived="+ncharsTotalReceived +" ncharsRead="+ncharsRead);
797 if (ncharsTotalReceived >= ncharsSent) {
798 debugLog.printRTAriDebug(fn,
799 "Received the correct number of characters, ncharsSent=" + ncharsSent + " ncharsTotalReceived="
800 + ncharsTotalReceived);
805 } catch (JSchException e) {
806 debugLog.printRTAriDebug(fn, "Caught an JSchException e=" + e);
807 debugLog.printRTAriDebug(fn,
808 "ncharsSent=" + ncharsSent + " ncharsTotalReceived=" + ncharsTotalReceived + " ncharsRead="
810 throw new TimedOutException(e.toString());
814 public String getHostName() {
818 public String getUserName() {
822 public String getPassWord() {
826 public void sftpPut(String sourcePath, String destDirectory) throws IOException {
827 String fn = "SshJcraftWrapper.sftp";
829 Session sftpSession = jsch.getSession(userName, hostName, 22);
830 UserInfo ui = new MyUserInfo();
831 sftpSession.setPassword(passWord);
832 sftpSession.setUserInfo(ui);
833 sftpSession.connect(30 * 1000);
834 debugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
835 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
836 debugLog.printRTAriDebug(fn, "Connecting....");
838 debugLog.printRTAriDebug(fn, "Sending " + sourcePath + " --> " + destDirectory);
839 sftp.put(sourcePath, destDirectory, ChannelSftp.OVERWRITE);
840 debugLog.printRTAriDebug(fn, "Sent successfully");
841 sftpSession.disconnect();
842 } catch (Exception e) {
843 debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
844 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
845 throw new IOException(e.toString());
850 public void SftpPut(String stringOfData, String fullPathDest) throws IOException {
851 String fn = "SshJcraftWrapper.Sftp";
853 Session sftpSession = jsch.getSession(userName, hostName, 22);
854 UserInfo ui = new MyUserInfo();
855 sftpSession.setPassword(passWord);
856 sftpSession.setUserInfo(ui);
857 sftpSession.connect(30 * 1000);
858 debugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
859 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
860 debugLog.printRTAriDebug(fn, "Connecting....");
862 InputStream is = new ByteArrayInputStream(stringOfData.getBytes());
863 debugLog.printRTAriDebug(fn, "Sending stringOfData --> " + fullPathDest);
864 sftp.put(is, fullPathDest, ChannelSftp.OVERWRITE);
865 debugLog.printRTAriDebug(fn, "Sent successfully");
866 sftpSession.disconnect();
867 } catch (Exception e) {
868 debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
869 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
870 throw new IOException(e.toString());
874 public String sftpGet(String fullFilePathName) throws IOException {
875 String fn = "SshJcraftWrapper.Sftp";
877 Session sftpSession = jsch.getSession(userName, hostName, 22);
878 UserInfo ui = new MyUserInfo();
879 sftpSession.setPassword(passWord);
880 sftpSession.setUserInfo(ui);
881 sftpSession.connect(30 * 1000);
882 debugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
883 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
884 debugLog.printRTAriDebug(fn, "Connecting....");
886 InputStream in = null;
887 in = sftp.get(fullFilePathName);
888 String sftpFileString = readInputStreamAsString(in);
889 debugLog.printRTAriDebug(fn, "Retreived successfully");
890 // debugLog.printRTAriDebug (fn, "sftpFileString="+sftpFileString);
891 sftpSession.disconnect();
892 return (sftpFileString);
893 } catch (Exception e) {
894 debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
895 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
896 throw new IOException(e.toString());
900 public static String readInputStreamAsString(InputStream in) throws IOException {
901 BufferedInputStream bis = new BufferedInputStream(in);
902 ByteArrayOutputStream buf = new ByteArrayOutputStream();
903 int result = bis.read();
904 while (result != -1) {
905 byte b = (byte) result;
909 return buf.toString();
913 public void logMemoryUsage() {
914 String fn = "SshJcraftWrapper.logMemoryUsage";
915 int mb = 1024 * 1024;
917 long maxMemoryAdvailable;
918 long memoryLetfOnHeap;
919 maxMemoryAdvailable = (runtime.maxMemory() / mb);
920 usedMemory = ((runtime.totalMemory() / mb) - (runtime.freeMemory() / mb));
921 memoryLetfOnHeap = maxMemoryAdvailable - usedMemory;
922 DebugLog.printAriDebug(fn,
923 "maxMemoryAdvailable=" + maxMemoryAdvailable + " usedMemory=" + usedMemory + " memoryLetfOnHeap="
927 // ----------------------------------------------------------------------------
928 // ----------------------------------------------------------------------------
929 // ----------------------------------------------------------------------------
930 // ----------------------------------------------------------------------------
933 // User specifies the port number, and the subsystem
934 public void connect(String hostname, String username, String password, String prompt, int timeOut, int portNum,
935 String subsystem) throws IOException {
936 String fn = "SshJcraftWrapper.connect";
938 debugLog.printRTAriDebug(fn,
939 ":::Attempting to connect to " + hostname + " username=" + username + " prompt='"
940 + prompt + "' timeOut=" + timeOut + " portNum=" + portNum + " subsystem=" + subsystem);
941 RouterName = hostname;
944 session = jsch.getSession(username, hostname, portNum);
945 UserInfo ui = new MyUserInfo();
946 session.setPassword(password);
947 session.setUserInfo(ui);
948 session.setConfig("StrictHostKeyChecking", "no");
949 session.connect(timeOut);
950 session.setServerAliveCountMax(
951 0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
952 channel = session.openChannel("subsystem");
953 ((ChannelSubsystem) channel).setSubsystem(subsystem);
954 // ((ChannelSubsystem)channel).setPtyType("vt102");
955 ((ChannelSubsystem) channel).setPty(true);
957 inputStream = channel.getInputStream();
958 dis = new DataInputStream(inputStream);
959 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
961 debugLog.printRTAriDebug(fn, "Successfully connected.");
962 debugLog.printRTAriDebug(fn, "Five second sleep....");
965 } catch (java.lang.InterruptedException ee) {
966 boolean ignore = true;
968 } catch (Exception e) {
969 debugLog.printRTAriDebug(fn, "Caught an Exception. e=" + e);
970 throw new IOException(e.toString());
974 public void connect(String hostName, String username, String password, int portNumber) throws IOException {
975 String fn = "SshJcraftWrapper.connect";
977 debugLog.printRTAriDebug(fn,
978 "::Attempting to connect to " + hostName + " username=" + username + " portNumber=" + portNumber);
979 debugLog.printRTAriDebug(fn, "Trace C");
980 RouterName = hostName;
981 this.hostName = hostName;
985 java.util.Properties config = new java.util.Properties();
986 config.put("StrictHostKeyChecking", "no");
987 session = jsch.getSession(username, hostName, 22);
988 // session = jsch.getSession(username, hostName, portNumber);
989 UserInfo ui = new MyUserInfo();
990 session.setConfig(config);
991 session.setPassword(password);
992 session.setUserInfo(ui);
993 session.connect(30000);
994 channel = session.openChannel("shell");
995 session.setServerAliveCountMax(
996 0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
997 ((ChannelShell) channel).setPtyType("vt102");
998 inputStream = channel.getInputStream();
999 dis = new DataInputStream(inputStream);
1000 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
1002 debugLog.printRTAriDebug(fn, "::Successfully connected.");
1003 debugLog.printRTAriDebug(fn, "::Flushing input buffer");
1005 receiveUntil(":~#", 9000, "No cmd was sent, just waiting, but we can stop on a '~#'");
1006 } catch (Exception e) {
1007 debugLog.printRTAriDebug(fn, "Caught an Exception::: Nothing to flush out.");
1010 } catch (Exception e) {
1011 debugLog.printRTAriDebug(fn, "Caught an Exception. e=" + e);
1012 // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostName +" "+e);
1013 throw new IOException(e.toString());
1018 public void put(String sourcePath, String destDirectory) throws IOException {
1019 String fn = "SshJcraftWrapper.sftp";
1021 Session sftpSession = jsch.getSession(userName, hostName, 22);
1022 UserInfo ui = new MyUserInfo();
1023 sftpSession.setPassword(passWord);
1024 sftpSession.setUserInfo(ui);
1025 sftpSession.connect(30 * 1000);
1026 debugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
1027 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
1028 debugLog.printRTAriDebug(fn, "Connecting....");
1030 debugLog.printRTAriDebug(fn, "Sending " + sourcePath + " --> " + destDirectory);
1031 sftp.put(sourcePath, destDirectory, ChannelSftp.OVERWRITE);
1032 debugLog.printRTAriDebug(fn, "Sent successfully");
1033 sftpSession.disconnect();
1034 } catch (Exception e) {
1035 debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
1036 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
1037 throw new IOException(e.toString());
1041 public void put(InputStream is, String fullPathDest, String hostName, String userName, String passWord)
1042 throws IOException {
1043 String fn = "SshJcraftWrapper.put";
1044 Session sftpSession = null;
1046 debugLog.printRTAriDebug(fn, "userName=" + userName + " hostName=" + hostName);
1048 java.util.Properties config = new java.util.Properties();
1049 config.put("StrictHostKeyChecking", "no");
1050 sftpSession = jsch.getSession(userName, hostName, 22);
1051 UserInfo ui = new MyUserInfo();
1052 sftpSession.setPassword(passWord);
1053 sftpSession.setUserInfo(ui);
1054 sftpSession.setConfig(config);
1055 sftpSession.connect(30 * 1000);
1056 debugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
1057 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
1058 debugLog.printRTAriDebug(fn, "Connecting....");
1060 String oldFiles = fullPathDest + "*";
1061 debugLog.printRTAriDebug(fn, "Deleting old files --> " + oldFiles);
1064 debugLog.printRTAriDebug(fn, "Sending stringOfData --> " + fullPathDest);
1065 } catch (SftpException sft) {
1066 String exp = "No such file";
1067 if (sft.getMessage() != null && sft.getMessage().contains(exp)) {
1068 debugLog.printRTAriDebug(fn, "No files found -- Continue");
1070 debugLog.printRTAriDebug(fn, "Exception while sftp.rm " + sft.getMessage());
1071 sft.printStackTrace();
1075 sftp.put(is, fullPathDest, ChannelSftp.OVERWRITE);
1076 debugLog.printRTAriDebug(fn, "Sent successfully");
1077 } catch (Exception e) {
1078 debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
1079 throw new IOException(e.toString());
1081 if(sftpSession != null) {
1082 sftpSession.disconnect();
1088 public String get(String fullFilePathName, String hostName, String userName, String passWord) throws IOException {
1089 String fn = "SshJcraftWrapper.get";
1090 Session sftpSession = null;
1092 debugLog.printRTAriDebug(fn, "userName=" + userName + " hostName=" + hostName);
1094 sftpSession = jsch.getSession(userName, hostName, 22);
1095 java.util.Properties config = new java.util.Properties();
1096 config.put("StrictHostKeyChecking", "no");
1097 UserInfo ui = new MyUserInfo();
1098 sftpSession.setPassword(passWord);
1099 sftpSession.setUserInfo(ui);
1100 sftpSession.setConfig(config);
1101 sftpSession.connect(30 * 1000);
1102 debugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
1103 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
1104 debugLog.printRTAriDebug(fn, "Connecting....");
1106 InputStream in = sftp.get(fullFilePathName);
1107 String sftpFileString = readInputStreamAsString(in);
1108 debugLog.printRTAriDebug(fn, "Retreived successfully");
1109 return sftpFileString;
1110 } catch (Exception e) {
1111 debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
1112 throw new IOException(e.toString());
1114 if(sftpSession != null) {
1115 sftpSession.disconnect();
1120 public String send(String cmd, String delimiter) throws IOException {
1121 String fn = "SshJcraftWrapper.send";
1122 OutputStream out = channel.getOutputStream();
1123 DataOutputStream dos = new DataOutputStream(out);
1125 if ((cmd.charAt(cmd.length() - 1) != '\n') && (cmd.charAt(cmd.length() - 1) != '\r')) {
1128 int length = cmd.length();
1130 int nchars = 300000;
1131 int ncharsTotalSent = 0;
1134 debugLog.printRTAriDebug(fn, "Length of cmd is:" + length); // 2,937,706
1135 debugLog.printRTAriDebug(fn, "Length of cmd is:" + length); // 2,937,706
1137 if (length > 600000) {
1139 for (i = 0; i < length; i += nchars) {
1140 String Cmd = cmd.substring(i, Math.min(length, i + nchars));
1141 ncharsSent = Cmd.length();
1142 ncharsTotalSent = ncharsTotalSent + Cmd.length();
1143 debugLog.printRTAriDebug(fn, "i=" + i + " Sending Cmd: ncharsSent=" + ncharsSent);
1144 dos.writeBytes(Cmd);
1147 debugLog.printRTAriDebug(fn, ":::i=" + i + " length=" + length);
1148 if (ncharsSent < length) {
1149 receiveUntilBufferFlush(ncharsSent, timeout, "buffer flush i=" + i);
1151 debugLog.printRTAriDebug(fn, "i=" + i + " No Waiting this time....");
1154 } catch (Exception e) {
1155 debugLog.printRTAriDebug(fn, "Caught an Exception: Nothing to flush out.");
1159 debugLog.printRTAriDebug(fn, "Before executing the dos.writeBytes");
1160 dos.writeBytes(cmd);
1163 // Now lets get the response.
1164 String response = receiveUntil(delimiter, 300000, cmd);
1165 debugLog.printRTAriDebug(fn, "Leaving method");
1167 } catch (IOException e) {
1168 debugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e);
1169 throw new IOException(e.toString());