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 = "";
205 FileWriter fileWriter = null;
207 long deadline = new Date().getTime() + timeout;
209 session.setTimeout(timeout); // This is the socket timeout value.
211 if (new Date().getTime() > deadline) {
212 debugLog.printRTAriDebug(fn,
213 "Throwing a TimedOutException: time in routine has exceed our deadline: RouterName:"
214 + RouterName + " CmdThatWasSent=" + CmdThatWasSent);
215 throw new TimedOutException("Timeout: time in routine has exceed our deadline");
219 } catch (java.lang.InterruptedException ee) {
220 boolean ignore = true;
222 int len = reader.read(charBuffer, 0, BUFFER_SIZE);
223 appendToFile(debugLogFileName, fn + " After reader.read cmd: len=" + len + "\n");
225 debugLog.printRTAriDebug(fn,
226 "Reader read " + len + " bytes. Looks like we timed out, router=" + RouterName);
227 throw new TimedOutException("Received a SocketTimeoutException router=" + RouterName);
230 if (cmdThatWasSent.indexOf("IOS_XR_uploadedSwConfigCmd") != -1) {
232 // This is a IOS XR sw config file. We will write it to the disk.
233 timeout = timeout * 2;
234 deadline = new Date().getTime() + timeout;
235 debugLog.printRTAriDebug(fn, "IOS XR upload for software config: timeout=" + timeout);
236 StringTokenizer st = new StringTokenizer(cmdThatWasSent);
238 routerFileName = st.nextToken();
239 fileWriter = new FileWriter(routerFileName);
240 out = new BufferedWriter(fileWriter);
241 routerLogFileName = "/tmp/" + RouterName;
242 _tmpFile = new File(routerLogFileName);
243 debugLog.printRTAriDebug(fn,
244 "Will write the swConfigFile to disk, routerFileName=" + routerFileName);
247 out.write(charBuffer, 0, len);
249 appendToFile(debugLogFileName, fn + " Wrote " + len + " bytes to the disk\n");
250 if (_tmpFile.exists()) {
251 appendToRouterFile(routerLogFileName, len);
253 match = checkIfReceivedStringMatchesDelimeter(len, "\nXML>");
262 appendToFile(debugLogFileName,
263 fn + " readCounts=" + readCounts + " Reader read " + len + " of data\n");
266 for (int i = 0; i < len; i++) {
268 if ((c != 7) && (c != 13) && (c != 0) && (c != 27)) {
269 sbReceive.append((char) charBuffer[i]);
270 sb2.append((char) charBuffer[i]);
273 appendToRouterFile("/tmp/" + RouterName, len);
274 if (listener != null) {
275 listener.receivedString(sb2.toString());
278 appendToFile(debugLogFileName, fn + " Trace 1\n");
279 match = checkIfReceivedStringMatchesDelimeter(delimeters, sb2.toString(), cmdThatWasSent);
280 appendToFile(debugLogFileName, fn + " Trace 2\n");
282 appendToFile(debugLogFileName, fn + " Match was true, breaking...\n");
287 debugLog.printRTAriDebug(fn, "cliPromptCmd, Trace 2");
289 for (int i = 0; i < len; i++) {
290 sbReceive.append((char) charBuffer[i]);
291 sb2.append((char) charBuffer[i]);
293 appendToRouterFile("/tmp/" + RouterName, sb2);
294 if (listener != null) {
295 listener.receivedString(sb2.toString());
297 debugLog.printRTAriDebug(fn, "sb2='" + sb2.toString() + "' delimeters='" + delimeters + "'");
298 if (sb2.toString().indexOf("\nariPrompt>") != -1) {
299 debugLog.printRTAriDebug(fn, "Found our prompt");
305 } catch (JSchException e) {
306 debugLog.printRTAriDebug(fn, "Caught an JSchException e=" + e.toString());
307 dbLog.outputStackTrace(e);
308 throw new TimedOutException(e.toString());
309 } catch (IOException ee) {
310 debugLog.printRTAriDebug(fn, "Caught an IOException: ee=" + ee.toString());
311 dbLog.outputStackTrace(ee);
312 throw new TimedOutException(ee.toString());
315 if (fileWriter != null) {
318 } catch(IOException ex) {
319 debugLog.printRTAriDebug(fn, "Failed to close fileWriter output stream: ex=" + ex);
322 String result = stripOffCmdFromRouterResponse(sbReceive.toString());
323 debugLog.printRTAriDebug(fn, "Leaving method successfully");
327 public boolean checkIfReceivedStringMatchesDelimeter(String delimeters, String receivedString,
328 String cmdThatWasSent) {
329 // The delimeters are in a '|' seperated string. Return true on the first match.
330 String fn = "SshJcraftWrapper.checkIfReceivedStringMatchesDelimeter";
331 appendToFile(debugLogFileName,
332 fn + " Entered: delimeters='" + delimeters + " cmdThatWasSent='" + cmdThatWasSent + "' receivedString='"
333 + receivedString + "'\n");
334 StringTokenizer st = new StringTokenizer(delimeters, "|");
336 if ((delimeters.indexOf("#$") != -1) || (routerCmdType.equals("CLI"))) // This would be an IOS XR, CLI command.
338 int x = receivedString.lastIndexOf("#");
339 int y = receivedString.length() - 1;
340 appendToFile(debugLogFileName, fn + " IOS XR, CLI command\n");
341 if (extraDebugFile.exists()) {
342 appendToFile(debugLogFileName,
343 fn + " :::cmdThatWasSent='" + cmdThatWasSent + "' x=" + x + " y=" + y + "\n");
345 return (x != -1) && (y == x);
347 if (cmdThatWasSent.indexOf("show config") != -1) {
348 appendToFile(debugLogFileName, fn + "In the block for 'show config'\n");
349 while (st.hasMoreTokens()) {
350 String delimeter = st.nextToken();
351 // Make sure we don't get faked out by a response of " #".
353 // # signaling-local-address ipv6 FD00:F4D5:EA06:1::110:136:254
355 int x = receivedString.lastIndexOf(delimeter);
356 if ((receivedString.lastIndexOf(delimeter) != -1) && (receivedString.lastIndexOf(" #") != x - 1)) {
357 appendToFile(debugLogFileName, fn + "receivedString=\n'" + receivedString + "'\n");
358 appendToFile(debugLogFileName,
359 fn + "Returning true for the 'show config' command. We found our real delmeter. \n\n");
364 aggregatedReceivedString = aggregatedReceivedString + receivedString;
365 _appendToFile("/tmp/aggregatedReceivedString.debug", aggregatedReceivedString);
367 while (st.hasMoreTokens()) {
368 String delimeter = st.nextToken();
369 appendToFile(debugLogFileName, fn + " Looking for an delimeter of:'" + delimeter + "'\n");
370 appendToFile(debugLogFileName, fn + " receivedString='" + receivedString);
371 if (aggregatedReceivedString.indexOf(delimeter) != -1) {
372 debugLog.printRTAriDebug(fn, "Found our delimeter, which was: '" + delimeter + "'");
373 aggregatedReceivedString = "";
381 public boolean checkIfReceivedStringMatchesDelimeter(int len, String delimeter) {
382 String fnName = "SshJcraftWrapper.checkIfReceivedStringMatchesDelimeter:::";
385 String str = StringUtils.EMPTY;
387 if (jcraftReadSwConfigFileFromDisk()) {
388 DebugLog.printAriDebug(fnName, "jcraftReadSwConfigFileFromDisk block");
389 File fileName = new File(routerFileName);
390 appendToFile(debugLogFileName,
391 fnName + " jcraftReadSwConfigFileFromDisk::: Will read the tail end of the file from the disk");
393 str = getLastFewLinesOfFile(fileName, 3);
394 } catch (IOException e) {
395 DebugLog.printAriDebug(fnName, "Caught an Exception, e=" + e);
396 dbLog.outputStackTrace(e);
400 // DebugLog.printAriDebug(fnName, "TRACE 1: ******************************");
401 // When looking at the end of the charBuffer, don't include any linefeeds or spaces. We only want to make the smallest string possible.
402 for (x = len - 1; x >= 0; x--) {
404 if (extraDebugFile.exists()) {
405 appendToFile(debugLogFileName, fnName + " x=" + x + " c=" + c + "\n");
407 if ((c != 10) && (c != 32)) // Not a line feed nor a space.
412 if ((x + 1 - 13) >= 0) {
413 str = new String(charBuffer, (x + 1 - 13), 13);
414 appendToFile(debugLogFileName, fnName + " str:'" + str + "'\n");
416 File fileName = new File(routerFileName);
417 appendToFile(debugLogFileName,
418 fnName + " Will read the tail end of the file from the disk, x=" + x + " len=" + len + " str::'"
419 + str + "' routerFileName='" + routerFileName + "'\n");
420 DebugLog.printAriDebug(fnName,
421 "Will read the tail end of the file from the disk, x=" + x + " len=" + len + " str::'" + str
422 + "' routerFileName='" + routerFileName + "'");
424 str = getLastFewLinesOfFile(fileName, 3);
425 } catch (IOException e) {
426 DebugLog.printAriDebug(fnName, "Caught an Exception, e=" + e);
427 dbLog.outputStackTrace(e);
433 if (str.indexOf(delimeter) != -1) {
434 DebugLog.printAriDebug(fnName, "str in break is:'" + str + "'" + " delimeter='" + delimeter + "'");
435 appendToFile(debugLogFileName,
436 fnName + " str in break is:'" + str + " delimeter='" + delimeter + "'" + "'\n");
439 appendToFile(debugLogFileName, fnName + " Returning false");
445 public void closeConnection() {
446 String fn = "SshJcraftWrapper.closeConnection";
447 debugLog.printRTAriDebug(fn, "Executing the closeConnection....");
452 session.disconnect();
456 public void send(String cmd) throws IOException {
457 String fn = "SshJcraftWrapper.send";
458 OutputStream out = channel.getOutputStream();
459 DataOutputStream dos = new DataOutputStream(out);
461 if ((cmd.charAt(cmd.length() - 1) != '\n') && (cmd.charAt(cmd.length() - 1) != '\r')) {
464 int length = cmd.length();
467 int ncharsTotalSent = 0;
470 appendToFile(debugLogFileName, fn + ": Sending: '" + cmd);
471 // debugLog.printRTAriDebug (fn, "cmd = "+cmd);
472 debugLog.printRTAriDebug(fn, "Length of cmd is:" + length); // 2,937,706
474 if (length > 600000) {
476 for (i = 0; i < length; i += nchars) {
477 String Cmd = cmd.substring(i, Math.min(length, i + nchars));
478 ncharsSent = Cmd.length();
479 ncharsTotalSent = ncharsTotalSent + Cmd.length();
480 debugLog.printRTAriDebug(fn, "i=" + i + " Sending Cmd: ncharsSent=" + ncharsSent);
484 debugLog.printRTAriDebug(fn, ":::i=" + i + " length=" + length);
485 if (ncharsSent < length) {
486 receiveUntilBufferFlush(ncharsSent, timeout, "buffer flush i=" + i);
488 debugLog.printRTAriDebug(fn, "i=" + i + " No Waiting this time....");
491 } catch (Exception e) {
492 debugLog.printRTAriDebug(fn, "Caught an Exception: Nothing to flush out.");
496 debugLog.printRTAriDebug(fn, "Before executing the dos.writeBytes");
500 debugLog.printRTAriDebug(fn, "Leaving method");
501 appendToFile(debugLogFileName, fn + ": Leaving method\n");
502 } catch (IOException e) {
503 debugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e);
504 dbLog.outputStackTrace(e);
505 throw new IOException(e.toString());
510 public void sendChar(int v) throws IOException {
511 String fn = "SshJcraftWrapper.sendChar";
512 OutputStream out = channel.getOutputStream();
513 DataOutputStream dos = new DataOutputStream(out);
515 debugLog.printRTAriDebug(fn, "Sending: '" + v + "'");
518 } catch (IOException e) {
519 debugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e);
520 throw new IOException(e.toString());
524 public void send(byte[] b, int off, int len) throws IOException {
525 String fn = "SshJcraftWrapper.send:byte[]";
526 OutputStream out = channel.getOutputStream();
527 DataOutputStream dos = new DataOutputStream(out);
529 dos.write(b, off, len);
531 } catch (IOException e) {
532 debugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e);
533 throw new IOException(e.toString());
537 public static class MyUserInfo implements UserInfo, UIKeyboardInteractive {
539 public String getPassword() {
543 public boolean promptYesNo(String str) {
547 public String getPassphrase() {
551 public boolean promptPassphrase(String message) {
555 public boolean promptPassword(String message) {
559 public void showMessage(String message) {
562 public String[] promptKeyboardInteractive(String destination,
571 public void addListener(TelnetListener listener) {
572 this.listener = listener;
575 public void appendToFile(String fileName, String dataToWrite) {
576 String fn = "SshJcraftWrapper.appendToFile";
579 // First check to see if a file 'fileName' exist, if it does
580 // write to it. If it does not exist, don't write to it.
581 File tmpFile = new File(fileName);
582 if (tmpFile.exists()) {
583 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
584 // out.write(dataToWrite);
585 // out.write(getTheDate() +": " +Thread.currentThread().getName() +": "+dataToWrite);
586 out.write(getTheDate() + ": " + tId + ": " + dataToWrite);
589 } catch (IOException e) {
590 debugLog.printRTAriDebug(fn, "Caught an IOException: e=" + e);
591 } catch (Exception e) {
592 debugLog.printRTAriDebug(fn, "Caught an Exception: e=" + e);
596 public void _appendToFile(String fileName, String dataToWrite) {
597 String fn = "SshJcraftWrapper.appendToFile";
600 // First check to see if a file 'fileName' exist, if it does
601 // write to it. If it does not exist, don't write to it.
602 File tmpFile = new File(fileName);
603 if (tmpFile.exists()) {
604 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
605 out.write(dataToWrite);
608 } catch (IOException e) {
609 debugLog.printRTAriDebug(fn, "Caught an IOException: e=" + e);
610 } catch (Exception e) {
611 debugLog.printRTAriDebug(fn, "Caught an Exception: e=" + e);
616 public String getTheDate() {
617 Calendar cal = Calendar.getInstance();
618 java.util.Date today = cal.getTime();
619 DateFormat df1 = DateFormat.getDateInstance();
620 DateFormat df3 = new SimpleDateFormat("MM/dd/yyyy H:mm:ss ");
621 return (df3.format(today));
625 public void appendToRouterFile(String fileName, StringBuffer dataToWrite) {
626 String fnName = "SshJcraftWrapper.appendToRouterFile";
627 debugLog.printRTAriDebug(fnName, "Entered.... ");
629 // First check to see if a file 'fileName' exist, if it does
630 // write to it. If it does not exist, don't write to it.
631 File tmpFile = new File(fileName);
633 // if ((tmpFile.exists()) && (tmpFile.setWritable(true, true)))
634 if (tmpFile.exists()) {
635 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
636 // out.write("<!-- "+getTheDate() +": " +tId +" -->\n");
637 out.write(dataToWrite.toString());
641 } catch (IOException e) {
642 System.err.println("writeToFile() exception: " + e);
647 public void appendToRouterFile(String fileName, int len) {
648 String fnName = "SshJcraftWrapper.appendToFile";
649 // debugLog.printRTAriDebug (fnName, "Entered.... len="+len);
651 // First check to see if a file 'fileName' exist, if it does
652 // write to it. If it does not exist, don't write to it.
653 File tmpFile = new File(fileName);
654 // if ((tmpFile.exists()) && (tmpFile.setWritable(true, true)))
655 if (tmpFile.exists()) {
656 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
657 // out.write("<!-- "+getTheDate() +": " +tId +" -->\n");
658 out.write(charBuffer, 0, len);
661 } catch (IOException e) {
662 System.err.println("writeToFile() exception: " + e);
667 public String removeWhiteSpaceAndNewLineCharactersAroundString(String str) {
669 StringTokenizer strTok = new StringTokenizer(str, "\n");
670 StringBuffer sb = new StringBuffer();
672 while (strTok.hasMoreTokens()) {
673 String line = strTok.nextToken();
676 return (sb.toString().trim());
682 public String stripOffCmdFromRouterResponse(String routerResponse) {
683 String fn = "SshJcraftWrapper.stripOffCmdFromRouterResponse";
684 // appendToFile(debugLogFileName, fn+": routerResponse='"+routerResponse +"'\n");
686 // The session of SSH will echo the command sent to the router, in the router's response.
687 // Since all our commands are terminated by a '\n', strip off the first line
688 // of the response from the router. This first line contains the orginal command.
690 StringTokenizer rr = new StringTokenizer(routerResponse, "\n");
691 StringBuffer sb = new StringBuffer();
693 int numTokens = rr.countTokens();
694 // debugLog.printRTAriDebug (fn, "Number of lines in the response from the router is:" +numTokens);
696 rr.nextToken(); //Skip the first line.
697 while (rr.hasMoreTokens()) {
698 sb.append(rr.nextToken() + '\n');
701 return (sb.toString());
704 public void setRouterCommandType(String type) {
705 String fn = "SshJcraftWrapper.setRouterCommandType";
706 this.routerCmdType = type;
707 debugLog.printRTAriDebug(fn, "Setting routerCmdType to a value of '" + type + "'");
710 public String getLastFewLinesOfFile(File file, int linesToRead) throws FileNotFoundException, IOException {
711 String fn = "SshJcraftWrapper.getLastFewLinesOfFile";
712 RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
714 StringBuilder builder = new StringBuilder();
716 long length = file.length();
718 randomAccessFile.seek(length);
719 for (long seek = length; seek >= 0; --seek) {
720 randomAccessFile.seek(seek);
721 char c = (char) randomAccessFile.read();
724 builder = builder.reverse();
725 // System.out.println(builder.toString());
726 tail = builder.toString() + tail;
728 builder.setLength(0);
729 if (lines == linesToRead) {
734 randomAccessFile.close();
735 if (!jcraftReadSwConfigFileFromDisk()) {
736 debugLog.printRTAriDebug(fn, "tail='" + tail + "'");
738 appendToFile(debugLogFileName, "tail='" + tail + "'\n");
742 public boolean jcraftReadSwConfigFileFromDisk() {
743 if (jcraftReadSwConfigFileFromDisk.exists()) {
750 public String getEquipNameCode() {
751 return (equipNameCode);
755 public void setEquipNameCode(String equipNameCode) {
756 this.equipNameCode = equipNameCode;
759 public String getRouterName() {
763 // Routine does reads until it has read 'nchars' or times out.
764 public void receiveUntilBufferFlush(int ncharsSent, int timeout, String message)
765 throws TimedOutException, IOException {
766 String fn = "SshJcraftWrapper.receiveUntilBufferFlush";
767 StringBuffer sb2 = new StringBuffer();
768 StringBuffer sbReceive = new StringBuffer();
769 debugLog.printRTAriDebug(fn, "ncharsSent=" + ncharsSent + " timeout=" + timeout + " " + message);
770 int ncharsTotalReceived = 0;
772 boolean flag = false;
773 charactersFromBufferFlush.setLength(0);
775 long deadline = new Date().getTime() + timeout;
778 session.setTimeout(timeout); // This is the socket timeout value.
780 if (new Date().getTime() > deadline) {
781 debugLog.printRTAriDebug(fn,
782 "Throwing a TimedOutException: time in routine has exceed our deadline: ncharsSent="
783 + ncharsSent + " ncharsTotalReceived=" + ncharsTotalReceived);
785 throw new TimedOutException("Timeout: time in routine has exceed our deadline");
787 ncharsRead = reader.read(charBuffer, 0, BUFFER_SIZE);
788 if (listener != null) {
789 listener.receivedString(String.copyValueOf(charBuffer, 0, ncharsRead));
791 appendToRouterFile("/tmp/" + RouterName, ncharsRead);
792 ncharsTotalReceived = ncharsTotalReceived + ncharsRead;
793 // debugLog.printRTAriDebug (fn, "::ncharsSent="+ncharsSent+" ncharsTotalReceived="+ncharsTotalReceived +" ncharsRead="+ncharsRead);
794 if (ncharsTotalReceived >= ncharsSent) {
795 debugLog.printRTAriDebug(fn,
796 "Received the correct number of characters, ncharsSent=" + ncharsSent + " ncharsTotalReceived="
797 + ncharsTotalReceived);
802 } catch (JSchException e) {
803 debugLog.printRTAriDebug(fn, "Caught an JSchException e=" + e);
804 debugLog.printRTAriDebug(fn,
805 "ncharsSent=" + ncharsSent + " ncharsTotalReceived=" + ncharsTotalReceived + " ncharsRead="
807 throw new TimedOutException(e.toString());
811 public String getHostName() {
815 public String getUserName() {
819 public String getPassWord() {
823 public void sftpPut(String sourcePath, String destDirectory) throws IOException {
824 String fn = "SshJcraftWrapper.sftp";
826 Session sftpSession = jsch.getSession(userName, hostName, 22);
827 UserInfo ui = new MyUserInfo();
828 sftpSession.setPassword(passWord);
829 sftpSession.setUserInfo(ui);
830 sftpSession.connect(30 * 1000);
831 debugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
832 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
833 debugLog.printRTAriDebug(fn, "Connecting....");
835 debugLog.printRTAriDebug(fn, "Sending " + sourcePath + " --> " + destDirectory);
836 sftp.put(sourcePath, destDirectory, ChannelSftp.OVERWRITE);
837 debugLog.printRTAriDebug(fn, "Sent successfully");
838 sftpSession.disconnect();
839 } catch (Exception e) {
840 debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
841 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
842 throw new IOException(e.toString());
847 public void SftpPut(String stringOfData, String fullPathDest) throws IOException {
848 String fn = "SshJcraftWrapper.Sftp";
850 Session sftpSession = jsch.getSession(userName, hostName, 22);
851 UserInfo ui = new MyUserInfo();
852 sftpSession.setPassword(passWord);
853 sftpSession.setUserInfo(ui);
854 sftpSession.connect(30 * 1000);
855 debugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
856 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
857 debugLog.printRTAriDebug(fn, "Connecting....");
859 InputStream is = new ByteArrayInputStream(stringOfData.getBytes());
860 debugLog.printRTAriDebug(fn, "Sending stringOfData --> " + fullPathDest);
861 sftp.put(is, fullPathDest, ChannelSftp.OVERWRITE);
862 debugLog.printRTAriDebug(fn, "Sent successfully");
863 sftpSession.disconnect();
864 } catch (Exception e) {
865 debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
866 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
867 throw new IOException(e.toString());
871 public String sftpGet(String fullFilePathName) throws IOException {
872 String fn = "SshJcraftWrapper.Sftp";
874 Session sftpSession = jsch.getSession(userName, hostName, 22);
875 UserInfo ui = new MyUserInfo();
876 sftpSession.setPassword(passWord);
877 sftpSession.setUserInfo(ui);
878 sftpSession.connect(30 * 1000);
879 debugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
880 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
881 debugLog.printRTAriDebug(fn, "Connecting....");
883 InputStream in = null;
884 in = sftp.get(fullFilePathName);
885 String sftpFileString = readInputStreamAsString(in);
886 debugLog.printRTAriDebug(fn, "Retreived successfully");
887 // debugLog.printRTAriDebug (fn, "sftpFileString="+sftpFileString);
888 sftpSession.disconnect();
889 return (sftpFileString);
890 } catch (Exception e) {
891 debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
892 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
893 throw new IOException(e.toString());
897 public static String readInputStreamAsString(InputStream in) throws IOException {
898 BufferedInputStream bis = new BufferedInputStream(in);
899 ByteArrayOutputStream buf = new ByteArrayOutputStream();
900 int result = bis.read();
901 while (result != -1) {
902 byte b = (byte) result;
906 return buf.toString();
910 public void logMemoryUsage() {
911 String fn = "SshJcraftWrapper.logMemoryUsage";
912 int mb = 1024 * 1024;
914 long maxMemoryAdvailable;
915 long memoryLetfOnHeap;
916 maxMemoryAdvailable = (runtime.maxMemory() / mb);
917 usedMemory = ((runtime.totalMemory() / mb) - (runtime.freeMemory() / mb));
918 memoryLetfOnHeap = maxMemoryAdvailable - usedMemory;
919 DebugLog.printAriDebug(fn,
920 "maxMemoryAdvailable=" + maxMemoryAdvailable + " usedMemory=" + usedMemory + " memoryLetfOnHeap="
924 // ----------------------------------------------------------------------------
925 // ----------------------------------------------------------------------------
926 // ----------------------------------------------------------------------------
927 // ----------------------------------------------------------------------------
930 // User specifies the port number, and the subsystem
931 public void connect(String hostname, String username, String password, String prompt, int timeOut, int portNum,
932 String subsystem) throws IOException {
933 String fn = "SshJcraftWrapper.connect";
935 debugLog.printRTAriDebug(fn,
936 ":::Attempting to connect to " + hostname + " username=" + username + " password=" + password + " prompt='"
937 + prompt + "' timeOut=" + timeOut + " portNum=" + portNum + " subsystem=" + subsystem);
938 RouterName = hostname;
941 session = jsch.getSession(username, hostname, portNum);
942 UserInfo ui = new MyUserInfo();
943 session.setPassword(password);
944 session.setUserInfo(ui);
945 session.setConfig("StrictHostKeyChecking", "no");
946 session.connect(timeOut);
947 session.setServerAliveCountMax(
948 0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
949 channel = session.openChannel("subsystem");
950 ((ChannelSubsystem) channel).setSubsystem(subsystem);
951 // ((ChannelSubsystem)channel).setPtyType("vt102");
952 ((ChannelSubsystem) channel).setPty(true);
954 inputStream = channel.getInputStream();
955 dis = new DataInputStream(inputStream);
956 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
958 debugLog.printRTAriDebug(fn, "Successfully connected.");
959 debugLog.printRTAriDebug(fn, "Five second sleep....");
962 } catch (java.lang.InterruptedException ee) {
963 boolean ignore = true;
965 } catch (Exception e) {
966 debugLog.printRTAriDebug(fn, "Caught an Exception. e=" + e);
967 throw new IOException(e.toString());
971 public void connect(String hostName, String username, String password, int portNumber) throws IOException {
972 String fn = "SshJcraftWrapper.connect";
974 debugLog.printRTAriDebug(fn,
975 "::Attempting to connect to " + hostName + " username=" + username + " password=" + password
976 + " portNumber=" + portNumber);
977 debugLog.printRTAriDebug(fn, "Trace C");
978 RouterName = hostName;
979 this.hostName = hostName;
983 java.util.Properties config = new java.util.Properties();
984 config.put("StrictHostKeyChecking", "no");
985 session = jsch.getSession(username, hostName, 22);
986 // session = jsch.getSession(username, hostName, portNumber);
987 UserInfo ui = new MyUserInfo();
988 session.setConfig(config);
989 session.setPassword(password);
990 session.setUserInfo(ui);
991 session.connect(30000);
992 channel = session.openChannel("shell");
993 session.setServerAliveCountMax(
994 0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
995 ((ChannelShell) channel).setPtyType("vt102");
996 inputStream = channel.getInputStream();
997 dis = new DataInputStream(inputStream);
998 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
1000 debugLog.printRTAriDebug(fn, "::Successfully connected.");
1001 debugLog.printRTAriDebug(fn, "::Flushing input buffer");
1003 receiveUntil(":~#", 9000, "No cmd was sent, just waiting, but we can stop on a '~#'");
1004 } catch (Exception e) {
1005 debugLog.printRTAriDebug(fn, "Caught an Exception::: Nothing to flush out.");
1008 } catch (Exception e) {
1009 debugLog.printRTAriDebug(fn, "Caught an Exception. e=" + e);
1010 // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostName +" "+e);
1011 throw new IOException(e.toString());
1016 public void put(String sourcePath, String destDirectory) throws IOException {
1017 String fn = "SshJcraftWrapper.sftp";
1019 Session sftpSession = jsch.getSession(userName, hostName, 22);
1020 UserInfo ui = new MyUserInfo();
1021 sftpSession.setPassword(passWord);
1022 sftpSession.setUserInfo(ui);
1023 sftpSession.connect(30 * 1000);
1024 debugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
1025 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
1026 debugLog.printRTAriDebug(fn, "Connecting....");
1028 debugLog.printRTAriDebug(fn, "Sending " + sourcePath + " --> " + destDirectory);
1029 sftp.put(sourcePath, destDirectory, ChannelSftp.OVERWRITE);
1030 debugLog.printRTAriDebug(fn, "Sent successfully");
1031 sftpSession.disconnect();
1032 } catch (Exception e) {
1033 debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
1034 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
1035 throw new IOException(e.toString());
1039 public void put(InputStream is, String fullPathDest, String hostName, String userName, String passWord)
1040 throws IOException {
1041 String fn = "SshJcraftWrapper.put";
1042 Session sftpSession = null;
1044 debugLog.printRTAriDebug(fn, "userName=" + userName + " hostName=" + hostName + " passWord=" + passWord);
1046 java.util.Properties config = new java.util.Properties();
1047 config.put("StrictHostKeyChecking", "no");
1048 sftpSession = jsch.getSession(userName, hostName, 22);
1049 UserInfo ui = new MyUserInfo();
1050 sftpSession.setPassword(passWord);
1051 sftpSession.setUserInfo(ui);
1052 sftpSession.setConfig(config);
1053 sftpSession.connect(30 * 1000);
1054 debugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
1055 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
1056 debugLog.printRTAriDebug(fn, "Connecting....");
1058 String oldFiles = fullPathDest + "*";
1059 debugLog.printRTAriDebug(fn, "Deleting old files --> " + oldFiles);
1062 debugLog.printRTAriDebug(fn, "Sending stringOfData --> " + fullPathDest);
1063 } catch (SftpException sft) {
1064 String exp = "No such file";
1065 if (sft.getMessage() != null && sft.getMessage().contains(exp)) {
1066 debugLog.printRTAriDebug(fn, "No files found -- Continue");
1068 debugLog.printRTAriDebug(fn, "Exception while sftp.rm " + sft.getMessage());
1069 sft.printStackTrace();
1073 sftp.put(is, fullPathDest, ChannelSftp.OVERWRITE);
1074 debugLog.printRTAriDebug(fn, "Sent successfully");
1075 } catch (Exception e) {
1076 debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
1077 throw new IOException(e.toString());
1079 if(sftpSession != null) {
1080 sftpSession.disconnect();
1086 public String get(String fullFilePathName, String hostName, String userName, String passWord) throws IOException {
1087 String fn = "SshJcraftWrapper.get";
1088 Session sftpSession = null;
1090 debugLog.printRTAriDebug(fn, "userName=" + userName + " hostName=" + hostName + " passWord=" + passWord);
1092 sftpSession = jsch.getSession(userName, hostName, 22);
1093 java.util.Properties config = new java.util.Properties();
1094 config.put("StrictHostKeyChecking", "no");
1095 UserInfo ui = new MyUserInfo();
1096 sftpSession.setPassword(passWord);
1097 sftpSession.setUserInfo(ui);
1098 sftpSession.setConfig(config);
1099 sftpSession.connect(30 * 1000);
1100 debugLog.printRTAriDebug(fn, "Opening up an sftp channel....");
1101 ChannelSftp sftp = (ChannelSftp) sftpSession.openChannel("sftp");
1102 debugLog.printRTAriDebug(fn, "Connecting....");
1104 InputStream in = sftp.get(fullFilePathName);
1105 String sftpFileString = readInputStreamAsString(in);
1106 debugLog.printRTAriDebug(fn, "Retreived successfully");
1107 return sftpFileString;
1108 } catch (Exception e) {
1109 debugLog.printRTAriDebug(fn, "Caught an Exception, e=" + e);
1110 throw new IOException(e.toString());
1112 if(sftpSession != null) {
1113 sftpSession.disconnect();
1118 public String send(String cmd, String delimiter) throws IOException {
1119 String fn = "SshJcraftWrapper.send";
1120 OutputStream out = channel.getOutputStream();
1121 DataOutputStream dos = new DataOutputStream(out);
1123 if ((cmd.charAt(cmd.length() - 1) != '\n') && (cmd.charAt(cmd.length() - 1) != '\r')) {
1126 int length = cmd.length();
1128 int nchars = 300000;
1129 int ncharsTotalSent = 0;
1132 debugLog.printRTAriDebug(fn, "Length of cmd is:" + length); // 2,937,706
1133 debugLog.printRTAriDebug(fn, "Length of cmd is:" + length); // 2,937,706
1135 if (length > 600000) {
1137 for (i = 0; i < length; i += nchars) {
1138 String Cmd = cmd.substring(i, Math.min(length, i + nchars));
1139 ncharsSent = Cmd.length();
1140 ncharsTotalSent = ncharsTotalSent + Cmd.length();
1141 debugLog.printRTAriDebug(fn, "i=" + i + " Sending Cmd: ncharsSent=" + ncharsSent);
1142 dos.writeBytes(Cmd);
1145 debugLog.printRTAriDebug(fn, ":::i=" + i + " length=" + length);
1146 if (ncharsSent < length) {
1147 receiveUntilBufferFlush(ncharsSent, timeout, "buffer flush i=" + i);
1149 debugLog.printRTAriDebug(fn, "i=" + i + " No Waiting this time....");
1152 } catch (Exception e) {
1153 debugLog.printRTAriDebug(fn, "Caught an Exception: Nothing to flush out.");
1157 debugLog.printRTAriDebug(fn, "Before executing the dos.writeBytes");
1158 dos.writeBytes(cmd);
1161 // Now lets get the response.
1162 String response = receiveUntil(delimiter, 300000, cmd);
1163 debugLog.printRTAriDebug(fn, "Leaving method");
1165 } catch (IOException e) {
1166 debugLog.printRTAriDebug(fn, "Caught an IOException. e=" + e);
1167 throw new IOException(e.toString());