Revision: 158
Author:   janne.t.harkonen
Date:     Fri Aug 24 04:22:36 2012
Log:      move login functionality fom Library to Client
http://code.google.com/p/robotframework-sshlibrary/source/detail?r=158

Modified:
 /trunk/src/SSHLibrary/__init__.py
 /trunk/src/SSHLibrary/core.py
 /trunk/src/SSHLibrary/javaclient.py
 /trunk/src/SSHLibrary/pythonclient.py

=======================================
--- /trunk/src/SSHLibrary/__init__.py   Fri Aug 24 04:22:04 2012
+++ /trunk/src/SSHLibrary/__init__.py   Fri Aug 24 04:22:36 2012
@@ -12,16 +12,14 @@
 #  See the License for the specific language governing permissions and
 #  limitations under the License.

-import time
 import os
 import glob
-import re
 import posixpath

 from robot import utils

 from connectioncache import ConnectionCache
-from core import AuthenticationException, ClientConfig, SSHClientException
+from core import ClientConfig, SSHClientException
 from config import (Configuration, StringEntry, NewlineEntry, TimeEntry,
         LogLevelEntry)
 from deprecated import DeprecatedSSHLibraryKeywords
@@ -230,11 +228,7 @@
         Example:
         | Login | john | secret |
         """
-        self._log_login(username)
-        self.ssh_client.login(username, password)
-        self.ssh_client.open_shell()
- return self.read_until_prompt() if self.ssh_client.config.prompt else \
-                    self.read()
+        return self._login(self.ssh_client.login, username, password)

     def login_with_public_key(self, username, keyfile, password):
         """Logs into SSH server with using key-based authentication.
@@ -245,28 +239,17 @@

Reads and returns available output. If prompt is set, everything until
         the prompt is returned.
-
         """
-        self._verify_key_file(keyfile)
-        self._log_login(username)
-        try:
- self.ssh_client.login_with_public_key(username, keyfile, password)
-        except AuthenticationException:
-            raise RuntimeError('Login with public key failed')
- return self.read_until_prompt() if self.ssh_client.config.prompt else \
-                    self.read()
+        return self._login(self.ssh_client.login_with_public_key, username,
+                           keyfile, password)

-    def _log_login(self, username):
+    def _login(self, login_method, username, *args):
         self._info("Logging into '%s:%s' as '%s'."
- % (self.ssh_client.host, self.ssh_client.port, username))
-
-    def _verify_key_file(self, keyfile):
-        if not os.path.exists(keyfile):
- raise RuntimeError("Given key file '%s' does not exist" % keyfile) + % (self.ssh_client.host, self.ssh_client.port, username))
         try:
-            open(keyfile).close()
-        except IOError:
-            raise RuntimeError("Could not read key file '%s'" % keyfile)
+            return login_method(username, *args)
+        except SSHClientException, e:
+            raise RuntimeError(e)

     def execute_command(self, command, return_stdout=True,
                         return_stderr=False, return_rc=False):
@@ -411,8 +394,6 @@
         | Read Until Regexp | (#|$) |
         | Read Until Regexp | some regexp  | DEBUG |
         """
-        if isinstance(regexp, basestring):
-            regexp = re.compile(regexp)
         reader = lambda: self.ssh_client.read_until_regexp(regexp)
         return self._read_and_log(reader, loglevel)

=======================================
--- /trunk/src/SSHLibrary/core.py       Fri Aug 24 04:22:04 2012
+++ /trunk/src/SSHLibrary/core.py       Fri Aug 24 04:22:36 2012
@@ -12,6 +12,8 @@
 #  See the License for the specific language governing permissions and
 #  limitations under the License.

+import os
+import re
 import time

 from config import Configuration, StringEntry, TimeEntry, IntegerEntry
@@ -33,10 +35,6 @@
                 height=IntegerEntry(height or 24))


-class AuthenticationException(RuntimeError):
-    pass
-
-
 class SSHClientException(RuntimeError):
     pass

@@ -74,6 +72,51 @@
         self.client = self._create_client()
         self._commands = []

+    def login(self, username, password):
+        """Login using given credentials.
+
+        :param str username: username to log in with
+        :param str password: password for `username`
+ :returns: If prompt is defined, read and return output until prompt.
+            Otherwise all output is read and returned.
+        """
+        try:
+            self._login(username, password)
+        except SSHClientException:
+            msg = 'Authentication failed for user: %s' % username
+            raise SSHClientException(msg)
+        return self._finalize_login()
+
+    def login_with_public_key(self, username, keyfile, password):
+        """Login using given credentials.
+
+        :param str username: username to log in with
+        :param str keyfile: path to a valid OpenSSH keyfile
+        :param str password: password used in unlocking the keyfile
+ :returns: If prompt is defined, read and return output until prompt.
+            Otherwise all output is read and returned.
+        """
+        self._verify_key_file(keyfile)
+        try:
+            self._login_with_public_key(username, keyfile, password)
+        except SSHClientException:
+            msg = 'Login with public key failed for user: %s' % username
+            raise SSHClientException(msg)
+        return self._finalize_login()
+
+    def _finalize_login(self):
+        self.open_shell()
+ return self.read_until_prompt() if self.config.prompt else self.read()
+
+    def _verify_key_file(self, keyfile):
+        if not os.path.exists(keyfile):
+            raise SSHClientException("Given key file '%s' does not exist" %
+                                     keyfile)
+        try:
+            open(keyfile).close()
+        except IOError:
+ raise SSHClientException("Could not read key file '%s'" % keyfile)
+
     def execute_command(self, command, return_stdout, return_stderr,
                         return_rc):
         self.start_command(command)
@@ -155,12 +198,14 @@
     def read_until_regexp(self, regexp):
         """Read and return from the output until regexp matches.

-        :param regexp: a compiled regexp obect used for matching
+ :param regexp: a pattern or a compiled regexp obect used for matching
         :raises SSHClientException: if match is not found in output when
             timeout expires.

         timeout is defined with :py:methc:`open_connection()`
         """
+        if isinstance(regexp, basestring):
+            regexp = re.compile(regexp)
         return self._read_until(lambda s: regexp.search(s), regexp.pattern)

     def write_until_expected(self, text, expected, timeout, interval):
=======================================
--- /trunk/src/SSHLibrary/javaclient.py Fri Aug 24 04:22:04 2012
+++ /trunk/src/SSHLibrary/javaclient.py Fri Aug 24 04:22:36 2012
@@ -23,7 +23,7 @@
     raise ImportError('Importing Trilead SSH classes failed. '
'Make sure you have the Trilead jar file in CLASSPATH.')

-from core import SSHClient, Command, AuthenticationException
+from core import SSHClient, Command, SSHClientException


 class JavaSSHClient(SSHClient):
@@ -37,19 +37,19 @@
         client.connect()
         return client

-    def login(self, username, password):
+    def _login(self, username, password):
         if not self.client.authenticateWithPassword(username, password):
- raise AuthenticationException("Authentication failed for user: %s"
-                                          % username)
+            raise SSHClientException

-    def login_with_public_key(self, username, key, password):
+    def _login_with_public_key(self, username, keyfile, password):
         try:
- if not self.client.authenticateWithPublicKey(username, File(key),
-                                                         password):
-                raise AuthenticationException()
+            success = self.client.authenticateWithPublicKey(
+                            username, File(keyfile), password)
+            if not success:
+                raise SSHClientException
         except IOError:
             # IOError is raised also when key file is invalid
-            raise AuthenticationException()
+            raise SSHClientException

     def close(self):
         self.client.close()
=======================================
--- /trunk/src/SSHLibrary/pythonclient.py       Fri Aug 24 04:22:04 2012
+++ /trunk/src/SSHLibrary/pythonclient.py       Fri Aug 24 04:22:36 2012
@@ -22,7 +22,7 @@
             'Ensure that paramiko and pycrypto modules are installed.'
             )

-from core import SSHClient, Command, AuthenticationException
+from core import SSHClient, Command, SSHClientException


 # There doesn't seem to be a simpler way to increase banner timeout
@@ -48,15 +48,15 @@
         client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
         return client

-    def login(self, username, password):
+    def _login(self, username, password):
         self.client.connect(self.host, self.port, username, password)

-    def login_with_public_key(self, username, keyfile, password):
+    def _login_with_public_key(self, username, keyfile, password):
         try:
             self.client.connect(self.host, self.port, username, password,
                                 key_filename=keyfile)
         except paramiko.AuthenticationException:
-            raise AuthenticationException()
+            raise SSHClientException

     def close(self):
         self.client.close()

Reply via email to