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.openecomp.appc.ccadaptor;
27 import java.io.BufferedReader;
28 import java.io.IOException;
29 import java.io.InputStream;
30 import java.io.InputStreamReader;
33 import java.text.DateFormat;
34 import java.text.SimpleDateFormat;
35 import java.util.Calendar;
36 import com.jcraft.jsch.*;
38 public class SshJcraftWrapper
41 private String debugLogFileName = "/tmp/sshJcraftWrapperDebug";
42 InputStream inputStream = null;
43 OutputStream outputStream = null;
44 private TelnetListener listener = null;
45 private String routerLogFileName = null;
46 DebugLog debugLog = new DebugLog();
47 private String host = null;
48 private String RouterName = null;
49 private int BUFFER_SIZE = 512000;
50 // private int BUFFER_SIZE = 4000000;
51 private DataInputStream dis = null;
52 private BufferedReader reader = null;
53 char[] charBuffer = new char[BUFFER_SIZE];
54 private BufferedWriter out = null;
55 private File _tmpFile = null;
56 private JSch jsch = null;
57 private Session session = null;
58 private Channel channel = null;
59 private String tId = "";
60 private String aggregatedReceivedString = "";
61 private File extraDebugFile = new File("/tmp/sshJcraftWrapperDEBUG");
62 private String routerCmdType = "XML";
63 private String routerFileName = null;
64 private File jcraftReadSwConfigFileFromDisk = new File("/tmp/jcraftReadSwConfigFileFromDisk");
65 private String equipNameCode = null;
66 private String hostName = null;
67 private String userName = null;
68 private String passWord = null;
69 private StringBuffer charactersFromBufferFlush = new StringBuffer();
70 private Runtime runtime = Runtime.getRuntime();
71 private DebugLog dbLog = new DebugLog();
73 public void SshJcraftWrapper()
75 String fn = "SshJcraftWrapper.SshJcraftWrapper";
76 debugLog.printRTAriDebug (fn, "SshJcraftWrapper has been instantated");
77 routerLogFileName = "/tmp/" +host;
81 public void connect (String hostname, String username, String password, String prompt, int timeOut) throws IOException
83 String fn = "SshJcraftWrapper.connect";
85 debugLog.printRTAriDebug (fn, "Attempting to connect to "+hostname +" username="+username +" password="+password + " prompt='"+prompt +"' timeOut="+timeOut);
86 debugLog.printRTAriDebug (fn, "Trace A");
87 RouterName = hostname;
93 session = jsch.getSession(username, hostname, 22);
94 UserInfo ui = new MyUserInfo();
95 session.setPassword(password);
96 session.setUserInfo(ui);
97 session.connect(timeOut);
98 channel = session.openChannel("shell");
99 session.setServerAliveCountMax(0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
100 ((ChannelShell)channel).setPtyType("vt102");
101 inputStream = channel.getInputStream();
102 dis = new DataInputStream(inputStream);
103 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
105 debugLog.printRTAriDebug (fn, "Successfully connected.");
106 debugLog.printRTAriDebug (fn, "Flushing input buffer");
109 receiveUntil(prompt, 3000, "No cmd was sent, just waiting");
113 debugLog.printRTAriDebug (fn, "Caught an Exception: Nothing to flush out.");
118 debugLog.printRTAriDebug (fn, "Caught an Exception. e="+e);
119 // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostname +" "+e);
120 throw new IOException(e.toString());
124 // User specifies the port number.
125 public void connect (String hostname, String username, String password, String prompt, int timeOut, int portNum) throws IOException
127 String fn = "SshJcraftWrapper.connect";
128 debugLog.printRTAriDebug (fn, ":Attempting to connect to "+hostname +" username="+username +" password="+password + " prompt='"+prompt +"' timeOut="+timeOut +" portNum="+portNum);
129 RouterName = hostname;
133 RouterName = hostname;
137 session = jsch.getSession(username, hostname, portNum);
138 UserInfo ui = new MyUserInfo();
139 session.setPassword(password);
140 session.setUserInfo(ui);
141 session.setConfig("StrictHostKeyChecking", "no");
142 debugLog.printRTAriDebug (fn, ":StrictHostKeyChecking set to 'no'");
144 session.connect(timeOut);
145 session.setServerAliveCountMax(0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
146 channel = session.openChannel("shell");
147 ((ChannelShell)channel).setPtyType("vt102");
148 inputStream = channel.getInputStream();
149 dis = new DataInputStream(inputStream);
150 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
152 debugLog.printRTAriDebug (fn, ":Successfully connected.");
153 debugLog.printRTAriDebug (fn, ":Flushing input buffer");
156 if (prompt.equals("]]>]]>"))
157 receiveUntil("]]>]]>", 10000, "No cmd was sent, just waiting");
159 receiveUntil(":~#", 5000, "No cmd was sent, just waiting");
163 debugLog.printRTAriDebug (fn, "Caught an Exception::: Nothing to flush out.");
168 debugLog.printRTAriDebug (fn, ":Caught an Exception. e="+e);
169 dbLog.outputStackTrace(e);
171 // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostname +" "+e);
172 throw new IOException(e.toString());
177 public String receiveUntil (String delimeters, int timeout, String cmdThatWasSent) throws TimedOutException, IOException
179 String fn = "SshJcraftWrapper.receiveUntil";
180 boolean match = false;
181 boolean cliPromptCmd = false;
182 StringBuffer sb2 = new StringBuffer();
183 StringBuffer sbReceive = new StringBuffer();
184 debugLog.printRTAriDebug (fn, "delimeters='"+delimeters +"' timeout="+timeout +" cmdThatWasSent='"+cmdThatWasSent +"'");
185 appendToFile(debugLogFileName, fn +" delimeters='"+delimeters +"' timeout="+timeout +" cmdThatWasSent='"+cmdThatWasSent +"'\n");
186 String CmdThatWasSent = removeWhiteSpaceAndNewLineCharactersAroundString(cmdThatWasSent);
188 aggregatedReceivedString = "";
190 long deadline = new Date().getTime() + timeout;
193 session.setTimeout(timeout); // This is the socket timeout value.
196 if(new Date().getTime() > deadline)
198 debugLog.printRTAriDebug (fn, "Throwing a TimedOutException: time in routine has exceed our deadline: RouterName:"+RouterName +" CmdThatWasSent="+ CmdThatWasSent);
199 throw new TimedOutException("Timeout: time in routine has exceed our deadline");
205 catch (java.lang.InterruptedException ee)
207 boolean ignore = true;
209 int len = reader.read(charBuffer, 0, BUFFER_SIZE);
210 appendToFile(debugLogFileName, fn +" After reader.read cmd: len="+len +"\n");
213 debugLog.printRTAriDebug (fn, "Reader read "+len +" bytes. Looks like we timed out, router="+RouterName);
214 throw new TimedOutException ("Received a SocketTimeoutException router="+RouterName);
218 if (cmdThatWasSent.indexOf("IOS_XR_uploadedSwConfigCmd") != -1)
222 // This is a IOS XR sw config file. We will write it to the disk.
223 timeout = timeout * 2;
224 deadline = new Date().getTime() + timeout;
225 debugLog.printRTAriDebug (fn, "IOS XR upload for software config: timeout="+timeout);
226 StringTokenizer st = new StringTokenizer(cmdThatWasSent);
228 routerFileName = st.nextToken();
229 out = new BufferedWriter(new FileWriter(routerFileName));
230 routerLogFileName = "/tmp/"+RouterName;
231 _tmpFile = new File(routerLogFileName);
232 debugLog.printRTAriDebug (fn, "Will write the swConfigFile to disk, routerFileName="+routerFileName);
235 out.write(charBuffer, 0, len);
237 appendToFile(debugLogFileName, fn +" Wrote "+len +" bytes to the disk\n");
238 if (_tmpFile.exists())
239 appendToRouterFile(routerLogFileName, len);
240 match = checkIfReceivedStringMatchesDelimeter(len, "\nXML>");
252 appendToFile(debugLogFileName, fn +" readCounts="+readCounts +" Reader read "+len +" of data\n");
255 for(int i=0; i<len; i++ )
258 if ((c != 7) && (c != 13) && (c != 0) && (c != 27))
260 sbReceive.append((char)charBuffer[i]);
261 sb2.append((char)charBuffer[i]);
264 appendToRouterFile("/tmp/"+RouterName, len);
265 if (listener != null)
266 listener.receivedString(sb2.toString());
268 appendToFile(debugLogFileName, fn +" Trace 1\n");
269 match = checkIfReceivedStringMatchesDelimeter(delimeters, sb2.toString(), cmdThatWasSent);
270 appendToFile(debugLogFileName, fn +" Trace 2\n");
273 appendToFile(debugLogFileName, fn +" Match was true, breaking...\n");
280 debugLog.printRTAriDebug (fn, "cliPromptCmd, Trace 2");
282 for(int i=0; i<len; i++ )
284 sbReceive.append( (char)charBuffer[i] );
285 sb2.append( (char)charBuffer[i] );
287 appendToRouterFile("/tmp/"+RouterName, sb2);
288 if (listener != null)
289 listener.receivedString(sb2.toString());
290 debugLog.printRTAriDebug (fn, "sb2='"+sb2.toString() +"' delimeters='" +delimeters +"'");
291 if (sb2.toString().indexOf("\nariPrompt>") != -1)
293 debugLog.printRTAriDebug (fn, "Found our prompt");
300 catch (JSchException e)
302 debugLog.printRTAriDebug (fn, "Caught an JSchException e="+e.toString());
303 dbLog.outputStackTrace(e);
304 throw new TimedOutException (e.toString());
306 catch (IOException ee)
308 debugLog.printRTAriDebug (fn, "Caught an IOException: ee="+ee.toString());
309 dbLog.outputStackTrace(ee);
310 throw new TimedOutException (ee.toString());
312 String result = stripOffCmdFromRouterResponse(sbReceive.toString());
313 debugLog.printRTAriDebug (fn, "Leaving method successfully");
317 public boolean checkIfReceivedStringMatchesDelimeter(String delimeters, String receivedString, String cmdThatWasSent)
319 // The delimeters are in a '|' seperated string. Return true on the first match.
320 String fn = "SshJcraftWrapper.checkIfReceivedStringMatchesDelimeter";
321 appendToFile(debugLogFileName, fn +" Entered: delimeters='"+delimeters +" cmdThatWasSent='"+cmdThatWasSent +"' receivedString='"+receivedString +"'\n");
322 StringTokenizer st = new StringTokenizer(delimeters, "|");
324 if ((delimeters.indexOf("#$") != -1) || (routerCmdType.equals("CLI"))) // This would be an IOS XR, CLI command.
326 int x = receivedString.lastIndexOf("#");
327 int y = receivedString.length() - 1;
328 appendToFile(debugLogFileName, fn +" IOS XR, CLI command\n");
329 if (extraDebugFile.exists())
330 appendToFile(debugLogFileName, fn +" :::cmdThatWasSent='"+cmdThatWasSent +"' x="+x +" y="+y +"\n");
331 if ((x != -1) && (y == x))
336 if (cmdThatWasSent.indexOf("show config") != -1)
338 appendToFile(debugLogFileName, fn +"In the block for 'show config'\n");
339 while (st.hasMoreTokens())
341 String delimeter = st.nextToken();
342 // Make sure we don't get faked out by a response of " #".
344 // # signaling-local-address ipv6 FD00:F4D5:EA06:1::110:136:254
346 int x = receivedString.lastIndexOf(delimeter);
347 if ((receivedString.lastIndexOf(delimeter) != -1) && (receivedString.lastIndexOf(" #") != x-1))
349 appendToFile(debugLogFileName, fn +"receivedString=\n'" +receivedString +"'\n");
350 appendToFile(debugLogFileName, fn +"Returning true for the 'show config' command. We found our real delmeter. \n\n");
357 aggregatedReceivedString = aggregatedReceivedString + receivedString;
358 _appendToFile ("/tmp/aggregatedReceivedString.debug", aggregatedReceivedString);
360 while (st.hasMoreTokens())
362 String delimeter = st.nextToken();
363 appendToFile(debugLogFileName, fn +" Looking for an delimeter of:'"+delimeter+"'\n");
364 appendToFile(debugLogFileName, fn +" receivedString='"+receivedString);
365 if (aggregatedReceivedString.indexOf(delimeter) != -1)
367 debugLog.printRTAriDebug (fn, "Found our delimeter, which was: '"+delimeter +"'");
368 aggregatedReceivedString = "";
376 public boolean checkIfReceivedStringMatchesDelimeter(int len, String delimeter)
378 String fnName = "SshJcraftWrapper.checkIfReceivedStringMatchesDelimeter:::";
383 if (jcraftReadSwConfigFileFromDisk())
385 DebugLog.printAriDebug(fnName, "jcraftReadSwConfigFileFromDisk block");
386 File fileName = new File(routerFileName);
387 appendToFile(debugLogFileName, fnName +" jcraftReadSwConfigFileFromDisk::: Will read the tail end of the file from the disk");
390 str = getLastFewLinesOfFile(fileName, 3);
392 catch (IOException e)
394 DebugLog.printAriDebug(fnName, "Caught an Exception, e="+e);
395 dbLog.outputStackTrace(e);
401 // DebugLog.printAriDebug(fnName, "TRACE 1: ******************************");
402 // When looking at the end of the charBuffer, don't include any linefeeds or spaces. We only want to make the smallest string possible.
403 for(x=len-1; x>=0; x--)
406 if (extraDebugFile.exists())
407 appendToFile(debugLogFileName, fnName +" x="+x +" c="+c +"\n");
408 if ((c != 10) && (c != 32)) // Not a line feed nor a space.
413 str = new String (charBuffer, (x+1-13), 13);
414 appendToFile(debugLogFileName, fnName +" str:'"+str +"'\n");
418 File fileName = new File(routerFileName);
419 appendToFile(debugLogFileName, fnName +" Will read the tail end of the file from the disk, x="+x +" len="+len +" str::'"+str +"' routerFileName='" +routerFileName +"'\n");
420 DebugLog.printAriDebug(fnName, "Will read the tail end of the file from the disk, x="+x +" len="+len +" str::'"+str +"' routerFileName='" +routerFileName +"'");
423 str = getLastFewLinesOfFile(fileName, 3);
425 catch (IOException e)
427 DebugLog.printAriDebug(fnName, "Caught an Exception, e="+e);
428 dbLog.outputStackTrace(e);
434 if (str.indexOf(delimeter) != -1)
436 DebugLog.printAriDebug(fnName, "str in break is:'"+str +"'" +" delimeter='" +delimeter +"'");
437 appendToFile(debugLogFileName, fnName +" str in break is:'"+str +" delimeter='" +delimeter +"'" +"'\n");
442 appendToFile(debugLogFileName, fnName +" Returning false");
448 public void closeConnection()
450 String fn = "SshJcraftWrapper.closeConnection";
451 debugLog.printRTAriDebug (fn, "Executing the closeConnection....");
456 session.disconnect();
460 public void send (String cmd) throws IOException
462 String fn = "SshJcraftWrapper.send";
463 OutputStream out = channel.getOutputStream();
464 DataOutputStream dos = new DataOutputStream(out);
466 if ((cmd.charAt(cmd.length() - 1) != '\n') && (cmd.charAt(cmd.length() - 1) != '\r'))
468 int length = cmd.length();
471 int ncharsTotalSent = 0;
474 appendToFile(debugLogFileName, fn+": Sending: '"+cmd );
475 // debugLog.printRTAriDebug (fn, "cmd = "+cmd);
476 debugLog.printRTAriDebug (fn, "Length of cmd is:" +length); // 2,937,706
482 for (i=0; i<length; i+=nchars)
484 String Cmd = cmd.substring(i, Math.min(length, i + nchars));
485 ncharsSent = Cmd.length();
486 ncharsTotalSent = ncharsTotalSent + Cmd.length();
487 debugLog.printRTAriDebug (fn, "i="+i +" Sending Cmd: ncharsSent="+ncharsSent);
492 debugLog.printRTAriDebug (fn, ":::i="+i +" length="+length);
493 if (ncharsSent < length)
494 receiveUntilBufferFlush (ncharsSent, timeout, "buffer flush i="+i);
497 debugLog.printRTAriDebug (fn, "i="+i +" No Waiting this time....");
503 debugLog.printRTAriDebug (fn, "Caught an Exception: Nothing to flush out.");
509 debugLog.printRTAriDebug (fn, "Before executing the dos.writeBytes");
513 debugLog.printRTAriDebug (fn, "Leaving method");
514 appendToFile(debugLogFileName, fn+": Leaving method\n");
516 catch (IOException e)
518 debugLog.printRTAriDebug (fn, "Caught an IOException. e="+e);
519 dbLog.outputStackTrace(e);
520 throw new IOException(e.toString());
525 public void sendChar (int v) throws IOException
527 String fn = "SshJcraftWrapper.sendChar";
528 OutputStream out = channel.getOutputStream();
529 DataOutputStream dos = new DataOutputStream(out);
532 debugLog.printRTAriDebug (fn, "Sending: '" +v +"'");
536 catch (IOException e)
538 debugLog.printRTAriDebug (fn, "Caught an IOException. e="+e);
539 throw new IOException(e.toString());
543 public void send (byte[] b, int off, int len) throws IOException
545 String fn = "SshJcraftWrapper.send:byte[]";
546 OutputStream out = channel.getOutputStream();
547 DataOutputStream dos = new DataOutputStream(out);
550 dos.write (b, off, len);
553 catch (IOException e)
555 debugLog.printRTAriDebug (fn, "Caught an IOException. e="+e);
556 throw new IOException(e.toString());
560 public static class MyUserInfo implements UserInfo, UIKeyboardInteractive
562 public String getPassword()
566 public boolean promptYesNo(String str)
570 public String getPassphrase()
574 public boolean promptPassphrase(String message)
578 public boolean promptPassword(String message)
582 public void showMessage(String message)
584 public String[] promptKeyboardInteractive(String destination,
594 public void addListener(TelnetListener listener)
596 this.listener = listener;
599 public void appendToFile (String fileName, String dataToWrite)
601 String fn = "SshJcraftWrapper.appendToFile";
605 // First check to see if a file 'fileName' exist, if it does
606 // write to it. If it does not exist, don't write to it.
607 File tmpFile = new File(fileName);
608 if (tmpFile.exists())
610 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
611 // out.write(dataToWrite);
612 // out.write(getTheDate() +": " +Thread.currentThread().getName() +": "+dataToWrite);
613 out.write(getTheDate() +": " +tId +": "+dataToWrite);
617 catch (IOException e)
619 debugLog.printRTAriDebug (fn, "Caught an IOException: e="+e);
623 debugLog.printRTAriDebug (fn, "Caught an Exception: e="+e);
627 public void _appendToFile (String fileName, String dataToWrite)
629 String fn = "SshJcraftWrapper.appendToFile";
633 // First check to see if a file 'fileName' exist, if it does
634 // write to it. If it does not exist, don't write to it.
635 File tmpFile = new File(fileName);
636 if (tmpFile.exists())
638 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
639 out.write(dataToWrite);
643 catch (IOException e)
645 debugLog.printRTAriDebug (fn, "Caught an IOException: e="+e);
649 debugLog.printRTAriDebug (fn, "Caught an Exception: e="+e);
654 public String getTheDate()
656 Calendar cal = Calendar.getInstance();
657 java.util.Date today = cal.getTime();
658 DateFormat df1 = DateFormat.getDateInstance();
659 DateFormat df3 = new SimpleDateFormat("MM/dd/yyyy H:mm:ss ");
660 return (df3.format(today));
664 public void appendToRouterFile (String fileName, StringBuffer dataToWrite)
666 String fnName = "SshJcraftWrapper.appendToRouterFile";
667 debugLog.printRTAriDebug (fnName, "Entered.... ");
670 // First check to see if a file 'fileName' exist, if it does
671 // write to it. If it does not exist, don't write to it.
672 File tmpFile = new File(fileName);
674 // if ((tmpFile.exists()) && (tmpFile.setWritable(true, true)))
675 if (tmpFile.exists())
677 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
678 // out.write("<!-- "+getTheDate() +": " +tId +" -->\n");
679 out.write(dataToWrite.toString());
684 catch (IOException e)
686 System.err.println("writeToFile() exception: " + e);
691 public void appendToRouterFile (String fileName, int len)
693 String fnName = "SshJcraftWrapper.appendToFile";
694 // debugLog.printRTAriDebug (fnName, "Entered.... len="+len);
697 // First check to see if a file 'fileName' exist, if it does
698 // write to it. If it does not exist, don't write to it.
699 File tmpFile = new File(fileName);
700 // if ((tmpFile.exists()) && (tmpFile.setWritable(true, true)))
701 if (tmpFile.exists())
703 BufferedWriter out = new BufferedWriter(new FileWriter(fileName, true));
704 // out.write("<!-- "+getTheDate() +": " +tId +" -->\n");
705 out.write(charBuffer, 0, len);
709 catch (IOException e)
711 System.err.println("writeToFile() exception: " + e);
716 public String removeWhiteSpaceAndNewLineCharactersAroundString(String str)
720 StringTokenizer strTok = new StringTokenizer(str, "\n");
721 StringBuffer sb = new StringBuffer();
723 while (strTok.hasMoreTokens())
725 String line = strTok.nextToken();
728 return (sb.toString().trim());
734 public String stripOffCmdFromRouterResponse(String routerResponse)
736 String fn = "SshJcraftWrapper.stripOffCmdFromRouterResponse";
737 // appendToFile(debugLogFileName, fn+": routerResponse='"+routerResponse +"'\n");
739 // The session of SSH will echo the command sent to the router, in the router's response.
740 // Since all our commands are terminated by a '\n', strip off the first line
741 // of the response from the router. This first line contains the orginal command.
743 StringTokenizer rr = new StringTokenizer(routerResponse, "\n");
744 StringBuffer sb = new StringBuffer();
746 int numTokens = rr.countTokens();
747 // debugLog.printRTAriDebug (fn, "Number of lines in the response from the router is:" +numTokens);
750 rr.nextToken(); //Skip the first line.
751 while (rr.hasMoreTokens())
753 sb.append(rr.nextToken()+'\n');
756 return (sb.toString());
759 public void setRouterCommandType(String type)
761 String fn = "SshJcraftWrapper.setRouterCommandType";
762 this.routerCmdType = type;
763 debugLog.printRTAriDebug (fn, "Setting routerCmdType to a value of '"+type +"'");
766 public String getLastFewLinesOfFile(File file, int linesToRead) throws FileNotFoundException, IOException
768 String fn = "SshJcraftWrapper.getLastFewLinesOfFile";
769 RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
771 StringBuilder builder = new StringBuilder();
773 long length = file.length();
775 randomAccessFile.seek(length);
776 for(long seek = length; seek >= 0; --seek)
778 randomAccessFile.seek(seek);
779 char c = (char)randomAccessFile.read();
783 builder = builder.reverse();
784 // System.out.println(builder.toString());
785 tail = builder.toString() + tail;
787 builder.setLength(0);
788 if (lines == linesToRead)
794 randomAccessFile.close();
795 if(!jcraftReadSwConfigFileFromDisk())
796 debugLog.printRTAriDebug (fn, "tail='"+tail +"'");
797 appendToFile(debugLogFileName, "tail='"+tail +"'\n");
801 public boolean jcraftReadSwConfigFileFromDisk()
803 if (jcraftReadSwConfigFileFromDisk.exists())
809 public String getEquipNameCode()
811 return (equipNameCode);
815 public void setEquipNameCode(String equipNameCode)
817 this.equipNameCode = equipNameCode;
820 public String getRouterName()
825 // Routine does reads until it has read 'nchars' or times out.
826 public void receiveUntilBufferFlush (int ncharsSent, int timeout, String message) throws TimedOutException, IOException
828 String fn = "SshJcraftWrapper.receiveUntilBufferFlush";
829 StringBuffer sb2 = new StringBuffer();
830 StringBuffer sbReceive = new StringBuffer();
831 debugLog.printRTAriDebug (fn, "ncharsSent="+ncharsSent+" timeout="+timeout +" "+message);
832 int ncharsTotalReceived = 0;
834 boolean flag = false;
835 charactersFromBufferFlush.setLength(0);
837 long deadline = new Date().getTime() + timeout;
841 session.setTimeout(timeout); // This is the socket timeout value.
844 if(new Date().getTime() > deadline)
846 debugLog.printRTAriDebug (fn, "Throwing a TimedOutException: time in routine has exceed our deadline: ncharsSent="+ncharsSent+" ncharsTotalReceived="+ncharsTotalReceived);
848 throw new TimedOutException("Timeout: time in routine has exceed our deadline");
850 ncharsRead = reader.read(charBuffer, 0, BUFFER_SIZE);
851 if (listener != null)
852 listener.receivedString(String.copyValueOf(charBuffer,0,ncharsRead));
853 appendToRouterFile("/tmp/"+RouterName, ncharsRead);
854 ncharsTotalReceived = ncharsTotalReceived + ncharsRead;
855 // debugLog.printRTAriDebug (fn, "::ncharsSent="+ncharsSent+" ncharsTotalReceived="+ncharsTotalReceived +" ncharsRead="+ncharsRead);
856 if (ncharsTotalReceived >= ncharsSent)
858 debugLog.printRTAriDebug (fn, "Received the correct number of characters, ncharsSent="+ncharsSent +" ncharsTotalReceived="+ncharsTotalReceived);
864 catch (JSchException e)
866 debugLog.printRTAriDebug (fn, "Caught an JSchException e="+e.toString());
867 debugLog.printRTAriDebug (fn, "ncharsSent="+ncharsSent+" ncharsTotalReceived="+ncharsTotalReceived +" ncharsRead="+ncharsRead);
868 throw new TimedOutException (e.toString());
872 public String getHostName()
877 public String getUserName()
882 public String getPassWord()
887 public void sftpPut(String sourcePath, String destDirectory) throws IOException
889 String fn = "SshJcraftWrapper.sftp";
892 Session sftpSession = jsch.getSession(userName, hostName, 22);
893 UserInfo ui = new MyUserInfo();
894 sftpSession.setPassword(passWord);
895 sftpSession.setUserInfo(ui);
896 sftpSession.connect(30*1000);
897 debugLog.printRTAriDebug (fn, "Opening up an sftp channel....");
898 ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp");
899 debugLog.printRTAriDebug (fn, "Connecting....");
901 debugLog.printRTAriDebug (fn, "Sending "+sourcePath +" --> "+destDirectory);
902 sftp.put(sourcePath, destDirectory, ChannelSftp.OVERWRITE);
903 debugLog.printRTAriDebug (fn, "Sent successfully");
904 sftpSession.disconnect();
908 debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e);
909 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
910 throw new IOException(e.toString());
916 public void SftpPut(String stringOfData, String fullPathDest) throws IOException
918 String fn = "SshJcraftWrapper.Sftp";
921 Session sftpSession = jsch.getSession(userName, hostName, 22);
922 UserInfo ui = new MyUserInfo();
923 sftpSession.setPassword(passWord);
924 sftpSession.setUserInfo(ui);
925 sftpSession.connect(30*1000);
926 debugLog.printRTAriDebug (fn, "Opening up an sftp channel....");
927 ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp");
928 debugLog.printRTAriDebug (fn, "Connecting....");
930 InputStream is = new ByteArrayInputStream(stringOfData.getBytes());
931 debugLog.printRTAriDebug (fn, "Sending stringOfData --> "+fullPathDest);
932 sftp.put(is, fullPathDest, ChannelSftp.OVERWRITE);
933 debugLog.printRTAriDebug (fn, "Sent successfully");
934 sftpSession.disconnect();
938 debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e);
939 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
940 throw new IOException(e.toString());
944 public String sftpGet(String fullFilePathName) throws IOException
946 String fn = "SshJcraftWrapper.Sftp";
949 Session sftpSession = jsch.getSession(userName, hostName, 22);
950 UserInfo ui = new MyUserInfo();
951 sftpSession.setPassword(passWord);
952 sftpSession.setUserInfo(ui);
953 sftpSession.connect(30*1000);
954 debugLog.printRTAriDebug (fn, "Opening up an sftp channel....");
955 ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp");
956 debugLog.printRTAriDebug (fn, "Connecting....");
958 InputStream in = null;
959 in = sftp.get(fullFilePathName);
960 String sftpFileString = readInputStreamAsString(in);
961 debugLog.printRTAriDebug (fn, "Retreived successfully");
962 // debugLog.printRTAriDebug (fn, "sftpFileString="+sftpFileString);
963 sftpSession.disconnect();
964 return(sftpFileString);
968 debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e);
969 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
970 throw new IOException(e.toString());
974 public static String readInputStreamAsString(InputStream in) throws IOException
976 BufferedInputStream bis = new BufferedInputStream(in);
977 ByteArrayOutputStream buf = new ByteArrayOutputStream();
978 int result = bis.read();
981 byte b = (byte)result;
985 return buf.toString();
989 public void logMemoryUsage()
991 String fn = "SshJcraftWrapper.logMemoryUsage";
994 long maxMemoryAdvailable;
995 long memoryLetfOnHeap;
996 maxMemoryAdvailable = (runtime.maxMemory() / mb);
997 usedMemory = ((runtime.totalMemory()/mb) - (runtime.freeMemory()/mb));
998 memoryLetfOnHeap = maxMemoryAdvailable - usedMemory;
999 DebugLog.printAriDebug(fn, "maxMemoryAdvailable="+maxMemoryAdvailable +" usedMemory="+usedMemory +" memoryLetfOnHeap="+memoryLetfOnHeap);
1002 // ----------------------------------------------------------------------------
1003 // ----------------------------------------------------------------------------
1004 // ----------------------------------------------------------------------------
1005 // ----------------------------------------------------------------------------
1008 // User specifies the port number, and the subsystem
1009 public void connect (String hostname, String username, String password, String prompt, int timeOut, int portNum, String subsystem) throws IOException
1011 String fn = "SshJcraftWrapper.connect";
1013 debugLog.printRTAriDebug (fn, ":::Attempting to connect to "+hostname +" username="+username +" password="+password + " prompt='"+prompt +"' timeOut="+timeOut +" portNum="+portNum +" subsystem="+subsystem);
1014 RouterName = hostname;
1018 session = jsch.getSession(username, hostname, portNum);
1019 UserInfo ui = new MyUserInfo();
1020 session.setPassword(password);
1021 session.setUserInfo(ui);
1022 session.setConfig("StrictHostKeyChecking", "no");
1023 session.connect(timeOut);
1024 session.setServerAliveCountMax(0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
1025 channel = session.openChannel("subsystem");
1026 ((ChannelSubsystem)channel).setSubsystem(subsystem);
1027 // ((ChannelSubsystem)channel).setPtyType("vt102");
1028 ((ChannelSubsystem)channel).setPty(true);
1030 inputStream = channel.getInputStream();
1031 dis = new DataInputStream(inputStream);
1032 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
1034 debugLog.printRTAriDebug (fn, "Successfully connected.");
1035 debugLog.printRTAriDebug (fn, "Five second sleep....");
1036 try { Thread.sleep(5000); } catch (java.lang.InterruptedException ee) { boolean ignore = true; }
1040 debugLog.printRTAriDebug (fn, "Caught an Exception. e="+e);
1041 throw new IOException(e.toString());
1045 public void connect (String hostName, String username, String password, int portNumber) throws IOException
1047 String fn = "SshJcraftWrapper.connect";
1049 debugLog.printRTAriDebug (fn, "::Attempting to connect to "+hostName +" username="+username +" password="+password +" portNumber="+portNumber);
1050 debugLog.printRTAriDebug (fn, "Trace C");
1051 RouterName = hostName;
1052 this.hostName = hostName;
1053 userName = username;
1054 passWord = password;
1057 java.util.Properties config = new java.util.Properties();
1058 config.put("StrictHostKeyChecking", "no");
1059 session = jsch.getSession(username, hostName, 22);
1060 // session = jsch.getSession(username, hostName, portNumber);
1061 UserInfo ui = new MyUserInfo();
1062 session.setConfig(config);
1063 session.setPassword(password);
1064 session.setUserInfo(ui);
1065 session.connect(30000);
1066 channel = session.openChannel("shell");
1067 session.setServerAliveCountMax(0); // If this is not set to '0', then socket timeout on all reads will not work!!!!
1068 ((ChannelShell)channel).setPtyType("vt102");
1069 inputStream = channel.getInputStream();
1070 dis = new DataInputStream(inputStream);
1071 reader = new BufferedReader(new InputStreamReader(dis), BUFFER_SIZE);
1073 debugLog.printRTAriDebug (fn, "::Successfully connected.");
1074 debugLog.printRTAriDebug (fn, "::Flushing input buffer");
1077 receiveUntil(":~#", 9000, "No cmd was sent, just waiting, but we can stop on a '~#'");
1081 debugLog.printRTAriDebug (fn, "Caught an Exception::: Nothing to flush out.");
1087 debugLog.printRTAriDebug (fn, "Caught an Exception. e="+e);
1088 // dbLog.storeData("ErrorMsg= Exception trying to connect to "+hostName +" "+e);
1089 throw new IOException(e.toString());
1094 public void put(String sourcePath, String destDirectory) throws IOException
1096 String fn = "SshJcraftWrapper.sftp";
1099 Session sftpSession = jsch.getSession(userName, hostName, 22);
1100 UserInfo ui = new MyUserInfo();
1101 sftpSession.setPassword(passWord);
1102 sftpSession.setUserInfo(ui);
1103 sftpSession.connect(30*1000);
1104 debugLog.printRTAriDebug (fn, "Opening up an sftp channel....");
1105 ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp");
1106 debugLog.printRTAriDebug (fn, "Connecting....");
1108 debugLog.printRTAriDebug (fn, "Sending "+sourcePath +" --> "+destDirectory);
1109 sftp.put(sourcePath, destDirectory, ChannelSftp.OVERWRITE);
1110 debugLog.printRTAriDebug (fn, "Sent successfully");
1111 sftpSession.disconnect();
1115 debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e);
1116 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
1117 throw new IOException(e.toString());
1121 public void put(InputStream is, String fullPathDest, String hostName, String userName, String passWord) throws IOException
1123 String fn = "SshJcraftWrapper.put";
1124 Session sftpSession = null;
1127 debugLog.printRTAriDebug (fn, "userName="+userName +" hostName="+hostName +" passWord="+passWord);
1129 java.util.Properties config = new java.util.Properties();
1130 config.put("StrictHostKeyChecking", "no");
1131 sftpSession = jsch.getSession(userName, hostName, 22);
1132 UserInfo ui = new MyUserInfo();
1133 sftpSession.setPassword(passWord);
1134 sftpSession.setUserInfo(ui);
1135 sftpSession.setConfig(config);
1136 sftpSession.connect(30*1000);
1137 debugLog.printRTAriDebug (fn, "Opening up an sftp channel....");
1138 ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp");
1139 debugLog.printRTAriDebug (fn, "Connecting....");
1141 String oldFiles = fullPathDest +"*";
1142 debugLog.printRTAriDebug (fn, "Deleting old files --> "+oldFiles);
1145 debugLog.printRTAriDebug (fn, "Sending stringOfData --> "+fullPathDest);
1147 catch(SftpException sft){
1148 String exp = "No such file";
1149 if(sft.getMessage()!=null && sft.getMessage().contains(exp))
1150 debugLog.printRTAriDebug (fn, "No files found -- Continue");
1152 debugLog.printRTAriDebug (fn, "Exception while sftp.rm " + sft.getMessage());
1153 sft.printStackTrace();
1157 sftp.put(is, fullPathDest, ChannelSftp.OVERWRITE);
1158 debugLog.printRTAriDebug (fn, "Sent successfully");
1159 sftpSession.disconnect();
1164 debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e);
1165 sftpSession.disconnect();
1167 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
1168 throw new IOException(e.toString());
1173 public String get(String fullFilePathName, String hostName, String userName, String passWord) throws IOException
1175 String fn = "SshJcraftWrapper.get";
1176 Session sftpSession = null;
1179 debugLog.printRTAriDebug (fn, "userName="+userName +" hostName="+hostName +" passWord="+passWord);
1181 sftpSession = jsch.getSession(userName, hostName, 22);
1182 java.util.Properties config = new java.util.Properties();
1183 config.put("StrictHostKeyChecking", "no");
1184 UserInfo ui = new MyUserInfo();
1185 sftpSession.setPassword(passWord);
1186 sftpSession.setUserInfo(ui);
1187 sftpSession.setConfig(config);
1188 sftpSession.connect(30*1000);
1189 debugLog.printRTAriDebug (fn, "Opening up an sftp channel....");
1190 ChannelSftp sftp=(ChannelSftp)sftpSession.openChannel("sftp");
1191 debugLog.printRTAriDebug (fn, "Connecting....");
1193 InputStream in = null;
1194 in = sftp.get(fullFilePathName);
1195 String sftpFileString = readInputStreamAsString(in);
1196 debugLog.printRTAriDebug (fn, "Retreived successfully");
1197 // debugLog.printRTAriDebug (fn, "sftpFileString="+sftpFileString);
1198 sftpSession.disconnect();
1200 return(sftpFileString);
1204 debugLog.printRTAriDebug (fn, "Caught an Exception, e="+e);
1205 sftpSession.disconnect();
1207 // dbLog.storeData("ErrorMsg= sftp threw an Exception. error is:"+e);
1208 throw new IOException(e.toString());
1212 public String send(String cmd, String delimiter) throws IOException
1214 String fn = "SshJcraftWrapper.send";
1215 OutputStream out = channel.getOutputStream();
1216 DataOutputStream dos = new DataOutputStream(out);
1218 if ((cmd.charAt(cmd.length() - 1) != '\n') && (cmd.charAt(cmd.length() - 1) != '\r'))
1220 int length = cmd.length();
1222 int nchars = 300000;
1223 int ncharsTotalSent = 0;
1226 debugLog.printRTAriDebug (fn, "Length of cmd is:" +length); // 2,937,706
1227 debugLog.printRTAriDebug (fn, "Length of cmd is:" +length); // 2,937,706
1230 if (length > 600000)
1233 for (i=0; i<length; i+=nchars)
1235 String Cmd = cmd.substring(i, Math.min(length, i + nchars));
1236 ncharsSent = Cmd.length();
1237 ncharsTotalSent = ncharsTotalSent + Cmd.length();
1238 debugLog.printRTAriDebug (fn, "i="+i +" Sending Cmd: ncharsSent="+ncharsSent);
1239 dos.writeBytes(Cmd);
1243 debugLog.printRTAriDebug (fn, ":::i="+i +" length="+length);
1244 if (ncharsSent < length)
1245 receiveUntilBufferFlush (ncharsSent, timeout, "buffer flush i="+i);
1248 debugLog.printRTAriDebug (fn, "i="+i +" No Waiting this time....");
1254 debugLog.printRTAriDebug (fn, "Caught an Exception: Nothing to flush out.");
1260 debugLog.printRTAriDebug (fn, "Before executing the dos.writeBytes");
1261 dos.writeBytes(cmd);
1264 // Now lets get the response.
1265 String response = receiveUntil (delimiter, 300000, cmd);
1266 debugLog.printRTAriDebug (fn, "Leaving method");
1269 catch (IOException e)
1271 debugLog.printRTAriDebug (fn, "Caught an IOException. e="+e);
1272 throw new IOException(e.toString());