1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
| package snec.models.audit.auditModel.client.connectionClient;
import...
/**
* Class which allow the software to connect to a telnet server and execute instructions on it.
*/
public class AuditSSHClient implements AuditClient {
/*----------------------------------------------------------------
* Attributes
------------------------------------------------------------------*/
/**
* The Hop list associated with the equipment.
*/
private ArrayList<ConnectInfo> hop;
/**
* Indicate if the client is connected to the remote server.
*/
private boolean isConnected;
/**
* Indicate if the client is logged to the remote server.
*/
private boolean isLogged;
/**
* The current hop used by the ConnecInfo.
*/
private int currentHop = 0;
/**
* SSH Session.
*/
private Session sess;
/**
* String indicating if the connection failed or not.
*/
private String failed = "";
/**
* The SSH connection.
*/
private Connection conn;
/**
* The input stream of the ssh ConnecInfo.
*/
private InputStream sshIn;
/**
* The output stream of the ssh ConnecInfo.
*/
private OutputStream sshOut;
/**
* The equipment log file where are written some information.
*/
private SnecFile loadingLog;
/**
* The operation log file where are written some information.
*/
private SnecFile operationLogFile;
/**
* Boolean managing the end of the current command.
*/
private boolean nextCommand;
/**
* The skeleton containing all the class functions that this audit client needs.
*/
private AuditSkeleton skeleton;
/**
* The flow that we display in the progress panel flow text since the previous "change" calling.
*/
private String buffer;
/**
* The remaining time to display in the progress panel (for the current command).
*/
private String timeToDisplay = "";
/**
* The connection type ( = SSH).
*/
private String type;
/**
* The object allowing graphical updates by calling the "change" method.
*/
private AuditModel auditModel;
/**
* The boolean attribut refers to the good execution of a command.
*/
private boolean commandStatus;
/*-----------------------------------------------------------------
* Constructors
-------------------------------------------------------------------*/
/**
* Construct a new AuditSSHClient using a list of hops.
* @param listHop The list of the hopes which will be used to connect to the final remote server.
*/
public AuditSSHClient(Equipment equipment) {
this.type = "SSH";
this.hop = equipment.getHopListInfo();
this.nextCommand = false;
this.skeleton = new AuditSkeleton(this);
this.auditModel = equipment.getAuditModel();
}
/**
* Connect the software to a remote server.
* @return Indicate if the ConnecInfo attempt is a success.
*/
public boolean connect() {
//get the log files associated to the current equipment.
this.loadingLog = AuditModel.getCurrentEquipment().getLoadingLogfile();
this.operationLogFile = AuditModel.getCurrentEquipment().getOperationLogfile();
this.timeToDisplay = "Try to connect on " + this.hop.get(0).getHostname();
this.change();
this.conn = new Connection(this.hop.get(0).getHostname(), this.hop.get(0).getPort());
try {
ConnectionInfo connectInfoTemp = this.conn.connect();
// If connection is available
if (connectInfoTemp != null) {
this.loadingLog.writeFile("[Date] : SNEC is connected to the remote server (" + this.hop.get(0).getHostname() + ") by SSH");
this.isConnected = true;
}
} catch (IOException E02) {
this.loadingLog.writeFile("[Date] : SNEC can't connect the remote server (" + this.hop.get(0).getHostname() + ") by SSH ! ( " + E02.getMessage() + " )");
this.isConnected = false;
return false;
}
this.currentHop = 0;
while (this.currentHop < this.hop.size() && this.isConnected) {
this.isConnected = this.logon();
this.currentHop++;
}
this.currentHop--;
return this.isConnected;
}
/**
* Disconnect from the remote server.
**/
public void disconnect() {
if (this.isConnected) {
try {
this.sess.close();
this.conn.close();
this.loadingLog.writeFile("[Date] : SNEC is disconnected from the remote server");
} catch (Exception ECT03) {
this.loadingLog.writeFile("[Date] : [ECT03] Can't close the " + this.type + " connection ! ( " + ECT03.getMessage() + " )");
}
}
}
/**
* Connect the the software to a ssh hop
* @param hop The ConnecInfo hop
* @param number The number of the hop
* @return the result of the ConnecInfo
*/
public boolean ConnectHop(ConnectInfo hop, int number) {
return this.skeleton.ConnectHop(hop, number);
}
/**
* Log the software on the remote server.
* @return Indicate if the login attempt was a success.
*/
private boolean logon() {
if (this.currentHop == 0 && this.conn.isAuthenticationComplete() == false) {
try {
this.isLogged = this.conn.authenticateWithPassword(this.hop.get(this.currentHop).getLogin(), this.hop.get(this.currentHop).getPassword());
if (this.isLogged) {
this.sess = this.conn.openSession();
this.sess.requestDumbPTY();
this.sess.startShell();
this.sshOut = this.sess.getStdin();
this.sshIn = this.sess.getStdout();
this.loadingLog.writeFile("[Date] : The LoginPrompt <" + this.hop.get(0).getLoginPrompt() + "> was found");
this.loadingLog.writeFile("[Date] : The PasswordPrompt <" + this.hop.get(0).getPasswordPrompt() + "> was found");
this.waitFor(this.hop.get(0).getPrompt(), 10);
if (this.commandStatus == false) {
this.loadingLog.writeFile("[Date] : The Prompt is wrong ! <" + this.hop.get(0).getPrompt() + "> expected, <" + this.failed + "> found");
this.loadingLog.writeFile("[Date] : SNEC can't log to the remote server !");
return false;
} else {
this.loadingLog.writeFile("[Date] : SNEC is logged to the remote server with the " + this.hop.get(0).getLogin() + " account");
return true;
}
} else {
this.loadingLog.writeFile("[Date] : Wrong parameter(s) ! ");
this.loadingLog.writeFile("[Date] : - Prompt : <" + this.hop.get(0).getPrompt() + "> expected");
this.loadingLog.writeFile("[Date] : - Login prompt : " + this.hop.get(0).getLoginPrompt() + " found");
this.loadingLog.writeFile("[Date] : - Password prompt : " + this.hop.get(0).getPasswordPrompt() + " found");
this.loadingLog.writeFile("[Date] : SNEC can't log on the remote server with the " + this.hop.get(0).getLogin() + " account !");
return false;
}
} catch (IOException E) {
this.loadingLog.writeFile("[Date] : SNEC can't log on the remote server with the " + this.hop.get(0).getLogin() + " account ! ( " + E.getMessage() + " )");
E.printStackTrace();
return false;
}
} else {
int hopNumberToDisplay = this.currentHop + 1;
this.loadingLog.writeFile("[Date] : SNEC try to connect to the hop number " + hopNumberToDisplay + " (" + this.hop.get(this.currentHop).getHostname() + ") by " + this.hop.get(this.currentHop).getProtocol());
return this.ConnectHop(this.hop.get(this.currentHop), this.currentHop);
}
}
/**
* Send a new integer on the remote server, to skip the executing command
* @param value The integer which will be send to the remote server.
*/
public void write(int value) {
try {
this.sshOut.write(value);
} catch (Exception ECT04) {
this.operationLogFile.writeFile("[Date] : [ECT04] Can't write on the remote server ! " + ECT04.getMessage());
}
}
/**
* Wait for the delay 'duree' and read all InputStream data during this period.
* @param duree The time limit of the operation.
* @return All the data which were read until the time limit.
*/
public String wait(int duree) {
//The String Buffer which will contains the response of the server
StringBuffer in = new StringBuffer();
//The string containing the remote response of this command
String response = "";
//Get the input stream of the telnet connection
InputStream sshInput = this.sess.getStdout();
// Gets the present time
Calendar endTime = Calendar.getInstance();
endTime.add(Calendar.SECOND, duree);
while (Calendar.getInstance().before(endTime)) {
try {
while (sshInput.available() != 0 && Calendar.getInstance().before(endTime)) {
//if there are bytes that can be read
in.append((char) sshInput.read());
}
//Get the present response
this.buffer = in.toString();
//Delete the previous response stocks in the string buffer "in"
in.delete(0, in.length());
//Store up the previous remote responses
response += this.buffer;
Calendar currentTime = Calendar.getInstance();
this.timeToDisplay = String.valueOf((endTime.getTimeInMillis() - currentTime.getTimeInMillis()) / 1000);
if (this.buffer.contains("\n")) {
this.change();
}
//check if user wants to stop this command.
if (this.nextCommand) {
this.nextCommand = false;
this.commandStatus = false;
return response;
}
} catch (IOException E) {
//if istream.available() create an error
this.operationLogFile.writeFile("[Date] : [ERROR] The SSH flow was interrupted by the system ( " + E.getMessage() + " )");
}
}
this.commandStatus = true;
return response;
}
/**
* Receive the data coming from the remote server in a passive mode until a specific pattern is recognized.
* @param Pattern The pattern which need to be recognized.
* @param timeout The time limit of the operation
* @return All the data which were read until the recognition of the pattern.
*/
public String waitFor(String Pattern, int timeout) {
//The String Buffer which will contains the response of the server
StringBuffer in = new StringBuffer();
//The string containing the remote response of this command
String response = "";
//Get the input stream of the SSH connection
InputStream sshInput = this.sess.getStdout();
//The objects that will identify the pattern
Pattern Identifier2;
Matcher Match2;
Pattern = Pattern.replace("\\", "\\\\");
Pattern = Pattern.replace("[", "\\[");
Pattern = Pattern.replace("]", "\\]");
Pattern = Pattern.replace("^", "\\^");
Pattern = Pattern.replace("(", "\\(");
Pattern = Pattern.replace(")", "\\)");
Pattern = Pattern.replace("&", "\\&)");
Pattern = Pattern.replace(".", "\\.");
Pattern = Pattern.replace("*", "(.)*");
Pattern = Pattern.replace("{", "\\{");
Pattern = Pattern.replace("}", "\\}");
Pattern = Pattern.replace("?", ".");
int i = 0;
int j = 0;
for (i = 0; i < Pattern.length(); i++) {
if (Pattern.charAt(i) != '.') {
break;
}
j++;
}
if (i != 0) {
Pattern = Pattern.substring(i);
}
//Creation of the regex compiler
Identifier2 = java.util.regex.Pattern.compile(Pattern.toLowerCase());
//Indicate if the pattern was found
boolean pattFound = false;
// Timeout is set
// Gets the present time
Calendar endTime = Calendar.getInstance();
Calendar currentTime = Calendar.getInstance();
// Variables used to display correctly the timeout remaining
long timeoutRemaining;
// Adds the timeout at the present time
endTime.add(Calendar.SECOND, timeout);
//launch a unending loop
while (true) {
try {
while (Calendar.getInstance().before(endTime) && sshInput.available() == 0) {
try {
if (this.nextCommand) {
this.setNextCommand(false);
this.commandStatus = false;
return response;
}
Thread.sleep(250);
currentTime = Calendar.getInstance();
timeoutRemaining = (endTime.getTimeInMillis() - currentTime.getTimeInMillis()) / 1000;
String time = this.timeToDisplay;
this.timeToDisplay = String.valueOf(timeoutRemaining);
if (!time.equalsIgnoreCase(this.timeToDisplay)) {
//Update the time expiration.
this.change();
}
} catch (InterruptedException E2) {
this.operationLogFile.writeFile("[Date] : [ERROR] The thread was interrupted by the system (" + E2.getMessage() + ")");
E2.printStackTrace();
}
}
} catch (IOException E3) {
this.operationLogFile.writeFile("[Date] : [ERROR] The SSH flow was interrupted by the system ( " + E3.getMessage() + " )");
E3.printStackTrace();
}
if (!Calendar.getInstance().before(endTime)) {
this.operationLogFile.writeFile("[Date] : Timeout expired !");
Pattern spl = java.util.regex.Pattern.compile("\r\n|\n|\r|\u0085|\u2028|\u2029");
String[] lines = spl.split(response);
Matcher m = Identifier2.matcher(lines[lines.length - 1].toLowerCase());
if (!m.find()) {
if (lines[lines.length - 1].toLowerCase().contains("more") || lines[lines.length - 1].toLowerCase().contains("press any")) {
PrintStream out = new PrintStream(this.sshOut);
out.print(" ");
out.flush();
// Gets the present time
endTime = Calendar.getInstance();
// Adds the timeout at the present time
endTime.add(Calendar.SECOND, timeout);
} // Case Omni6800
else if (lines[lines.length - 1].toLowerCase().contains("next line <cr>")) {
PrintStream out = new PrintStream(this.sshOut);
out.print(" ");
out.flush();
endTime = Calendar.getInstance();
// Adds the timeout at the present time
endTime.add(Calendar.SECOND, timeout);
} else {
this.failed = response;
this.operationLogFile.writeFile("[Date] : [ERROR] The prompt \"" + Identifier2.toString() + "\" was not found before timeout expiration. Check your command timeout !");
this.commandStatus = false;
return response;
}
} else {
this.operationLogFile.writeFile("[Date] : [ERROR] The prompt timeout \"" + Identifier2.toString() + "\" is too short !");
this.commandStatus = false;
return response;
}
}
try {
//Checks if any characters are waited over the session
while (sshInput.available() != 0 && in.length() < 10000) {
in.append((char) sshInput.read());
}
//Get the present response
this.buffer = in.toString();
//Delete the previous response stocks in the string buffer "in"
in.delete(0, in.length());
//Store up the previous remote responses
response += this.buffer;
//Update the flow text(s)
if (this.buffer.contains("\n")) {
this.change();
}
//allow user to stop this command.
if (this.nextCommand) {
this.setNextCommand(false);
this.commandStatus = false;
return response;
}
endTime = Calendar.getInstance();
endTime.add(Calendar.SECOND, timeout);
} catch (IOException E) {
this.operationLogFile.writeFile("[Date] : [ERROR] Can't check the flow over the session ! (" + E.getMessage() + ")");
}
Pattern spl = java.util.regex.Pattern.compile("\r\n|\n|\r|\u0085|\u2028|\u2029");
String[] lines = spl.split(response);
if (lines.length >= 1) {
// Checks if a "more" has been find in input stream
if (lines[lines.length - 1].toLowerCase().contains("more") || lines[lines.length - 1].toLowerCase().contains("press any")) {
PrintStream out = new PrintStream(this.sshOut);
out.print(" ");
out.flush();
} // Case Omni6800
else if (lines[lines.length - 1].toLowerCase().contains("next line <cr>")) {
PrintStream out = new PrintStream(this.sshOut);
out.print(" ");
out.flush();
} else {
Match2 = Identifier2.matcher(lines[lines.length - 1].toLowerCase());
pattFound = Match2.find();
if (pattFound) {
String Ret = response.replace(this.hop.get(this.currentHop).getPrompt(), "");
this.commandStatus = true;
return Ret;
}
}
}
}
}
/**
* Send a new instruction to the remote server.
* @param cmd The instruction to send to the remote server.
* @param timeout The time limit for the operation.
* @return The result of the operation.
*/
public String send(String cmd, int timeout) {
if (this.checkAccess()) {
PrintStream out = new PrintStream(this.sshOut);
out.println(cmd);
// Case of long command, Method Sleep to avoid Watifor Error
int milliSec = 100;
if (cmd.length() > 7) {
if (cmd.length() > 100) {
milliSec = 2000;
} else if (cmd.length() > 80) {
milliSec = 500;
} else if (cmd.length() > 30) {
milliSec = 250;
}
try {
Thread.sleep(milliSec);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
if (this.hop.get(this.currentHop).getPrompt() != null) {
String Ret = this.waitFor(this.hop.get(this.currentHop).getPrompt(), timeout);
if (this.commandStatus == false) {
//stop the current command which timeout expired or been skipped.
this.stopCommand(this.hop.get(this.currentHop).getPrompt());
}
return Ret;
} else {
return null;
}
} else {
return "";
}
}
/**
* Send a new instruction to the remote server.
* @param cmd The instruction to send to the remote server.
* @param timeout The time limit for the operation.
* @param Prompt The correct prompt
* @return The result of the operation.
*/
public String send(String cmd, int time, String Prompt) {
if (this.checkAccess()) {
PrintStream out = new PrintStream(this.sshOut);
out.println(cmd);
// Case of long command, Method Sleep to avoid Watifor Error
if (cmd.length() > 7) {
int milliSec = 100;
if (cmd.length() > 100) {
milliSec = 2000;
} else if (cmd.length() > 80) {
milliSec = 500;
} else if (cmd.length() > 30) {
milliSec = 250;
}
try {
Thread.sleep(milliSec);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
if (Prompt != null) {
String result = this.waitFor(Prompt, time);
if (this.commandStatus == false) {
//stop the current command which timeout expired or been skipped
this.stopCommand(Prompt);
}
return result;
} else {
//if prompt == null, launch the execution of periodic command with runtime attribut.
String result = "";
result = this.wait(time);
//periodic command has to be stopped after the runtime period.
this.stopCommand(this.hop.get(this.currentHop).getPrompt());
return result;
}
} else {
return null;
}
}
/**
* This class function stop the current command by sending a CTRL+C
* and taking off the generated prompt (in order to execute the following command)
*
* @param prompt The expected prompt
* @return The flow text extracted by waitFor()
*/
public void stopCommand(String prompt) {
this.write(0x03); // = send(CTRL+C)
this.write(0x0D); // = send (ENTER)
//Wait 200 milliseconds so that the remote server replies to those actions.
try {
Thread.sleep(200);
} catch (InterruptedException ex) {
Logger.getLogger(AuditTelnetClient.class.getName()).log(Level.SEVERE, null, ex);
}
//read the stream in order to replace the flow timekeeper at the beginning of the next command.
InputStream sshInput = this.sess.getStdout();
StringBuffer in = new StringBuffer();
try {
while (sshInput.available() != 0) {
in.append((char) sshInput.read());
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
/**
* Check if the ConnecInfo with the remote server works.
* @return The status of the ConnecInfo.
*/
public boolean checkAccess() {
return this.isConnected;
}
/**
* Update all controllers that observe auditModel.
*/
private void change() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
auditModel.change();
}
});
} catch (InterruptedException ex) {
Logger.getLogger(AuditTelnetClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvocationTargetException ex) {
Logger.getLogger(AuditTelnetClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
/*----------------------------------------------------------------
* Getter and Setter
------------------------------------------------------------------*/
/**
* Getter of the property <tt>hope</tt>
* @return Returns the hope.
*/
public ArrayList<ConnectInfo> getHop() {
return hop;
}
/**
* Setter of the property <tt>hope</tt>
* @param hop the hope to set.
*/
public void setHop(ArrayList<ConnectInfo> hop) {
this.hop = hop;
}
/**
* Set the attribut nextCommand
* @param b : boolean
*/
public void setNextCommand(boolean b) {
this.nextCommand = b;
}
/**
* Getter of the property <tt>failed</tt>
* @return failed : String indicating if the connection failed or not.
*/
public String getFailed() {
return this.failed;
}
/**
* Getter of the property <tt>operationLogfile</tt>
* @return operationLogfile : the operation log object.
*/
public SnecFile getLoadingLog() {
return this.loadingLog;
}
public String getBuffer() {
return this.buffer;
}
public String getTimeToDisplay() {
return this.timeToDisplay;
}
public String getType() {
return this.type;
}
public boolean getCommandStatus() {
return this.commandStatus;
}
public void setBuffer(String buffer) {
this.buffer = buffer;
}
public void write(String value) {
throw new UnsupportedOperationException("Not supported yet.");
}
} |
Partager