2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.appc.ccadaptor;
23 import java.io.BufferedReader;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.InputStreamReader;
29 import java.text.DateFormat;
30 import java.text.SimpleDateFormat;
31 import java.util.Calendar;
32 import com.jcraft.jsch.*;
34 public class SshJcraftWrapper
36 private String debugLogFileName = "/tmp/sshJcraftWrapperDebug";
37 InputStream inputStream = null;
38 OutputStream outputStream = null;
39 private TelnetListener listener = null;
40 private String routerLogFileName = null;
41 DebugLog debugLog = new DebugLog();
42 private String host = null;
43 private String RouterName = null;
44 private int BUFFER_SIZE = 512000;
45 // private int BUFFER_SIZE = 4000000;
46 private DataInputStream dis = null;
47 private BufferedReader reader = null;
48 char[] charBuffer = new char[BUFFER_SIZE];
49 private BufferedWriter out = null;
50 private File _tmpFile = null;
51 private JSch jsch = null;
52 private Session session = null;
53 private Channel channel = null;
54 private String tId = "";
55 private String aggregatedReceivedString = "";
56 private File extraDebugFile = new File("/tmp/sshJcraftWrapperDEBUG");
57 private String routerCmdType = "XML";
58 private String routerFileName = null;
59 private File jcraftReadSwConfigFileFromDisk = new File("/tmp/jcraftReadSwConfigFileFromDisk");
60 private String equipNameCode = null;
61 private String hostName = null;
62 private String userName = null;
63 private String passWord = null;
64 private StringBuffer charactersFromBufferFlush = new StringBuffer();
65 private Runtime runtime = Runtime.getRuntime();
66 private DebugLog dbLog = new DebugLog();
68 public void SshJcraftWrapper()
70 String fn = "SshJcraftWrapper.SshJcraftWrapper";
71 debugLog.printRTAriDebug (fn, "SshJcraftWrapper has been instantated");
72 routerLogFileName = "/tmp/" +host;
76 public void connect (String hostname, String username, String password, String prompt, int timeOut) throws IOException
78 String fn = "SshJcraftWrapper.connect";
80 debugLog.printRTAriDebug (fn, "Attempting to connect to "+hostname +" username="+username +
81 " password="+password + " prompt='"+prompt +"' timeOut="+timeOut);
82 debugLog.printRTAriDebug (fn, "Trace A");
83 RouterName = hostname;
89 session = jsch.getSession(username, hostname, 22);
90 UserInfo ui = new MyUserInfo();
91 session.setPassword(password);
92 session.setUserInfo(ui);
93 session.connect(timeOut);
94 channel = session.openChannel("shell");
95 session.setServerAliveCountMax(0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
96 ((ChannelShell)channel).setPtyType("vt102");
97 inputStream = channel.getInputStream();
98 dis = new DataInputStream(inputStream);
99 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
101 debugLog.printRTAriDebug (fn, "Successfully connected.");
102 debugLog.printRTAriDebug (fn, "Flushing input buffer");
105 receiveUntil(prompt, 3000, "No cmd was sent, just waiting");
109 debugLog.printRTAriDebug (fn, "Caught an Exception: Nothing to flush out.");
114 debugLog.printRTAriDebug (fn, "Caught an Exception. e="+e);
115 throw new IOException(e.toString());
119 // User specifies the port number.
120 public void connect (String hostname, String username, String password, String prompt, int timeOut, int portNum) throws IOException
122 String fn = "SshJcraftWrapper.connect";
123 debugLog.printRTAriDebug (fn, ":Attempting to connect to "+hostname +" username="+username +
124 " password="+password + " prompt='"+prompt +"' timeOut="+timeOut +" portNum="+portNum);
125 RouterName = hostname;
129 RouterName = hostname;
133 session = jsch.getSession(username, hostname, portNum);
134 UserInfo ui = new MyUserInfo();
135 session.setPassword(password);
136 session.setUserInfo(ui);
137 session.setConfig("StrictHostKeyChecking", "no");
138 debugLog.printRTAriDebug (fn, ":StrictHostKeyChecking set to 'no'");
140 session.connect(timeOut);
141 session.setServerAliveCountMax(0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
142 channel = session.openChannel("shell");
143 ((ChannelShell)channel).setPtyType("vt102");
144 inputStream = channel.getInputStream();
145 dis = new DataInputStream(inputStream);
146 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
148 debugLog.printRTAriDebug (fn, ":Successfully connected.");
149 debugLog.printRTAriDebug (fn, ":Flushing input buffer");
152 if (prompt.equals("]]>]]>"))
153 receiveUntil("]]>]]>", 10000, "No cmd was sent, just waiting");
155 receiveUntil(":~#", 5000, "No cmd was sent, just waiting");
159 debugLog.printRTAriDebug (fn, "Caught an Exception::: Nothing to flush out.");
164 debugLog.printRTAriDebug (fn, ":Caught an Exception. e="+e);
165 dbLog.outputStackTrace(e);
167 throw new IOException(e.toString());
172 public String receiveUntil (String delimeters, int timeout, String cmdThatWasSent) throws TimedOutException, IOException
174 String fn = "SshJcraftWrapper.receiveUntil";
175 boolean match = false;
176 boolean cliPromptCmd = false;
177 StringBuffer sb2 = new StringBuffer();
178 StringBuffer sbReceive = new StringBuffer();
179 debugLog.printRTAriDebug (fn, "delimeters='"+delimeters +"' timeout="+timeout +" cmdThatWasSent='"+cmdThatWasSent +"'");
180 appendToFile(debugLogFileName, fn +" delimeters='"+delimeters +"' timeout="+timeout +" cmdThatWasSent='"+cmdThatWasSent +"'\n");
181 String CmdThatWasSent = removeWhiteSpaceAndNewLineCharactersAroundString(cmdThatWasSent);
183 aggregatedReceivedString = "";
185 long deadline = new Date().getTime() + timeout;
188 session.setTimeout(timeout); // This is the socket timeout value.
191 if(new Date().getTime() > deadline)
193 debugLog.printRTAriDebug (fn, "Throwing a TimedOutException: time in routine has exceed our deadline: RouterName:"+
194 RouterName +" CmdThatWasSent="+ CmdThatWasSent);
195 throw new TimedOutException("Timeout: time in routine has exceed our deadline");
201 catch (java.lang.InterruptedException ee)
203 boolean ignore = true;
205 int len = reader.read(charBuffer, 0, BUFFER_SIZE);
206 appendToFile(debugLogFileName, fn +" After reader.read cmd: len="+len +"\n");
209 debugLog.printRTAriDebug (fn, "Reader read "+len +" bytes. Looks like we timed out, router="+RouterName);
210 throw new TimedOutException ("Received a SocketTimeoutException router="+RouterName);
214 if (cmdThatWasSent.indexOf("IOS_XR_uploadedSwConfigCmd") != -1)
218 // This is a IOS XR sw config file. We will write it to the disk.
219 timeout = timeout * 2;
220 deadline = new Date().getTime() + timeout;
221 debugLog.printRTAriDebug (fn, "IOS XR upload for software config: timeout="+timeout);
222 StringTokenizer st = new StringTokenizer(cmdThatWasSent);
224 routerFileName = st.nextToken();
225 out = new BufferedWriter(new FileWriter(routerFileName));
226 routerLogFileName = "/tmp/"+RouterName;
227 _tmpFile = new File(routerLogFileName);
228 debugLog.printRTAriDebug (fn, "Will write the swConfigFile to disk, routerFileName="+routerFileName);
231 out.write(charBuffer, 0, len);
233 appendToFile(debugLogFileName, fn +" Wrote "+len +" bytes to the disk\n");
234 if (_tmpFile.exists())
235 appendToRouterFile(routerLogFileName, len);
236 match = checkIfReceivedStringMatchesDelimeter(len, "\nXML>");
248 appendToFile(debugLogFileName, fn +" readCounts="+readCounts +" Reader read "+len +" of data\n");
251 for(int i=0; i<len; i++ )
254 if ((c != 7) && (c != 13) && (c != 0) && (c != 27))
256 sbReceive.append((char)charBuffer[i]);
257 sb2.append((char)charBuffer[i]);
260 appendToRouterFile("/tmp/"+RouterName, len);
261 if (listener != null)
262 listener.receivedString(sb2.toString());
264 appendToFile(debugLogFileName, fn +" Trace 1\n");
265 match = checkIfReceivedStringMatchesDelimeter(delimeters, sb2.toString(), cmdThatWasSent);
266 appendToFile(debugLogFileName, fn +" Trace 2\n");
269 appendToFile(debugLogFileName, fn +" Match was true, breaking...\n");
276 debugLog.printRTAriDebug (fn, "cliPromptCmd, Trace 2");
278 for(int i=0; i<len; i++ )
280 sbReceive.append( (char)charBuffer[i] );
281 sb2.append( (char)charBuffer[i] );
283 appendToRouterFile("/tmp/"+RouterName, sb2);
284 if (listener != null)
285 listener.receivedString(sb2.toString());
286 debugLog.printRTAriDebug (fn, "sb2='"+sb2.toString() +"' delimeters='" +delimeters +"'");
287 if (sb2.toString().indexOf("\nariPrompt>") != -1)
289 debugLog.printRTAriDebug (fn, "Found our prompt");
296 catch (JSchException e)
298 debugLog.printRTAriDebug (fn, "Caught an JSchException e="+e.toString());
299 dbLog.outputStackTrace(e);
300 throw new TimedOutException (e.toString());
302 catch (IOException ee)
304 debugLog.printRTAriDebug (fn, "Caught an IOException: ee="+ee.toString());
305 dbLog.outputStackTrace(ee);
306 throw new TimedOutException (ee.toString());
308 String result = stripOffCmdFromRouterResponse(sbReceive.toString());
309 debugLog.printRTAriDebug (fn, "Leaving method successfully");
313 public boolean checkIfReceivedStringMatchesDelimeter(String delimeters, String receivedString, String cmdThatWasSent)
315 // The delimeters are in a '|' seperated string. Return true on the first match.
316 String fn = "SshJcraftWrapper.checkIfReceivedStringMatchesDelimeter";
317 appendToFile(debugLogFileName, fn +" Entered: delimeters='"+delimeters +" cmdThatWasSent='"+cmdThatWasSent +"' receivedString='"+receivedString +"'\n");
318 StringTokenizer st = new StringTokenizer(delimeters, "|");
320 if ((delimeters.indexOf("#$") != -1) || (routerCmdType.equals("CLI"))) // This would be an IOS XR, CLI command.
322 int x = receivedString.lastIndexOf("#");
323 int y = receivedString.length() - 1;
324 appendToFile(debugLogFileName, fn +" IOS XR, CLI command\n");
325 if (extraDebugFile.exists())
326 appendToFile(debugLogFileName, fn +" :::cmdThatWasSent='"+cmdThatWasSent +"' x="+x +" y="+y +"\n");
327 if ((x != -1) && (y == x))
332 if (cmdThatWasSent.indexOf("show config") != -1)
334 appendToFile(debugLogFileName, fn +"In the block for 'show config'\n");
335 while (st.hasMoreTokens())
337 String delimeter = st.nextToken();
338 // Make sure we don't get faked out by a response of " #".
340 // # signaling-local-address ipv6 FD00:F4D5:EA06:1::110:136:254
342 int x = receivedString.lastIndexOf(delimeter);
343 if ((receivedString.lastIndexOf(delimeter) != -1) && (receivedString.lastIndexOf(" #") != x-1))
345 appendToFile(debugLogFileName, fn +"receivedString=\n'" +receivedString +"'\n");
346 appendToFile(debugLogFileName, fn +"Returning true for the 'show config' command. We found our real delmeter. \n\n");
353 aggregatedReceivedString = aggregatedReceivedString + receivedString;
354 _appendToFile ("/tmp/aggregatedReceivedString.debug", aggregatedReceivedString);
356 while (st.hasMoreTokens())
358 String delimeter = st.nextToken();
359 appendToFile(debugLogFileName, fn +" Looking for an delimeter of:'"+delimeter+"'\n");
360 appendToFile(debugLogFileName, fn +" receivedString='"+receivedString);
361 if (aggregatedReceivedString.indexOf(delimeter) != -1)
363 debugLog.printRTAriDebug (fn, "Found our delimeter, which was: '"+delimeter +"'");
364 aggregatedReceivedString = "";
372 public boolean checkIfReceivedStringMatchesDelimeter(int len, String delimeter)
374 String fnName = "SshJcraftWrapper.checkIfReceivedStringMatchesDelimeter:::";
379 if (jcraftReadSwConfigFileFromDisk())
381 DebugLog.printAriDebug(fnName, "jcraftReadSwConfigFileFromDisk block");
382 File fileName = new File(routerFileName);
383 appendToFile(debugLogFileName, fnName +" jcraftReadSwConfigFileFromDisk::: Will read the tail end of the file from the disk");
386 str = getLastFewLinesOfFile(fileName, 3);
388 catch (IOException e)
390 DebugLog.printAriDebug(fnName, "Caught an Exception, e="+e);
391 dbLog.outputStackTrace(e);
397 // DebugLog.printAriDebug(fnName, "TRACE 1: ******************************");
398 // When looking at the end of the charBuffer, don't include any linefeeds or spaces. We only want to make the smallest string possible.
399 for(x=len-1; x>=0; x--)
402 if (extraDebugFile.exists())
403 appendToFile(debugLogFileName, fnName +" x="+x +" c="+c +"\n");
404 if ((c != 10) && (c != 32)) // Not a line feed nor a space.
409 str = new String (charBuffer, (x+1-13), 13);
410 appendToFile(debugLogFileName, fnName +" str:'"+str +"'\n");
414 File fileName = new File(routerFileName);
415 appendToFile(debugLogFileName, fnName +" Will read the tail end of the file from the disk, x="+x +
416 " len="+len +" str::'"+str +"' routerFileName='" +routerFileName +"'\n");
417 DebugLog.printAriDebug(fnName, "Will read the tail end of the file from the disk, x="+x +" len="
418 +len +" str::'"+str +"' routerFileName='" +routerFileName +"'");
421 str = getLastFewLinesOfFile(fileName, 3);
423 catch (IOException e)
425 DebugLog.printAriDebug(fnName, "Caught an Exception, e="+e);
426 dbLog.outputStackTrace(e);
432 if (str.indexOf(delimeter) != -1)
434 DebugLog.printAriDebug(fnName, "str in break is:'"+str +"'" +" delimeter='" +delimeter +"'");
435 appendToFile(debugLogFileName, fnName +" str in break is:'"+str +" delimeter='" +delimeter +"'" +"'\n");
440 appendToFile(debugLogFileName, fnName +" Returning false");
446 public void closeConnection()
448 String fn = "SshJcraftWrapper.closeConnection";
449 debugLog.printRTAriDebug (fn, "Executing the closeConnection....");
454 session.disconnect();
458 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'))
466 int length = cmd.length();
469 int ncharsTotalSent = 0;
472 appendToFile(debugLogFileName, fn+": Sending: '"+cmd );
473 debugLog.printRTAriDebug (fn, "Length of cmd is:" +length); // 2,937,706
479 for (i=0; i<length; i+=nchars)
481 String Cmd = cmd.substring(i, Math.min(length, i + nchars));
482 ncharsSent = Cmd.length();
483 ncharsTotalSent = ncharsTotalSent + Cmd.length();
484 debugLog.printRTAriDebug (fn, "i="+i +" Sending Cmd: ncharsSent="+ncharsSent);
489 debugLog.printRTAriDebug (fn, ":::i="+i +" length="+length);
490 if (ncharsSent < length)
491 receiveUntilBufferFlush (ncharsSent, timeout, "buffer flush i="+i);
494 debugLog.printRTAriDebug (fn, "i="+i +" No Waiting this time....");
500 debugLog.printRTAriDebug (fn, "Caught an Exception: Nothing to flush out.");
506 debugLog.printRTAriDebug (fn, "Before executing the dos.writeBytes");
510 debugLog.printRTAriDebug (fn, "Leaving method");
511 appendToFile(debugLogFileName, fn+": Leaving method\n");
513 catch (IOException e)
515 debugLog.printRTAriDebug (fn, "Caught an IOException. e="+e);
516 dbLog.outputStackTrace(e);
517 throw new IOException(e.toString());
522 public void sendChar (int v) throws IOException
524 String fn = "SshJcraftWrapper.sendChar";
525 OutputStream out = channel.getOutputStream();
526 DataOutputStream dos = new DataOutputStream(out);
529 debugLog.printRTAriDebug (fn, "Sending: '" +v +"'");
533 catch (IOException e)
535 debugLog.printRTAriDebug (fn, "Caught an IOException. e="+e);
536 throw new IOException(e.toString());
540 public void send (byte[] b, int off, int len) throws IOException
542 String fn = "SshJcraftWrapper.send:byte[]";
543 OutputStream out = channel.getOutputStream();
544 DataOutputStream dos = new DataOutputStream(out);
547 dos.write (b, off, len);
550 catch (IOException e)
552 debugLog.printRTAriDebug (fn, "Caught an IOException. e="+e);
553 throw new IOException(e.toString());
557 public static class MyUserInfo implements UserInfo, UIKeyboardInteractive
559 public String getPassword()
563 public boolean promptYesNo(String str)
567 public String getPassphrase()
571 public boolean promptPassphrase(String message)
575 public boolean promptPassword(String message)
579 public void showMessage(String message)
581 public String[] promptKeyboardInteractive(String destination,
591 public void addListener(TelnetListener listener)
593 this.listener = listener;
596 public void appendToFile (String fileName, String dataToWrite)
598 String fn = "SshJcraftWrapper.appendToFile";
602 // First check to see if a file 'fileName' exist, if it does
603 // write to it. If it does not exist, don't write to it.
604 File tmpFile = new File(fileName);
605 if (tmpFile.exists())
607 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
608 out.write(getTheDate() +": " +tId +": "+dataToWrite);
612 catch (IOException e)
614 debugLog.printRTAriDebug (fn, "Caught an IOException: e="+e);
618 debugLog.printRTAriDebug (fn, "Caught an Exception: e="+e);
622 public void _appendToFile (String fileName, String dataToWrite)
624 String fn = "SshJcraftWrapper.appendToFile";
628 // First check to see if a file 'fileName' exist, if it does
629 // write to it. If it does not exist, don't write to it.
630 File tmpFile = new File(fileName);
631 if (tmpFile.exists())
633 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
634 out.write(dataToWrite);
638 catch (IOException e)
640 debugLog.printRTAriDebug (fn, "Caught an IOException: e="+e);
644 debugLog.printRTAriDebug (fn, "Caught an Exception: e="+e);
649 public String getTheDate()
651 Calendar cal = Calendar.getInstance();
652 java.util.Date today = cal.getTime();
653 DateFormat df1 = DateFormat.getDateInstance();
654 DateFormat df3 = new SimpleDateFormat("MM/dd/yyyy H:mm:ss ");
655 return (df3.format(today));
659 public void appendToRouterFile (String fileName, StringBuffer dataToWrite)
661 String fnName = "SshJcraftWrapper.appendToRouterFile";
662 debugLog.printRTAriDebug (fnName, "Entered.... ");
665 // First check to see if a file 'fileName' exist, if it does
666 // write to it. If it does not exist, don't write to it.
667 File tmpFile = new File(fileName);
669 // if ((tmpFile.exists()) && (tmpFile.setWritable(true, true)))
670 if (tmpFile.exists())
672 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
673 out.write(dataToWrite.toString());
678 catch (IOException e)
680 System.err.println("writeToFile() exception: " + e);
685 public void appendToRouterFile (String fileName, int len)
687 String fnName = "SshJcraftWrapper.appendToFile";
690 // First check to see if a file 'fileName' exist, if it does
691 // write to it. If it does not exist, don't write to it.
692 File tmpFile = new File(fileName);
693 // if ((tmpFile.exists()) && (tmpFile.setWritable(true, true)))
694 if (tmpFile.exists())
696 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
697 out.write(charBuffer, 0, len);
701 catch (IOException e)
703 System.err.println("writeToFile() exception: " + e);
708 public String removeWhiteSpaceAndNewLineCharactersAroundString(String str)
712 StringTokenizer strTok = new StringTokenizer(str, "\n");
713 StringBuffer sb = new StringBuffer();
715 while (strTok.hasMoreTokens())
717 String line = strTok.nextToken();
720 return (sb.toString().trim());
726 public String stripOffCmdFromRouterResponse(String routerResponse)
728 String fn = "SshJcraftWrapper.stripOffCmdFromRouterResponse";
729 // appendToFile(debugLogFileName, fn+": routerResponse='"+routerResponse +"'\n");
731 // The session of SSH will echo the command sent to the router, in the router's response.
732 // Since all our commands are terminated by a '\n', strip off the first line
733 // of the response from the router. This first line contains the orginal command.
735 StringTokenizer rr = new StringTokenizer(routerResponse, "\n");
736 StringBuffer sb = new StringBuffer();
738 int numTokens = rr.countTokens();
741 rr.nextToken(); //Skip the first line.
742 while (rr.hasMoreTokens())
744 sb.append(rr.nextToken()+'\n');
747 return (sb.toString());
750 public void setRouterCommandType(String type)
752 String fn = "SshJcraftWrapper.setRouterCommandType";
753 this.routerCmdType = type;
754 debugLog.printRTAriDebug (fn, "Setting routerCmdType to a value of '"+type +"'");
757 public String getLastFewLinesOfFile(File file, int linesToRead) throws FileNotFoundException, IOException
759 String fn = "SshJcraftWrapper.getLastFewLinesOfFile";
760 RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
762 StringBuilder builder = new StringBuilder();
764 long length = file.length();
766 randomAccessFile.seek(length);
767 for(long seek = length; seek >= 0; --seek)
769 randomAccessFile.seek(seek);
770 char c = (char)randomAccessFile.read();
774 builder = builder.reverse();
775 tail = builder.toString() + tail;
777 builder.setLength(0);
778 if (lines == linesToRead)
784 randomAccessFile.close();
785 if(!jcraftReadSwConfigFileFromDisk())
786 debugLog.printRTAriDebug (fn, "tail='"+tail +"'");
787 appendToFile(debugLogFileName, "tail='"+tail +"'\n");
791 public boolean jcraftReadSwConfigFileFromDisk()
793 if (jcraftReadSwConfigFileFromDisk.exists())
799 public String getEquipNameCode()
801 return (equipNameCode);
804 public void setEquipNameCode(String equipNameCode)
806 this.equipNameCode = equipNameCode;
809 public String getRouterName()
814 // Routine does reads until it has read 'nchars' or times out.
815 public void receiveUntilBufferFlush (int ncharsSent, int timeout, String message) throws TimedOutException, IOException
817 String fn = "SshJcraftWrapper.receiveUntilBufferFlush";
818 StringBuffer sb2 = new StringBuffer();
819 StringBuffer sbReceive = new StringBuffer();
820 debugLog.printRTAriDebug (fn, "ncharsSent="+ncharsSent+" timeout="+timeout +" "+message);
821 int ncharsTotalReceived = 0;
823 boolean flag = false;
824 charactersFromBufferFlush.setLength(0);
826 long deadline = new Date().getTime() + timeout;
830 session.setTimeout(timeout); // This is the socket timeout value.
833 if(new Date().getTime() > deadline)
835 debugLog.printRTAriDebug (fn, "Throwing a TimedOutException: time in routine has exceed our deadline: ncharsSent="
836 +ncharsSent+" ncharsTotalReceived="+ncharsTotalReceived);
838 throw new TimedOutException("Timeout: time in routine has exceed our deadline");
840 ncharsRead = reader.read(charBuffer, 0, BUFFER_SIZE);
841 if (listener != null)
842 listener.receivedString(String.copyValueOf(charBuffer,0,ncharsRead));
843 appendToRouterFile("/tmp/"+RouterName, ncharsRead);
844 ncharsTotalReceived = ncharsTotalReceived + ncharsRead;
845 if (ncharsTotalReceived >= ncharsSent)
847 debugLog.printRTAriDebug (fn, "Received the correct number of characters, ncharsSent="
848 +ncharsSent +" ncharsTotalReceived="+ncharsTotalReceived);
854 catch (JSchException e)
856 debugLog.printRTAriDebug (fn, "Caught an JSchException e="+e.toString());
857 debugLog.printRTAriDebug (fn, "ncharsSent="+ncharsSent+" ncharsTotalReceived="+ncharsTotalReceived +" ncharsRead="+ncharsRead);
858 throw new TimedOutException (e.toString());
862 public String getHostName()
867 public String getUserName()
872 public String getPassWord()
877 public void sftpPut(String sourcePath, String destDirectory) throws IOException
879 String fn = "SshJcraftWrapper.sftp";
882 Session sftpSession = jsch.getSession(userName, hostName, 22);
883 UserInfo ui = new MyUserInfo();
884 sftpSession.setPassword(passWord);
885 sftpSession.setUserInfo(ui);
886 sftpSession.connect(30*1000);
887 debugLog.printRTAriDebug (fn, "Opening up an sftp channel....");
888 ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp");
889 debugLog.printRTAriDebug (fn, "Connecting....");
891 debugLog.printRTAriDebug (fn, "Sending "+sourcePath +" --> "+destDirectory);
892 sftp.put(sourcePath, destDirectory, ChannelSftp.OVERWRITE);
893 debugLog.printRTAriDebug (fn, "Sent successfully");
894 sftpSession.disconnect();
898 debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e);
899 throw new IOException(e.toString());
905 public void SftpPut(String stringOfData, String fullPathDest) throws IOException
907 String fn = "SshJcraftWrapper.Sftp";
910 Session sftpSession = jsch.getSession(userName, hostName, 22);
911 UserInfo ui = new MyUserInfo();
912 sftpSession.setPassword(passWord);
913 sftpSession.setUserInfo(ui);
914 sftpSession.connect(30*1000);
915 debugLog.printRTAriDebug (fn, "Opening up an sftp channel....");
916 ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp");
917 debugLog.printRTAriDebug (fn, "Connecting....");
919 InputStream is = new ByteArrayInputStream(stringOfData.getBytes());
920 debugLog.printRTAriDebug (fn, "Sending stringOfData --> "+fullPathDest);
921 sftp.put(is, fullPathDest, ChannelSftp.OVERWRITE);
922 debugLog.printRTAriDebug (fn, "Sent successfully");
923 sftpSession.disconnect();
927 debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e);
928 throw new IOException(e.toString());
932 public String sftpGet(String fullFilePathName) throws IOException
934 String fn = "SshJcraftWrapper.Sftp";
937 Session sftpSession = jsch.getSession(userName, hostName, 22);
938 UserInfo ui = new MyUserInfo();
939 sftpSession.setPassword(passWord);
940 sftpSession.setUserInfo(ui);
941 sftpSession.connect(30*1000);
942 debugLog.printRTAriDebug (fn, "Opening up an sftp channel....");
943 ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp");
944 debugLog.printRTAriDebug (fn, "Connecting....");
946 InputStream in = null;
947 in = sftp.get(fullFilePathName);
948 String sftpFileString = readInputStreamAsString(in);
949 debugLog.printRTAriDebug (fn, "Retreived successfully");
950 // debugLog.printRTAriDebug (fn, "sftpFileString="+sftpFileString);
951 sftpSession.disconnect();
952 return(sftpFileString);
956 debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e);
957 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
958 throw new IOException(e.toString());
962 public static String readInputStreamAsString(InputStream in) throws IOException
964 BufferedInputStream bis = new BufferedInputStream(in);
965 ByteArrayOutputStream buf = new ByteArrayOutputStream();
966 int result = bis.read();
969 byte b = (byte)result;
973 return buf.toString();
977 public void logMemoryUsage()
979 String fn = "SshJcraftWrapper.logMemoryUsage";
982 long maxMemoryAdvailable;
983 long memoryLetfOnHeap;
984 maxMemoryAdvailable = (runtime.maxMemory() / mb);
985 usedMemory = ((runtime.totalMemory()/mb) - (runtime.freeMemory()/mb));
986 memoryLetfOnHeap = maxMemoryAdvailable - usedMemory;
987 DebugLog.printAriDebug(fn, "maxMemoryAdvailable="+maxMemoryAdvailable +" usedMemory="+usedMemory +" memoryLetfOnHeap="+memoryLetfOnHeap);
991 // User specifies the port number, and the subsystem
992 public void connect (String hostname, String username, String password, String prompt, int timeOut, int portNum, String subsystem) throws IOException
994 String fn = "SshJcraftWrapper.connect";
996 debugLog.printRTAriDebug (fn, ":::Attempting to connect to "+hostname +" username="+username +" password="+password + " prompt='"+prompt +"' timeOut="+timeOut +" portNum="+portNum +" subsystem="+subsystem);
997 RouterName = hostname;
1001 session = jsch.getSession(username, hostname, portNum);
1002 UserInfo ui = new MyUserInfo();
1003 session.setPassword(password);
1004 session.setUserInfo(ui);
1005 session.setConfig("StrictHostKeyChecking", "no");
1006 session.connect(timeOut);
1007 session.setServerAliveCountMax(0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
1008 channel = session.openChannel("subsystem");
1009 ((ChannelSubsystem)channel).setSubsystem(subsystem);
1010 ((ChannelSubsystem)channel).setPty(true);
1012 inputStream = channel.getInputStream();
1013 dis = new DataInputStream(inputStream);
1014 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
1016 debugLog.printRTAriDebug (fn, "Successfully connected.");
1017 debugLog.printRTAriDebug (fn, "Five second sleep....");
1018 try { Thread.sleep(5000); } catch (java.lang.InterruptedException ee) { boolean ignore = true; }
1022 debugLog.printRTAriDebug (fn, "Caught an Exception. e="+e);
1023 throw new IOException(e.toString());
1027 public void connect (String hostName, String username, String password, int portNumber) throws IOException
1029 String fn = "SshJcraftWrapper.connect";
1031 debugLog.printRTAriDebug (fn, "::Attempting to connect to "+hostName +" username="+username +" password="+password +" portNumber="+portNumber);
1032 debugLog.printRTAriDebug (fn, "Trace C");
1033 RouterName = hostName;
1034 this.hostName = hostName;
1035 userName = username;
1036 passWord = password;
1039 java.util.Properties config = new java.util.Properties();
1040 config.put("StrictHostKeyChecking", "no");
1041 session = jsch.getSession(username, hostName, 22);
1042 UserInfo ui = new MyUserInfo();
1043 session.setConfig(config);
1044 session.setPassword(password);
1045 session.setUserInfo(ui);
1046 session.connect(30000);
1047 channel = session.openChannel("shell");
1048 session.setServerAliveCountMax(0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
1049 ((ChannelShell)channel).setPtyType("vt102");
1050 inputStream = channel.getInputStream();
1051 dis = new DataInputStream(inputStream);
1052 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
1054 debugLog.printRTAriDebug (fn, "::Successfully connected.");
1055 debugLog.printRTAriDebug (fn, "::Flushing input buffer");
1058 receiveUntil(":~#", 9000, "No cmd was sent, just waiting, but we can stop on a '~#'");
1062 debugLog.printRTAriDebug (fn, "Caught an Exception::: Nothing to flush out.");
1068 debugLog.printRTAriDebug (fn, "Caught an Exception. e="+e);
1069 throw new IOException(e.toString());
1074 public void put(String sourcePath, String destDirectory) throws IOException
1076 String fn = "SshJcraftWrapper.sftp";
1079 Session sftpSession = jsch.getSession(userName, hostName, 22);
1080 UserInfo ui = new MyUserInfo();
1081 sftpSession.setPassword(passWord);
1082 sftpSession.setUserInfo(ui);
1083 sftpSession.connect(30*1000);
1084 debugLog.printRTAriDebug (fn, "Opening up an sftp channel....");
1085 ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp");
1086 debugLog.printRTAriDebug (fn, "Connecting....");
1088 debugLog.printRTAriDebug (fn, "Sending "+sourcePath +" --> "+destDirectory);
1089 sftp.put(sourcePath, destDirectory, ChannelSftp.OVERWRITE);
1090 debugLog.printRTAriDebug (fn, "Sent successfully");
1091 sftpSession.disconnect();
1095 debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e);
1096 throw new IOException(e.toString());
1100 public void put(InputStream is, String fullPathDest, String hostName, String userName, String passWord) throws IOException
1102 String fn = "SshJcraftWrapper.put";
1103 Session sftpSession = null;
1106 debugLog.printRTAriDebug (fn, "userName="+userName +" hostName="+hostName +" passWord="+passWord);
1108 java.util.Properties config = new java.util.Properties();
1109 config.put("StrictHostKeyChecking", "no");
1110 sftpSession = jsch.getSession(userName, hostName, 22);
1111 UserInfo ui = new MyUserInfo();
1112 sftpSession.setPassword(passWord);
1113 sftpSession.setUserInfo(ui);
1114 sftpSession.setConfig(config);
1115 sftpSession.connect(30*1000);
1116 debugLog.printRTAriDebug (fn, "Opening up an sftp channel....");
1117 ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp");
1118 debugLog.printRTAriDebug (fn, "Connecting....");
1120 String oldFiles = fullPathDest +"*";
1121 debugLog.printRTAriDebug (fn, "Deleting old files --> "+oldFiles);
1123 debugLog.printRTAriDebug (fn, "Sending stringOfData --> "+fullPathDest);
1124 sftp.put(is, fullPathDest, ChannelSftp.OVERWRITE);
1125 debugLog.printRTAriDebug (fn, "Sent successfully");
1126 sftpSession.disconnect();
1131 debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e);
1132 sftpSession.disconnect();
1134 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
1135 throw new IOException(e.toString());
1140 public String get(String fullFilePathName, String hostName, String userName, String passWord) throws IOException
1142 String fn = "SshJcraftWrapper.get";
1143 Session sftpSession = null;
1146 debugLog.printRTAriDebug (fn, "userName="+userName +" hostName="+hostName +" passWord="+passWord);
1148 sftpSession = jsch.getSession(userName, hostName, 22);
1149 java.util.Properties config = new java.util.Properties();
1150 config.put("StrictHostKeyChecking", "no");
1151 UserInfo ui = new MyUserInfo();
1152 sftpSession.setPassword(passWord);
1153 sftpSession.setUserInfo(ui);
1154 sftpSession.setConfig(config);
1155 sftpSession.connect(30*1000);
1156 debugLog.printRTAriDebug (fn, "Opening up an sftp channel....");
1157 ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp");
1158 debugLog.printRTAriDebug (fn, "Connecting....");
1160 InputStream in = null;
1161 in = sftp.get(fullFilePathName);
1162 String sftpFileString = readInputStreamAsString(in);
1163 debugLog.printRTAriDebug (fn, "Retreived successfully");
1164 // debugLog.printRTAriDebug (fn, "sftpFileString="+sftpFileString);
1165 sftpSession.disconnect();
1167 return(sftpFileString);
1171 debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e);
1172 sftpSession.disconnect();
1174 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
1175 throw new IOException(e.toString());
1179 public String send(String cmd, String delimiter) throws IOException
1181 String fn = "SshJcraftWrapper.send";
1182 OutputStream out = channel.getOutputStream();
1183 DataOutputStream dos = new DataOutputStream(out);
1185 if ((cmd.charAt(cmd.length() - 1) != '\n') && (cmd.charAt(cmd.length() - 1) != '\r'))
1187 int length = cmd.length();
1189 int nchars = 300000;
1190 int ncharsTotalSent = 0;
1193 debugLog.printRTAriDebug (fn, "Length of cmd is:" +length); // 2,937,706
1194 debugLog.printRTAriDebug (fn, "Length of cmd is:" +length); // 2,937,706
1197 if (length > 600000)
1200 for (i=0; i<length; i+=nchars)
1202 String Cmd = cmd.substring(i, Math.min(length, i + nchars));
1203 ncharsSent = Cmd.length();
1204 ncharsTotalSent = ncharsTotalSent + Cmd.length();
1205 debugLog.printRTAriDebug (fn, "i="+i +" Sending Cmd: ncharsSent="+ncharsSent);
1206 dos.writeBytes(Cmd);
1210 debugLog.printRTAriDebug (fn, ":::i="+i +" length="+length);
1211 if (ncharsSent < length)
1212 receiveUntilBufferFlush (ncharsSent, timeout, "buffer flush i="+i);
1215 debugLog.printRTAriDebug (fn, "i="+i +" No Waiting this time....");
1221 debugLog.printRTAriDebug (fn, "Caught an Exception: Nothing to flush out.");
1227 debugLog.printRTAriDebug (fn, "Before executing the dos.writeBytes");
1228 dos.writeBytes(cmd);
1231 // Now lets get the response.
1232 String response = receiveUntil (delimiter, 300000, cmd);
1233 debugLog.printRTAriDebug (fn, "Leaving method");
1236 catch (IOException e)
1238 debugLog.printRTAriDebug (fn, "Caught an IOException. e="+e);
1239 throw new IOException(e.toString());