From 4906d0c1aaddec2435ec8ef28aee16c8288d251a Mon Sep 17 00:00:00 2001 From: Angel Hermon Date: Wed, 4 May 2016 17:34:19 +0300 Subject: [PATCH 1/2] Add port attribute to SSH and use it connecting --- .../com/aqua/sysobj/conn/CliConnectionImpl.java | 8 ++++---- .../src/main/java/systemobject/terminal/SSH.java | 15 +++++++++++++-- .../java/systemobject/terminal/SSHWithRSA.java | 7 +++++-- .../main/java/systemobject/terminal/Terminal.java | 1 + 4 files changed, 23 insertions(+), 8 deletions(-) diff --git a/jsystem-core-system-objects/cli-so/src/main/java/com/aqua/sysobj/conn/CliConnectionImpl.java b/jsystem-core-system-objects/cli-so/src/main/java/com/aqua/sysobj/conn/CliConnectionImpl.java index 5e556185..ebc6d274 100644 --- a/jsystem-core-system-objects/cli-so/src/main/java/com/aqua/sysobj/conn/CliConnectionImpl.java +++ b/jsystem-core-system-objects/cli-so/src/main/java/com/aqua/sysobj/conn/CliConnectionImpl.java @@ -265,13 +265,13 @@ private void internalConnect() throws Exception { if (params.length < 5) { throw new Exception("Unable to extract parameters from host: " + host); } - terminal = new RS232(params[0], Integer.parseInt(params[1]), Integer.parseInt(params[2]), Integer.parseInt(params[3]), Integer - .parseInt(params[4])); + terminal = new RS232(params[0], Integer.parseInt(params[1]), Integer.parseInt(params[2]), Integer.parseInt(params[3]), Integer .parseInt(params[4])); } else if (protocol.toLowerCase().equals(EnumConnectionType.SSH.value())) { terminal = new SSH(host, user, password); - } else if (protocol.toLowerCase().equals( - EnumConnectionType.SSH_RSA.value())) { + ((SSH)terminal).setPort(port); + } else if (protocol.toLowerCase().equals(EnumConnectionType.SSH_RSA.value())) { terminal = new SSHWithRSA(host, user, password, privateKey); + ((SSH)terminal).setPort(port); prompts.add(new Prompt("$", false, true)); prompts.add(new Prompt("]$", false, true)); diff --git a/jsystem-core-system-objects/cli-so/src/main/java/systemobject/terminal/SSH.java b/jsystem-core-system-objects/cli-so/src/main/java/systemobject/terminal/SSH.java index 69d4cb38..a217d391 100644 --- a/jsystem-core-system-objects/cli-so/src/main/java/systemobject/terminal/SSH.java +++ b/jsystem-core-system-objects/cli-so/src/main/java/systemobject/terminal/SSH.java @@ -35,6 +35,8 @@ public class SSH extends Terminal { protected int destinationPort = -1; protected boolean xtermTerminal = true; + + protected int port = 22; public SSH(String hostnameP, String usernameP, String passwordP) { this(hostnameP, usernameP, passwordP, -1, -1, true); @@ -55,11 +57,11 @@ public SSH(String hostnameP, String usernameP, String passwordP, int sourceTunne } @Override - public void connect() throws IOException { + public void connect(int port) throws IOException { boolean isAuthenticated = false; /* Create a connection instance */ - conn = new Connection(hostname); + conn = new Connection(hostname, port); /* Now connect */ @@ -217,6 +219,15 @@ protected void setDestinationPort(int destinationPort) { this.destinationPort = destinationPort; } + public void setPort(int port) { + this.port = port; + + } + + public int getPort() { + return port; + } + diff --git a/jsystem-core-system-objects/cli-so/src/main/java/systemobject/terminal/SSHWithRSA.java b/jsystem-core-system-objects/cli-so/src/main/java/systemobject/terminal/SSHWithRSA.java index 9c61eea9..f529880f 100644 --- a/jsystem-core-system-objects/cli-so/src/main/java/systemobject/terminal/SSHWithRSA.java +++ b/jsystem-core-system-objects/cli-so/src/main/java/systemobject/terminal/SSHWithRSA.java @@ -22,13 +22,16 @@ public SSHWithRSA(String hostnameP, String usernameP, String passwordP, privateKeyFile = privateKey; } - @Override public void connect() throws IOException { + connect(port); + } + @Override + public void connect(int port) throws IOException { boolean isAuthenticated = false; /* Create a connection instance */ System.out.println("Connet to Host with SSH and RSA private key"); - conn = new Connection(hostname); + conn = new Connection(hostname, port); /* Now connect */ diff --git a/jsystem-core-system-objects/cli-so/src/main/java/systemobject/terminal/Terminal.java b/jsystem-core-system-objects/cli-so/src/main/java/systemobject/terminal/Terminal.java index 58d94cee..5fcd699e 100644 --- a/jsystem-core-system-objects/cli-so/src/main/java/systemobject/terminal/Terminal.java +++ b/jsystem-core-system-objects/cli-so/src/main/java/systemobject/terminal/Terminal.java @@ -24,6 +24,7 @@ public abstract class Terminal { ArrayList prompts = new ArrayList(); public abstract void connect() throws IOException; + public abstract void connect(int port) throws IOException; public abstract void disconnect() throws IOException; public abstract boolean isConnected(); public abstract String getConnectionName(); From d759d4aa4ed9554ad7cfb21434c4bc547573a4f1 Mon Sep 17 00:00:00 2001 From: Angel Hermon Date: Thu, 5 May 2016 11:14:01 +0300 Subject: [PATCH 2/2] fix compilation issue --- .../main/java/systemobject/terminal/SSH.java | 468 ++++---- .../systemobject/terminal/SSHWithRSA.java | 244 ++-- .../java/systemobject/terminal/Terminal.java | 1011 ++++++++--------- 3 files changed, 859 insertions(+), 864 deletions(-) diff --git a/jsystem-core-system-objects/cli-so/src/main/java/systemobject/terminal/SSH.java b/jsystem-core-system-objects/cli-so/src/main/java/systemobject/terminal/SSH.java index a217d391..84c6b717 100644 --- a/jsystem-core-system-objects/cli-so/src/main/java/systemobject/terminal/SSH.java +++ b/jsystem-core-system-objects/cli-so/src/main/java/systemobject/terminal/SSH.java @@ -1,234 +1,234 @@ -/* - * Copyright 2005-2010 Ignis Software Tools Ltd. All rights reserved. - */ -package systemobject.terminal; - -import java.io.File; -import java.io.IOException; -import java.util.Arrays; - -import ch.ethz.ssh2.Connection; -import ch.ethz.ssh2.InteractiveCallback; -import ch.ethz.ssh2.LocalPortForwarder; -import ch.ethz.ssh2.Session; - -/** - * A terminal used for SSH Connection - */ -public class SSH extends Terminal { - - protected String hostname; - - protected String username; - - protected String password; - - protected Connection conn = null; - - protected Session sess = null; - - //ssh port forwarding - protected LocalPortForwarder lpf = null; - - protected int sourcePort = -1; - - protected int destinationPort = -1; - - protected boolean xtermTerminal = true; - - protected int port = 22; - - public SSH(String hostnameP, String usernameP, String passwordP) { - this(hostnameP, usernameP, passwordP, -1, -1, true); - } - - public SSH(String hostnameP, String usernameP, String passwordP, int sourceTunnelPort, int destinationTunnelPort) { - this(hostnameP, usernameP, passwordP, sourceTunnelPort, destinationTunnelPort, true); - } - - public SSH(String hostnameP, String usernameP, String passwordP, int sourceTunnelPort, int destinationTunnelPort, boolean _xtermTerminal) { - super(); - hostname = hostnameP; - username = usernameP; - password = passwordP; - sourcePort = sourceTunnelPort; - destinationPort =destinationTunnelPort; - xtermTerminal = _xtermTerminal; - } - - @Override - public void connect(int port) throws IOException { - boolean isAuthenticated = false; - /* Create a connection instance */ - - conn = new Connection(hostname, port); - - /* Now connect */ - - conn.connect(); - - // Check what connection options are available to us - String[] authMethods = conn.getRemainingAuthMethods(username); - System.out.println("The supported auth Methods are:"); - for(String method: authMethods) { - System.out.println(method); - } - boolean privateKeyAuthentication = false; - boolean passAuthentication = false; - for (int i = 0; i < authMethods.length; i++) { - if (authMethods[i].equalsIgnoreCase("password")) { - // we can authenticate with a password - passAuthentication = true; - } - } - if(Arrays.asList(authMethods).contains("publickey")){ - // we can authenticate with a RSA private key - privateKeyAuthentication=true; - } - - /* Authenticate */ - if (passAuthentication) { - try { - isAuthenticated = conn.authenticateWithPassword(username, password); - } catch (Exception e) { - isAuthenticated = false; - } - } - if (isAuthenticated == false) { - // we're still not authenticated - try keyboard interactive - conn.authenticateWithKeyboardInteractive(username, new InteractiveLogic()); - } - - - if (sourcePort > -1 && destinationPort > -1) { - lpf = conn.createLocalPortForwarder(sourcePort, "localhost" , destinationPort); - } - - /* Create a session */ - sess = conn.openSession(); - - if (xtermTerminal) { - sess.requestPTY("xterm", 80, 24, 640, 480, null); - }else { - sess.requestPTY("dumb", 200, 50, 0, 0, null); - } - - sess.startShell(); - - in = sess.getStdout(); - out = sess.getStdin(); - } - - @Override - public void disconnect() { - if (lpf != null) { - try { - lpf.close(); - } catch (IOException e) { - } - } - if (sess != null) { - sess.close(); - } - if (conn != null) { - conn.close(); - } - } - - @Override - public boolean isConnected() { - return true; - } - - @Override - public String getConnectionName() { - return "SSH"; - } - - /** - * The logic that one has to implement if "keyboard-interactive" - * authentication shall be supported. - */ - class InteractiveLogic implements InteractiveCallback { - /* the callback may be invoked several times, depending on how many questions-sets the server sends */ - public String[] replyToChallenge(String name, String instruction, int numPrompts, String[] prompt, boolean[] echo) throws IOException { - /* Often, servers just send empty strings for "name" and "instruction" */ - - String[] result = new String[numPrompts]; - - for (int i = 0; i < numPrompts; i++) { - if (prompt[i].toLowerCase().startsWith("password:")) { - result[i] = password; - } else { - // we don't know how to handle the prompt - System.out.print("SSH client - Unknown prompt type returned (" + prompt[i] + ")\n"); - result[i] = ""; - } - } - - return result; - } - - } - - protected String getHostname() { - return hostname; - } - - protected void setHostname(String hostname) { - this.hostname = hostname; - } - - protected String getUsername() { - return username; - } - - protected void setUsername(String username) { - this.username = username; - } - - protected String getPassword() { - return password; - } - - protected void setPassword(String password) { - this.password = password; - } - - protected Connection getConn() { - return conn; - } - - protected void setConn(Connection conn) { - this.conn = conn; - } - - protected int getSourcePort() { - return sourcePort; - } - - protected void setSourcePort(int sourcePort) { - this.sourcePort = sourcePort; - } - - protected int getDestinationPort() { - return destinationPort; - } - - protected void setDestinationPort(int destinationPort) { - this.destinationPort = destinationPort; - } - - public void setPort(int port) { - this.port = port; - - } - - public int getPort() { - return port; - } - - - - -} +/* + * Copyright 2005-2010 Ignis Software Tools Ltd. All rights reserved. + */ +package systemobject.terminal; + +import java.io.File; +import java.io.IOException; +import java.util.Arrays; + +import ch.ethz.ssh2.Connection; +import ch.ethz.ssh2.InteractiveCallback; +import ch.ethz.ssh2.LocalPortForwarder; +import ch.ethz.ssh2.Session; + +/** + * A terminal used for SSH Connection + */ +public class SSH extends Terminal { + + protected String hostname; + + protected String username; + + protected String password; + + protected Connection conn = null; + + protected Session sess = null; + + //ssh port forwarding + protected LocalPortForwarder lpf = null; + + protected int sourcePort = -1; + + protected int destinationPort = -1; + + protected boolean xtermTerminal = true; + + protected int port = 22; + + public SSH(String hostnameP, String usernameP, String passwordP) { + this(hostnameP, usernameP, passwordP, -1, -1, true); + } + + public SSH(String hostnameP, String usernameP, String passwordP, int sourceTunnelPort, int destinationTunnelPort) { + this(hostnameP, usernameP, passwordP, sourceTunnelPort, destinationTunnelPort, true); + } + + public SSH(String hostnameP, String usernameP, String passwordP, int sourceTunnelPort, int destinationTunnelPort, boolean _xtermTerminal) { + super(); + hostname = hostnameP; + username = usernameP; + password = passwordP; + sourcePort = sourceTunnelPort; + destinationPort =destinationTunnelPort; + xtermTerminal = _xtermTerminal; + } + + @Override + public void connect() throws IOException { + boolean isAuthenticated = false; + /* Create a connection instance */ + + conn = new Connection(hostname, port); + + /* Now connect */ + + conn.connect(); + + // Check what connection options are available to us + String[] authMethods = conn.getRemainingAuthMethods(username); + System.out.println("The supported auth Methods are:"); + for(String method: authMethods) { + System.out.println(method); + } + boolean privateKeyAuthentication = false; + boolean passAuthentication = false; + for (int i = 0; i < authMethods.length; i++) { + if (authMethods[i].equalsIgnoreCase("password")) { + // we can authenticate with a password + passAuthentication = true; + } + } + if(Arrays.asList(authMethods).contains("publickey")){ + // we can authenticate with a RSA private key + privateKeyAuthentication=true; + } + + /* Authenticate */ + if (passAuthentication) { + try { + isAuthenticated = conn.authenticateWithPassword(username, password); + } catch (Exception e) { + isAuthenticated = false; + } + } + if (isAuthenticated == false) { + // we're still not authenticated - try keyboard interactive + conn.authenticateWithKeyboardInteractive(username, new InteractiveLogic()); + } + + + if (sourcePort > -1 && destinationPort > -1) { + lpf = conn.createLocalPortForwarder(sourcePort, "localhost" , destinationPort); + } + + /* Create a session */ + sess = conn.openSession(); + + if (xtermTerminal) { + sess.requestPTY("xterm", 80, 24, 640, 480, null); + }else { + sess.requestPTY("dumb", 200, 50, 0, 0, null); + } + + sess.startShell(); + + in = sess.getStdout(); + out = sess.getStdin(); + } + + @Override + public void disconnect() { + if (lpf != null) { + try { + lpf.close(); + } catch (IOException e) { + } + } + if (sess != null) { + sess.close(); + } + if (conn != null) { + conn.close(); + } + } + + @Override + public boolean isConnected() { + return true; + } + + @Override + public String getConnectionName() { + return "SSH"; + } + + /** + * The logic that one has to implement if "keyboard-interactive" + * authentication shall be supported. + */ + class InteractiveLogic implements InteractiveCallback { + /* the callback may be invoked several times, depending on how many questions-sets the server sends */ + public String[] replyToChallenge(String name, String instruction, int numPrompts, String[] prompt, boolean[] echo) throws IOException { + /* Often, servers just send empty strings for "name" and "instruction" */ + + String[] result = new String[numPrompts]; + + for (int i = 0; i < numPrompts; i++) { + if (prompt[i].toLowerCase().startsWith("password:")) { + result[i] = password; + } else { + // we don't know how to handle the prompt + System.out.print("SSH client - Unknown prompt type returned (" + prompt[i] + ")\n"); + result[i] = ""; + } + } + + return result; + } + + } + + protected String getHostname() { + return hostname; + } + + protected void setHostname(String hostname) { + this.hostname = hostname; + } + + protected String getUsername() { + return username; + } + + protected void setUsername(String username) { + this.username = username; + } + + protected String getPassword() { + return password; + } + + protected void setPassword(String password) { + this.password = password; + } + + protected Connection getConn() { + return conn; + } + + protected void setConn(Connection conn) { + this.conn = conn; + } + + protected int getSourcePort() { + return sourcePort; + } + + protected void setSourcePort(int sourcePort) { + this.sourcePort = sourcePort; + } + + protected int getDestinationPort() { + return destinationPort; + } + + protected void setDestinationPort(int destinationPort) { + this.destinationPort = destinationPort; + } + + public void setPort(int port) { + this.port = port; + + } + + public int getPort() { + return port; + } + + + + +} diff --git a/jsystem-core-system-objects/cli-so/src/main/java/systemobject/terminal/SSHWithRSA.java b/jsystem-core-system-objects/cli-so/src/main/java/systemobject/terminal/SSHWithRSA.java index f529880f..d1f00361 100644 --- a/jsystem-core-system-objects/cli-so/src/main/java/systemobject/terminal/SSHWithRSA.java +++ b/jsystem-core-system-objects/cli-so/src/main/java/systemobject/terminal/SSHWithRSA.java @@ -1,124 +1,120 @@ -/* - * Copyright 2005-2010 Ignis Software Tools Ltd. All rights reserved. - */ -package systemobject.terminal; - -import java.io.File; -import java.io.IOException; -import java.util.Arrays; - -import ch.ethz.ssh2.Connection; - -/** - * A terminal used for SSH Connection - */ -public class SSHWithRSA extends SSH { - - private File privateKeyFile; - - public SSHWithRSA(String hostnameP, String usernameP, String passwordP, - File privateKey) { - super(hostnameP, usernameP, passwordP); - privateKeyFile = privateKey; - - } - @Override - public void connect() throws IOException { - connect(port); - } - @Override - public void connect(int port) throws IOException { - boolean isAuthenticated = false; - /* Create a connection instance */ - System.out.println("Connet to Host with SSH and RSA private key"); - conn = new Connection(hostname, port); - - /* Now connect */ - - conn.connect(); - - // Check what connection options are available to us - String[] authMethods = conn.getRemainingAuthMethods(username); - System.out.println("The supported auth Methods are:"); - for (String method : authMethods) { - System.out.println(method); - } - boolean privateKeyAuthentication = false; - boolean passAuthentication = false; - for (int i = 0; i < authMethods.length; i++) { - if (authMethods[i].equalsIgnoreCase("password")) { - // we can authenticate with a password - passAuthentication = true; - } - } - if (Arrays.asList(authMethods).contains("publickey")) { - // we can authenticate with a RSA public/private key - privateKeyAuthentication = true; - } - - /* Authenticate */ - if (passAuthentication) { - super.connect(); - } else if (privateKeyAuthentication) { - try { - if (privateKeyFile != null && privateKeyFile.isFile()) { - System.out.println(); - isAuthenticated = conn.authenticateWithPublicKey(username, - privateKeyFile, ""); - } else { - System.out - .println("Auth Error - The privateKeyFile should be init from the SUT with a valid path to ppk/pem RSA private key"); - } - } catch (Exception e) { - System.out.println(e.getMessage()); - isAuthenticated = false; - } - } - if (isAuthenticated == false) { - // we're still not authenticated - try keyboard interactive - conn.authenticateWithKeyboardInteractive(username,new InteractiveLogic()); - } - - if (sourcePort > -1 && destinationPort > -1) { - lpf = conn.createLocalPortForwarder(sourcePort, "localhost",destinationPort); - } - - /* Create a session */ - sess = conn.openSession(); - - if (xtermTerminal) { - sess.requestPTY("xterm", 80, 24, 640, 480, null); - } else { - sess.requestPTY("dumb", 200, 50, 0, 0, null); - } - - sess.startShell(); - - in = sess.getStdout(); - out = sess.getStdin(); - } - - @Override - public void disconnect() { - super.disconnect(); - } - - @Override - public boolean isConnected() { - return super.isConnected(); - } - - @Override - public String getConnectionName() { - return "SSH_RSA"; - } - - public File getPrivateKeyFile() { - return privateKeyFile; - } - - public void setPrivateKeyFile(File privateKeyFile) { - this.privateKeyFile = privateKeyFile; - } - -} +/* + * Copyright 2005-2010 Ignis Software Tools Ltd. All rights reserved. + */ +package systemobject.terminal; + +import java.io.File; +import java.io.IOException; +import java.util.Arrays; + +import ch.ethz.ssh2.Connection; + +/** + * A terminal used for SSH Connection + */ +public class SSHWithRSA extends SSH { + + private File privateKeyFile; + + public SSHWithRSA(String hostnameP, String usernameP, String passwordP, + File privateKey) { + super(hostnameP, usernameP, passwordP); + privateKeyFile = privateKey; + + } + @Override + public void connect() throws IOException { + boolean isAuthenticated = false; + /* Create a connection instance */ + System.out.println("Connet to Host with SSH and RSA private key"); + conn = new Connection(hostname, port); + + /* Now connect */ + + conn.connect(); + + // Check what connection options are available to us + String[] authMethods = conn.getRemainingAuthMethods(username); + System.out.println("The supported auth Methods are:"); + for (String method : authMethods) { + System.out.println(method); + } + boolean privateKeyAuthentication = false; + boolean passAuthentication = false; + for (int i = 0; i < authMethods.length; i++) { + if (authMethods[i].equalsIgnoreCase("password")) { + // we can authenticate with a password + passAuthentication = true; + } + } + if (Arrays.asList(authMethods).contains("publickey")) { + // we can authenticate with a RSA public/private key + privateKeyAuthentication = true; + } + + /* Authenticate */ + if (passAuthentication) { + super.connect(); + } else if (privateKeyAuthentication) { + try { + if (privateKeyFile != null && privateKeyFile.isFile()) { + System.out.println(); + isAuthenticated = conn.authenticateWithPublicKey(username, + privateKeyFile, ""); + } else { + System.out + .println("Auth Error - The privateKeyFile should be init from the SUT with a valid path to ppk/pem RSA private key"); + } + } catch (Exception e) { + System.out.println(e.getMessage()); + isAuthenticated = false; + } + } + if (isAuthenticated == false) { + // we're still not authenticated - try keyboard interactive + conn.authenticateWithKeyboardInteractive(username,new InteractiveLogic()); + } + + if (sourcePort > -1 && destinationPort > -1) { + lpf = conn.createLocalPortForwarder(sourcePort, "localhost",destinationPort); + } + + /* Create a session */ + sess = conn.openSession(); + + if (xtermTerminal) { + sess.requestPTY("xterm", 80, 24, 640, 480, null); + } else { + sess.requestPTY("dumb", 200, 50, 0, 0, null); + } + + sess.startShell(); + + in = sess.getStdout(); + out = sess.getStdin(); + } + + @Override + public void disconnect() { + super.disconnect(); + } + + @Override + public boolean isConnected() { + return super.isConnected(); + } + + @Override + public String getConnectionName() { + return "SSH_RSA"; + } + + public File getPrivateKeyFile() { + return privateKeyFile; + } + + public void setPrivateKeyFile(File privateKeyFile) { + this.privateKeyFile = privateKeyFile; + } + +} diff --git a/jsystem-core-system-objects/cli-so/src/main/java/systemobject/terminal/Terminal.java b/jsystem-core-system-objects/cli-so/src/main/java/systemobject/terminal/Terminal.java index 5fcd699e..726253e5 100644 --- a/jsystem-core-system-objects/cli-so/src/main/java/systemobject/terminal/Terminal.java +++ b/jsystem-core-system-objects/cli-so/src/main/java/systemobject/terminal/Terminal.java @@ -1,506 +1,505 @@ -/* - * Copyright 2005-2010 Ignis Software Tools Ltd. All rights reserved. - */ -package systemobject.terminal; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintStream; -import java.util.ArrayList; -import java.util.logging.Logger; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public abstract class Terminal { - - Logger log = Logger.getLogger(Terminal.class.getName()); - protected static final int IN_BUFFER_SIZE = 65536; - private StringBuffer result = new StringBuffer(); - protected OutputStream out = null; - protected InputStream in = null; - protected int bufChar = 10; - protected long scrollEndTimeout = 200; - ArrayList prompts = new ArrayList(); - - public abstract void connect() throws IOException; - public abstract void connect(int port) throws IOException; - public abstract void disconnect() throws IOException; - public abstract boolean isConnected(); - public abstract String getConnectionName(); - - private boolean delayedTyping = false; - private boolean asciiFilter = true; - private PrintStream printStream = System.out; - private long keyTypingDelay = 20; - private boolean ignoreBackSpace = false; - private String charSet = "ASCII"; - - /** - * create a filter input stream:
- * 1) add the current input stream to the given stream.
- * 2) set the new input stream to the given one.
- * - * @param input the filter stream - */ - public void addFilter(InOutInputStream input) { - input.setInputStream(in); - in = input; - } - - /** - * send a given string to the terminal (no prompt waiting) - * - * @param command the command to send - * @param delayedTyping if True will sleep keyTypingDelay ms between each typed byte entered to the terminal - * @throws IOException - * @throws InterruptedException - */ - public synchronized void sendString(String command, boolean delayedTyping) throws IOException, InterruptedException{ - - byte[] buf = command.getBytes(charSet); - - // Do not override if delayed typing was set to TRUE from elsewhere - if (this.delayedTyping != true) { - setDelayedTyping(delayedTyping); - } - - if (isDelayedTyping()) { - for (int i = 0; i < buf.length; i++) { - out.write(buf[i]); - out.flush(); - Thread.sleep(keyTypingDelay); - } - } else { - out.write(buf); - out.flush(); - } - } - - /** - * get the input buffer data - * @return a String of all data in the input buffer - * @throws Exception - */ - public String readInputBuffer() throws Exception { - int avail = in.available(); - if (avail <= 0 ) { - return ""; - } - byte[] bytes = new byte[avail]; - in.read(bytes); - return new String(bytes, charSet); - } - - /** - * add a remark to the result buffer - * - * @param remark the String to add - */ - public synchronized void addRemark(String remark) { - result.append(remark); - } - - /** - * checks if there is more input in the buffer - * - * @return True if there isn't any new input after ${scrollEndTimeout} ms - * @throws Exception - */ - public synchronized boolean isScrallEnd() throws Exception{ - if (scrollEndTimeout == 0) { // if set to 0 always return true. - return true; - } - int avil0 = in.available(); - Thread.sleep(scrollEndTimeout); - int avil1 = in.available(); - if (avil1 > bufChar) { - return false; - } - if (avil0 == avil1) { // no change after 1/2 time and avail under bufChar - return true; - } - Thread.sleep(scrollEndTimeout); - if (in.available() < bufChar) { - return true; - } - return false; - } - - /** - * wait for ALL Strings in the given Array to be found, in the given time - * - * @param prompts the Strings to check - * @param timeout the time (in ms) before throwing a timeout exception - * @throws IOException - * @throws InterruptedException - */ - public synchronized void waitForPrompt(String[] prompts, long timeout) throws IOException, InterruptedException{ - - long startTime = System.currentTimeMillis(); - StringBuffer sb = new StringBuffer(); - while (true) { - if (timeout > 0) { - if (System.currentTimeMillis() - startTime > timeout) { - result.append(sb); - throw new IOException("timeout: " + timeout); - } - } - int avail = in.available(); - if (avail > 0) { - while (avail > 0) { - int b = in.read(); - if (b < 0) { - avail = in.available(); - continue; - } - if (b == 8 && !isIgnoreBackSpace()) { - sb.append('B'); - } - if (b >= 127 || - b < 9 || - (b >= 14 && b <= 31) || - b == 11 || - b == 12) { // not ascii byte will be ignored - avail = in.available(); - continue; - } - sb.append((char)b); - if (printStream != null) { - printStream.print((char)b); - } - - String bufString = sb.toString(); - boolean allPromptsFound = true; - for (int i = 0; i < prompts.length; i++) { - if (bufString.indexOf(prompts[i]) < 0) { - allPromptsFound = false; - break; - } - } - if (allPromptsFound) { - result.append(sb); - return; - } - avail = in.available(); - if (timeout > 0) { - if (System.currentTimeMillis() - startTime > timeout) { - result.append(sb); - throw new IOException("timeout: " + timeout); - } - } - } - } else { - Thread.sleep(10); - } - } - - } - - /** - * wait for one of the terminal defined prompts to be found in the input buffer - * - * @param timeout the time on which timeout exception will be thrown - * @return the found Prompt if any was found - * @throws IOException if Timeout was reached - * @throws InterruptedException - */ - public synchronized Prompt waitForPrompt(long timeout) throws IOException, InterruptedException{ - - long startTime = System.currentTimeMillis(); - StringBuffer sb = new StringBuffer(); - if (prompts == null || prompts.size() == 0) { - return null; - } - while (true) { - if (timeout > 0) { - if (System.currentTimeMillis() - startTime > timeout) { - result.append(sb); - throw new IOException("timeout: " + timeout); - } - } - int avail = in.available(); - if (avail > 0) { - while (avail > 0) { - int b = in.read(); - if (b < 0) { - avail = in.available(); - continue; - } - if (b == 8 && !isIgnoreBackSpace()) { - sb.append('B'); - } - if (asciiFilter) { - if (b >= 127 || b < 9 || (b >= 14 && b <= 31) || b == 11 || b == 12) { // not ascii byte will be ignored - avail = in.available(); // if the last value is a non-ascii character - continue; - } - } - sb.append((char)b); - if (printStream != null) { - printStream.print((char)b); - } - int promptArraySize = prompts.size(); - boolean skipNonExact = false; - if (in.available() > 40 + bufChar) { - skipNonExact = true; - } - for (int j = 0; j < promptArraySize; j++) { - Prompt prompt = (Prompt)prompts.get(j); - if (prompt == null || prompt.getPrompt() == null) { - continue; - } - String bufString = sb.toString(); - if (prompt.isRegularExpression()) { - Pattern p = prompt.getPattern(); - Matcher m = p.matcher(bufString); - if (m.find()) { - result.append(sb); - return prompt; - } - } else { - // accelerate cases with long output - if (!prompt.dontWaitForScrollEnd() && skipNonExact) { - continue; - } - if (bufString.endsWith(prompt.getPrompt())) { - result.append(sb); - return prompt; - } - } - } - avail = in.available(); - /** - * change the timeout to be activate in a state were there is endless amount of output - * from the cli. - */ - if (timeout > 0) { - if (System.currentTimeMillis() - startTime > timeout) { - result.append(sb); - throw new IOException("timeout: " + timeout); - } - } - } - } else { - Thread.sleep(10); - } - } - } - - /** - * wait for one of the terminal Prompts for 20 seconds - * - * @return the found Prompt if any was found - * @throws IOException if no prompt was found after 20 seconds - * @throws InterruptedException - */ - public synchronized Prompt waitFor() throws IOException, InterruptedException{ - return waitForPrompt(20000); - } - - /** - * get all data gathered by the input buffer - * - * @return a String of all input data gathered by the terminal - */ - public synchronized String getResult() { - String toRetun = result.toString(); - result = new StringBuffer(); - return toRetun; - } - - /** - * close input and output streams - * - * @throws IOException - */ - public void closeStreams() throws IOException{ - if (in != null) { - in.close(); - } - if (out != null) { - out.close(); - } - } - - /** - * add a given Prompt to the Terminal Prompts array - * - * @param promptString the prompt String to add - * @param isRegExp if True then Prompt will be marked as a regular expression - */ - public void addPrompt(String promptString, boolean isRegExp) { - Prompt prompt = new Prompt(promptString,isRegExp); - addPrompt(prompt); - } - - /** - * add a given Prompt to the Terminal Prompts array - * - * @param prompt the prompt to add - */ - public void addPrompt(Prompt prompt) { - prompts.remove(prompt); - prompts.add(prompt); - } - - /** - * locate the matching Terminal Prompt object by the given Prompt String - * @param prompt the Prompt String - * @return the Prompt object from the Terminal Prompts list or null if none was found - */ - public Prompt getPrompt(String prompt) { - for (int i = 0; i < prompts.size(); i++) { - Prompt p = (Prompt)prompts.get(i); - if (p.getPrompt().equals(prompt)) { - return p; - } - } - return null; - } - - /** - * clear all Terminal Prompts - */ - public void removePrompts() { - prompts = new ArrayList(); - } - - /** - * get a clone of the Terminal Prompts list - * @return - */ - @SuppressWarnings("unchecked") - public ArrayList getPrompts() { - return (ArrayList)prompts.clone(); - } - - /** - * set the Terminal Prompts list - * - * @param prompts the Prompts to set - */ - public void setPrompts(ArrayList prompts) { - this.prompts = prompts; - } - public int getBufChar() { - return bufChar; - } - public void setBufChar(int bufChar) { - this.bufChar = bufChar; - } - - /** - * the time (in ms) to wait for a terminal input to be received before declaring scroll end (no more input) - * - * @return - */ - public long getScrollEndTimeout() { - return scrollEndTimeout; - } - - /** - * the time (in ms) to wait for a terminal input to be received before declaring scroll end (no more input) - * - * @param scrollEndTimeout - */ - public void setScrollEndTimeout(long scrollEndTimeout) { - this.scrollEndTimeout = scrollEndTimeout; - } - - /** - * signals if input String should be typed char by char with 20ms delay or all at once - * @return - */ - public boolean isDelayedTyping() { - return delayedTyping; - } - - /** - * if set to True then input String (command) will be typed char by char with 20ms delay
- * if set to False all String will be send at once - * default is false - * - * @param delayedTyping - */ - public void setDelayedTyping(boolean delayedTyping) { - this.delayedTyping = delayedTyping; - } - - /** - * signals if ascii chars should be ignored when reading from the buffer - * - * @return - */ - public boolean isAsciiFilter() { - return asciiFilter; - } - - /** - * if set to True then non ascii chars will be ignored - * - * @param asciiFilter - */ - public void setAsciiFilter(boolean asciiFilter) { - this.asciiFilter = asciiFilter; - } - - /** - * Sets the print stream to which the stream of the connection - * will be dumped to. - * Set the print stream to System.out to dump terminal stream to the console, - * Set print stream to null to turn off stream dump. - */ - public void setPrintStream(PrintStream printStream) { - this.printStream = printStream; - } - - /** - * the time (in ms) to sleep between each typed byte entered to the terminal - * - * @return - */ - public long getKeyTypingDelay() { - return keyTypingDelay; - } - - /** - * the time (in ms) to sleep between each typed byte entered to the terminal - * - * @param keyTypingDelay - */ - public void setKeyTypingDelay(long keyTypingDelay) { - this.keyTypingDelay = keyTypingDelay; - } - - /** - * Whether to ignore backspace characters or not - * - * @param ignoreBackSpace - */ - public boolean isIgnoreBackSpace() { - return ignoreBackSpace; - } - - /** - * Whether to ignore backspace characters or not - * - * @param ignoreBackSpace - */ - public void setIgnoreBackSpace(boolean ignoreBackSpace) { - this.ignoreBackSpace = ignoreBackSpace; - } - - public void setCharSet(String charSet) { - this.charSet = charSet; - } - - public String getCharSet() { - return charSet; - } - - public InputStream getIn() { - return in; - } - -} +/* + * Copyright 2005-2010 Ignis Software Tools Ltd. All rights reserved. + */ +package systemobject.terminal; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintStream; +import java.util.ArrayList; +import java.util.logging.Logger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public abstract class Terminal { + + Logger log = Logger.getLogger(Terminal.class.getName()); + protected static final int IN_BUFFER_SIZE = 65536; + private StringBuffer result = new StringBuffer(); + protected OutputStream out = null; + protected InputStream in = null; + protected int bufChar = 10; + protected long scrollEndTimeout = 200; + ArrayList prompts = new ArrayList(); + + public abstract void connect() throws IOException; + public abstract void disconnect() throws IOException; + public abstract boolean isConnected(); + public abstract String getConnectionName(); + + private boolean delayedTyping = false; + private boolean asciiFilter = true; + private PrintStream printStream = System.out; + private long keyTypingDelay = 20; + private boolean ignoreBackSpace = false; + private String charSet = "ASCII"; + + /** + * create a filter input stream:
+ * 1) add the current input stream to the given stream.
+ * 2) set the new input stream to the given one.
+ * + * @param input the filter stream + */ + public void addFilter(InOutInputStream input) { + input.setInputStream(in); + in = input; + } + + /** + * send a given string to the terminal (no prompt waiting) + * + * @param command the command to send + * @param delayedTyping if True will sleep keyTypingDelay ms between each typed byte entered to the terminal + * @throws IOException + * @throws InterruptedException + */ + public synchronized void sendString(String command, boolean delayedTyping) throws IOException, InterruptedException{ + + byte[] buf = command.getBytes(charSet); + + // Do not override if delayed typing was set to TRUE from elsewhere + if (this.delayedTyping != true) { + setDelayedTyping(delayedTyping); + } + + if (isDelayedTyping()) { + for (int i = 0; i < buf.length; i++) { + out.write(buf[i]); + out.flush(); + Thread.sleep(keyTypingDelay); + } + } else { + out.write(buf); + out.flush(); + } + } + + /** + * get the input buffer data + * @return a String of all data in the input buffer + * @throws Exception + */ + public String readInputBuffer() throws Exception { + int avail = in.available(); + if (avail <= 0 ) { + return ""; + } + byte[] bytes = new byte[avail]; + in.read(bytes); + return new String(bytes, charSet); + } + + /** + * add a remark to the result buffer + * + * @param remark the String to add + */ + public synchronized void addRemark(String remark) { + result.append(remark); + } + + /** + * checks if there is more input in the buffer + * + * @return True if there isn't any new input after ${scrollEndTimeout} ms + * @throws Exception + */ + public synchronized boolean isScrallEnd() throws Exception{ + if (scrollEndTimeout == 0) { // if set to 0 always return true. + return true; + } + int avil0 = in.available(); + Thread.sleep(scrollEndTimeout); + int avil1 = in.available(); + if (avil1 > bufChar) { + return false; + } + if (avil0 == avil1) { // no change after 1/2 time and avail under bufChar + return true; + } + Thread.sleep(scrollEndTimeout); + if (in.available() < bufChar) { + return true; + } + return false; + } + + /** + * wait for ALL Strings in the given Array to be found, in the given time + * + * @param prompts the Strings to check + * @param timeout the time (in ms) before throwing a timeout exception + * @throws IOException + * @throws InterruptedException + */ + public synchronized void waitForPrompt(String[] prompts, long timeout) throws IOException, InterruptedException{ + + long startTime = System.currentTimeMillis(); + StringBuffer sb = new StringBuffer(); + while (true) { + if (timeout > 0) { + if (System.currentTimeMillis() - startTime > timeout) { + result.append(sb); + throw new IOException("timeout: " + timeout); + } + } + int avail = in.available(); + if (avail > 0) { + while (avail > 0) { + int b = in.read(); + if (b < 0) { + avail = in.available(); + continue; + } + if (b == 8 && !isIgnoreBackSpace()) { + sb.append('B'); + } + if (b >= 127 || + b < 9 || + (b >= 14 && b <= 31) || + b == 11 || + b == 12) { // not ascii byte will be ignored + avail = in.available(); + continue; + } + sb.append((char)b); + if (printStream != null) { + printStream.print((char)b); + } + + String bufString = sb.toString(); + boolean allPromptsFound = true; + for (int i = 0; i < prompts.length; i++) { + if (bufString.indexOf(prompts[i]) < 0) { + allPromptsFound = false; + break; + } + } + if (allPromptsFound) { + result.append(sb); + return; + } + avail = in.available(); + if (timeout > 0) { + if (System.currentTimeMillis() - startTime > timeout) { + result.append(sb); + throw new IOException("timeout: " + timeout); + } + } + } + } else { + Thread.sleep(10); + } + } + + } + + /** + * wait for one of the terminal defined prompts to be found in the input buffer + * + * @param timeout the time on which timeout exception will be thrown + * @return the found Prompt if any was found + * @throws IOException if Timeout was reached + * @throws InterruptedException + */ + public synchronized Prompt waitForPrompt(long timeout) throws IOException, InterruptedException{ + + long startTime = System.currentTimeMillis(); + StringBuffer sb = new StringBuffer(); + if (prompts == null || prompts.size() == 0) { + return null; + } + while (true) { + if (timeout > 0) { + if (System.currentTimeMillis() - startTime > timeout) { + result.append(sb); + throw new IOException("timeout: " + timeout); + } + } + int avail = in.available(); + if (avail > 0) { + while (avail > 0) { + int b = in.read(); + if (b < 0) { + avail = in.available(); + continue; + } + if (b == 8 && !isIgnoreBackSpace()) { + sb.append('B'); + } + if (asciiFilter) { + if (b >= 127 || b < 9 || (b >= 14 && b <= 31) || b == 11 || b == 12) { // not ascii byte will be ignored + avail = in.available(); // if the last value is a non-ascii character + continue; + } + } + sb.append((char)b); + if (printStream != null) { + printStream.print((char)b); + } + int promptArraySize = prompts.size(); + boolean skipNonExact = false; + if (in.available() > 40 + bufChar) { + skipNonExact = true; + } + for (int j = 0; j < promptArraySize; j++) { + Prompt prompt = (Prompt)prompts.get(j); + if (prompt == null || prompt.getPrompt() == null) { + continue; + } + String bufString = sb.toString(); + if (prompt.isRegularExpression()) { + Pattern p = prompt.getPattern(); + Matcher m = p.matcher(bufString); + if (m.find()) { + result.append(sb); + return prompt; + } + } else { + // accelerate cases with long output + if (!prompt.dontWaitForScrollEnd() && skipNonExact) { + continue; + } + if (bufString.endsWith(prompt.getPrompt())) { + result.append(sb); + return prompt; + } + } + } + avail = in.available(); + /** + * change the timeout to be activate in a state were there is endless amount of output + * from the cli. + */ + if (timeout > 0) { + if (System.currentTimeMillis() - startTime > timeout) { + result.append(sb); + throw new IOException("timeout: " + timeout); + } + } + } + } else { + Thread.sleep(10); + } + } + } + + /** + * wait for one of the terminal Prompts for 20 seconds + * + * @return the found Prompt if any was found + * @throws IOException if no prompt was found after 20 seconds + * @throws InterruptedException + */ + public synchronized Prompt waitFor() throws IOException, InterruptedException{ + return waitForPrompt(20000); + } + + /** + * get all data gathered by the input buffer + * + * @return a String of all input data gathered by the terminal + */ + public synchronized String getResult() { + String toRetun = result.toString(); + result = new StringBuffer(); + return toRetun; + } + + /** + * close input and output streams + * + * @throws IOException + */ + public void closeStreams() throws IOException{ + if (in != null) { + in.close(); + } + if (out != null) { + out.close(); + } + } + + /** + * add a given Prompt to the Terminal Prompts array + * + * @param promptString the prompt String to add + * @param isRegExp if True then Prompt will be marked as a regular expression + */ + public void addPrompt(String promptString, boolean isRegExp) { + Prompt prompt = new Prompt(promptString,isRegExp); + addPrompt(prompt); + } + + /** + * add a given Prompt to the Terminal Prompts array + * + * @param prompt the prompt to add + */ + public void addPrompt(Prompt prompt) { + prompts.remove(prompt); + prompts.add(prompt); + } + + /** + * locate the matching Terminal Prompt object by the given Prompt String + * @param prompt the Prompt String + * @return the Prompt object from the Terminal Prompts list or null if none was found + */ + public Prompt getPrompt(String prompt) { + for (int i = 0; i < prompts.size(); i++) { + Prompt p = (Prompt)prompts.get(i); + if (p.getPrompt().equals(prompt)) { + return p; + } + } + return null; + } + + /** + * clear all Terminal Prompts + */ + public void removePrompts() { + prompts = new ArrayList(); + } + + /** + * get a clone of the Terminal Prompts list + * @return + */ + @SuppressWarnings("unchecked") + public ArrayList getPrompts() { + return (ArrayList)prompts.clone(); + } + + /** + * set the Terminal Prompts list + * + * @param prompts the Prompts to set + */ + public void setPrompts(ArrayList prompts) { + this.prompts = prompts; + } + public int getBufChar() { + return bufChar; + } + public void setBufChar(int bufChar) { + this.bufChar = bufChar; + } + + /** + * the time (in ms) to wait for a terminal input to be received before declaring scroll end (no more input) + * + * @return + */ + public long getScrollEndTimeout() { + return scrollEndTimeout; + } + + /** + * the time (in ms) to wait for a terminal input to be received before declaring scroll end (no more input) + * + * @param scrollEndTimeout + */ + public void setScrollEndTimeout(long scrollEndTimeout) { + this.scrollEndTimeout = scrollEndTimeout; + } + + /** + * signals if input String should be typed char by char with 20ms delay or all at once + * @return + */ + public boolean isDelayedTyping() { + return delayedTyping; + } + + /** + * if set to True then input String (command) will be typed char by char with 20ms delay
+ * if set to False all String will be send at once + * default is false + * + * @param delayedTyping + */ + public void setDelayedTyping(boolean delayedTyping) { + this.delayedTyping = delayedTyping; + } + + /** + * signals if ascii chars should be ignored when reading from the buffer + * + * @return + */ + public boolean isAsciiFilter() { + return asciiFilter; + } + + /** + * if set to True then non ascii chars will be ignored + * + * @param asciiFilter + */ + public void setAsciiFilter(boolean asciiFilter) { + this.asciiFilter = asciiFilter; + } + + /** + * Sets the print stream to which the stream of the connection + * will be dumped to. + * Set the print stream to System.out to dump terminal stream to the console, + * Set print stream to null to turn off stream dump. + */ + public void setPrintStream(PrintStream printStream) { + this.printStream = printStream; + } + + /** + * the time (in ms) to sleep between each typed byte entered to the terminal + * + * @return + */ + public long getKeyTypingDelay() { + return keyTypingDelay; + } + + /** + * the time (in ms) to sleep between each typed byte entered to the terminal + * + * @param keyTypingDelay + */ + public void setKeyTypingDelay(long keyTypingDelay) { + this.keyTypingDelay = keyTypingDelay; + } + + /** + * Whether to ignore backspace characters or not + * + * @param ignoreBackSpace + */ + public boolean isIgnoreBackSpace() { + return ignoreBackSpace; + } + + /** + * Whether to ignore backspace characters or not + * + * @param ignoreBackSpace + */ + public void setIgnoreBackSpace(boolean ignoreBackSpace) { + this.ignoreBackSpace = ignoreBackSpace; + } + + public void setCharSet(String charSet) { + this.charSet = charSet; + } + + public String getCharSet() { + return charSet; + } + + public InputStream getIn() { + return in; + } + +}