Beispiel #1
0
 def _setup_hostkey():
     hostkey = paramiko.RSAKey(filename="test_rsa.key")
     print('Read key: ' + u(hexlify(hostkey.get_fingerprint())))
     return hostkey
Beispiel #2
0
class Server(paramiko.ServerInterface):
    # 'data' is the output of base64.b64encode(key)
    # (using the "user_rsa_key" files)
    data = (b'AAAAB3NzaC1yc2EAAAABIwAAAIEAyO4it3fHlmGZWJaGrfeHOVY7RWO3P9M7hp'
            b'fAu7jJ2d7eothvfeuoRFtJwhUmZDluRdFyhFY/hFAh76PJKGAusIqIQKlkJxMC'
            b'KDqIexkgHAfID/6mqvmnSJf0b5W8v5h2pI/stOSwTQ+pxVhwJ9ctYDhRSlF0iT'
            b'UWT10hcuO4Ks8=')
    good_pub_key = paramiko.RSAKey(data=decodebytes(data))

    commands = [
        b'$SHELL -ilc "locale charmap"', b'$SHELL -ic "locale charmap"'
    ]
    encodings = ['UTF-8', 'GBK', 'UTF-8\r\n', 'GBK\r\n']

    def __init__(self, encodings=[]):
        self.shell_event = threading.Event()
        self.exec_event = threading.Event()
        self.cmd_to_enc = self.get_cmd2enc(encodings)
        self.password_verified = False
        self.key_verified = False

    def get_cmd2enc(self, encodings):
        n = len(self.commands)
        while len(encodings) < n:
            encodings.append(random.choice(self.encodings))
        return dict(zip(self.commands, encodings[0:n]))

    def check_channel_request(self, kind, chanid):
        if kind == 'session':
            return paramiko.OPEN_SUCCEEDED
        return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED

    def check_auth_password(self, username, password):
        print('Auth attempt with username: {!r} & password: {!r}'.format(
            username, password))  # noqa
        if (username in ['robey', 'bar', 'foo']) and (password == 'foo'):
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED

    def check_auth_publickey(self, username, key):
        print('Auth attempt with username: {!r} & key: {!r}'.format(
            username, u(hexlify(key.get_fingerprint()))))  # noqa
        if (username in ['robey', 'keyonly']) and (key == self.good_pub_key):
            return paramiko.AUTH_SUCCESSFUL
        if username == 'pkey2fa' and key == self.good_pub_key:
            self.key_verified = True
            return paramiko.AUTH_PARTIALLY_SUCCESSFUL
        return paramiko.AUTH_FAILED

    def check_auth_interactive(self, username, submethods):
        if username in ['pass2fa', 'pkey2fa']:
            self.username = username
            prompt = 'Verification code: ' if self.password_verified else 'Password: '******'', '', prompt)
        return paramiko.AUTH_FAILED

    def check_auth_interactive_response(self, responses):
        if self.username in ['pass2fa', 'pkey2fa']:
            if not self.password_verified:
                if responses[0] == 'password':
                    print('password verified')
                    self.password_verified = True
                    if self.username == 'pkey2fa':
                        return self.check_auth_interactive(self.username, '')
                else:
                    print('wrong password: {}'.format(responses[0]))
                    return paramiko.AUTH_FAILED
            else:
                if responses[0] == 'passcode':
                    print('totp verified')
                    return paramiko.AUTH_SUCCESSFUL
                else:
                    print('wrong totp: {}'.format(responses[0]))
                    return paramiko.AUTH_FAILED
        else:
            return paramiko.AUTH_FAILED

    def get_allowed_auths(self, username):
        if username == 'keyonly':
            return 'publickey'
        if username == 'pass2fa':
            return 'keyboard-interactive'
        if username == 'pkey2fa':
            if not self.key_verified:
                return 'publickey'
            else:
                return 'keyboard-interactive'
        return 'password,publickey'

    def check_channel_exec_request(self, channel, command):
        if command not in self.commands:
            ret = False
        else:
            ret = True
            self.encoding = self.cmd_to_enc[command]
            channel.send(self.encoding)
            channel.shutdown(1)
        self.exec_event.set()
        return ret

    def check_channel_shell_request(self, channel):
        self.shell_event.set()
        return True

    def check_channel_pty_request(self, channel, term, width, height,
                                  pixelwidth, pixelheight, modes):
        return True

    def check_channel_window_change_request(self, channel, width, height,
                                            pixelwidth, pixelheight):
        channel.send('resized')
        return True
Beispiel #3
0
 def host_key(self):
     if not os.path.isfile(self.host_key_path):
         self.gen_host_key()
     return paramiko.RSAKey(filename=self.host_key_path)
Beispiel #4
0
import socket
import paramiko
import threading
import sys

host_key = paramiko.RSAKey(filename='id_rsa')


class Server(paramiko.ServerInterface):
    def __init__(self):
        self.event = threading.Event()

    def check_channel_request(self, kind, chanid):
        if kind == 'session':
            return paramiko.OPEN_SUCCEEDED
        return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED

    def check_auth_password(self, username, password):
        if (username == 'vagrant') and (password == 'vagrant'):
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED


server = sys.argv[1]
ssh_port = int(sys.argv[2])

try:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((server, ssh_port))
    sock.listen(100)
Beispiel #5
0
import base64
from binascii import hexlify
import os
import socket
import sys
import threading
import traceback

import paramiko
from paramiko.py3compat import b, u, decodebytes

# setup logging
paramiko.util.log_to_file('demo_server.log')

host_key = paramiko.RSAKey(filename='host.key')
#host_key = paramiko.DSSKey(filename='test_dss.key')

print('Read key: ' + u(hexlify(host_key.get_fingerprint())))


class Server(paramiko.ServerInterface):
    # 'data' is the output of base64.b64encode(key)
    # (using the "user_rsa_key" files)
    data = (
        b'AAAAB3NzaC1yc2EAAAADAQABAAACAQDQzL0E/aSxNtAhx6Jsn5Q9hkTiPnFWxo+gbf9YlPTzc9BxqH/ovatWkWXRhrI+bbMVwVVGJF/wvr0PAZ2HJhrTa6EteL/eyzdO5c4s+cW4jlmfmtb826ylKKVR056S5DfSiWqAcU7qg9m2FNnC6Uaerje3lWkB/MhpP6/+6/s2ytnfYu7EGIRz1FLGO+9V+OB3ep3mwUHTFrvji9zSWs5ssOpaxAi6KLCBgKvHsuOQ00KezRJORv7xTPmFnZOk4QISqGmWLPo0KThNCfPCHS7rTMehvywHOuSOVrGDik7xWTS6i6b5KOIJIn0JTMa+RXn+qcgBsMWZRxwJcLDN2fVK7n7bLQYWhSH/4lQpEcbnMVDFI76dUpXt3YMGZ+M8wZ9Tg4xmmABmws1bF8asfUwBvKvrhGJmBSBIQBAbzOT+NM3jEmgmkYUGJofFAimI9OsPp0CO0mc9vz2gw8/b1JAfVt//ZandX4bG0GBSWFMz0QUREOwV2fnJah7MfpG7D5IiiSE33W580Osw3vF9AAh3yjCN/ZIjpkA7SifGiEhL0bCXrCq4UPuOW1/gjed4QiY/OK0EJO8ZS5nKhpis74H3evZePQPX/p/Ju0h9QEFv80MvqI/J0QWuF4jBUYEuXZFPEJdE4t71F/eY2wsI9vwxRxmSzPtYCFOnpx19gV3wVw=='
    )
    good_pub_key = paramiko.RSAKey(data=decodebytes(data))

    def __init__(self, transport):
        self.event = threading.Event()
Beispiel #6
0
#!/usr/bin/env python2.7
import socket, sys, threading
import paramiko

if sys.version_info.major == 2:
    import thread

#generate keys with 'ssh-keygen -t rsa -f server.key'
HOST_KEY = paramiko.RSAKey(filename='server.key')
SSH_PORT = 2222
LOGFILE = 'logins.txt'  #File to log the user:password combinations to
LOGFILE_LOCK = threading.Lock()


class SSHServerHandler(paramiko.ServerInterface):
    def __init__(self):
        self.event = threading.Event()

    def check_auth_password(self, username, password):
        LOGFILE_LOCK.acquire()
        try:
            logfile_handle = open(LOGFILE, "a")
            print("New login: "******":" + password)
            logfile_handle.write(username + ":" + password + "\n")
            logfile_handle.close()
        finally:
            LOGFILE_LOCK.release()
        return paramiko.AUTH_FAILED

    def get_allowed_auths(self, username):
        return 'password'
 def run(self):
     oSocketConnection, address = self.oSocket.accept()
     self.connectionID = '%s:%d-%s:%d' % (self.oSocket.getsockname() +
                                          address)
     oSocketConnection.settimeout(self.options.timeout)
     self.oOutput.LineTimestamped('%s connection' % self.connectionID)
     dListener = dListeners[self.oSocket.getsockname()[1]]
     if THP_REFERENCE in dListener:
         dListener = dListeners[dListener[THP_REFERENCE]]
     try:
         oSSLConnection = None
         oSSLContext = dListener.get(THP_SSLCONTEXT, None)
         oSSHConnection = None
         oSSHFile = None
         if oSSLContext != None:
             oSSLConnection = oSSLContext.wrap_socket(oSocketConnection,
                                                      server_side=True)
             self.connection = oSSLConnection
         elif dListener.get(THP_SSH, None) != None:
             if ModuleLoaded('paramiko'):
                 if THP_KEYFILE in dListener[THP_SSH]:
                     oRSAKey = paramiko.RSAKey(
                         filename=dListener[THP_SSH][THP_KEYFILE])
                 else:
                     oRSAKey = paramiko.RSAKey.generate(1024)
                     self.oOutput.LineTimestamped(
                         '%s SSH generated RSA key' % self.connectionID)
                 oTransport = paramiko.Transport(oSocketConnection)
                 if THP_BANNER in dListener[THP_SSH]:
                     oTransport.local_version = dListener[THP_SSH][
                         THP_BANNER]
                 oTransport.load_server_moduli()
                 oTransport.add_server_key(oRSAKey)
                 oSSHServer = cSSHServer(self.oOutput, self.connectionID)
                 try:
                     oTransport.start_server(server=oSSHServer)
                 except paramiko.SSHException:
                     self.oOutput.LineTimestamped(
                         '%s SSH negotiation failed' % self.connectionID)
                     raise
                 self.oOutput.LineTimestamped(
                     '%s SSH banner %s' %
                     (self.connectionID, oTransport.remote_version))
                 oSSHConnection = oTransport.accept(20)
                 if oSSHConnection is None:
                     self.oOutput.LineTimestamped('%s SSH no channel' %
                                                  self.connectionID)
                     raise
                 self.oOutput.LineTimestamped('%s SSH authenticated' %
                                              self.connectionID)
                 oSSHServer.oEvent.wait(10)
                 if not oSSHServer.oEvent.is_set():
                     self.oOutput.LineTimestamped('%s SSH no shell' %
                                                  self.connectionID)
                     raise
                 self.connection = oSSHConnection
                 oSSHFile = oSSHConnection.makefile('rU')
             else:
                 self.oOutput.LineTimestamped(
                     '%s can not create SSH server, Python module paramiko missing'
                     % self.connectionID)
                 self.connection = oSocketConnection
         else:
             self.connection = oSocketConnection
         if THP_BANNER in dListener:
             self.connection.send(ReplaceAliases(dListener[THP_BANNER]))
             self.oOutput.LineTimestamped('%s send banner' %
                                          self.connectionID)
         for i in range(0, dListener.get(THP_LOOP, 1)):
             if oSSHFile == None:
                 data = self.connection.recv(self.options.readbuffer)
             else:
                 data = oSSHFile.readline()
             self.oOutput.LineTimestamped('%s data %s' %
                                          (self.connectionID, repr(data)))
             for splitdata in SplitIfRequested(dListener, data):
                 if splitdata != data:
                     self.oOutput.LineTimestamped(
                         '%s splitdata %s' %
                         (self.connectionID, repr(splitdata)))
                 if THP_REPLY in dListener:
                     self.connection.send(
                         ReplaceAliases(dListener[THP_REPLY]))
                     self.oOutput.LineTimestamped('%s send reply' %
                                                  self.connectionID)
                 if THP_MATCH in dListener:
                     dKeys = {}
                     for item in dListener[THP_MATCH].items():
                         for key in item[1].keys():
                             dKeys[key] = 1 + dKeys.get(key, 0)
                     if THP_REGEX in dKeys and THP_STARTSWITH in dKeys:
                         self.oOutput.LineTimestamped(
                             'THP_MATCH cannot contain both THP_REGEX and THP_STARTSWITH!'
                         )
                     elif THP_REGEX in dKeys:
                         matches = []
                         for matchname, dMatch in dListener[
                                 THP_MATCH].items():
                             if THP_REGEX in dMatch:
                                 oMatch = re.search(dMatch[THP_REGEX],
                                                    splitdata)
                                 if oMatch != None:
                                     matches.append([
                                         len(oMatch.group()), dMatch,
                                         matchname
                                     ])
                         if self.ProcessMatches(matches, dListener):
                             break
                     elif THP_STARTSWITH in dKeys:
                         matches = []
                         for matchname, dMatch in dListener[
                                 THP_MATCH].items():
                             if THP_STARTSWITH in dMatch and splitdata.startswith(
                                     dMatch[THP_STARTSWITH]):
                                 matches.append([
                                     len(dMatch[THP_STARTSWITH]), dMatch,
                                     matchname
                                 ])
                         if self.ProcessMatches(matches, dListener):
                             break
         #a# is it necessary to close both oSSLConnection and oSocketConnection?
         if oSSLConnection != None:
             oSSLConnection.shutdown(socket.SHUT_RDWR)
             oSSLConnection.close()
         oSocketConnection.shutdown(socket.SHUT_RDWR)
         oSocketConnection.close()
         self.oOutput.LineTimestamped('%s closed' % self.connectionID)
     except socket.timeout:
         self.oOutput.LineTimestamped('%s timeout' % self.connectionID)
     except Exception as e:
         self.oOutput.LineTimestamped("%s exception '%s'" %
                                      (self.connectionID, str(e)))
Beispiel #8
0
import os
import paramiko
import socket
import sys
import threading

CWD = os.path.dirname(os.path.realpath(__file__))
HOSTKEY = paramiko.RSAKey(filename=os.path.join(CWD, 'test_rsa.key'))


class Server (paramiko.ServerInterface):
    def _init_(self):
        self.event = threading.Event()

    def check_channel_request(self, kind, chanid):
        if kind == 'session':
            return paramiko.OPEN_SUCCEEDED
        return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED

    def check_auth_password(self, username, password):
        if (username == 'flint') and (password == 'Piastra!'):
            return paramiko.AUTH_SUCCESSFUL


if __name__ == '__main__':
    server = '127.0.0.1'
    ssh_port = 2222
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind((server, ssh_port))
Beispiel #9
0
import socket
import paramiko
import threading
import sys

host_key = paramiko.RSAKey(key=1).generate(2048)


class Server(paramiko.ServerInterface):

    def __init__(self):
        
        self.event = threading.Event()

    def check_channel_request(self, kind, chanid):

        if kind == 'session':
            return paramiko.OPEN_SUCCEEDED

        return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED

    def check_auth_password(self, username, password):

        if username == 'wsrtk' and password == 'none':
            return paramiko.AUTH_SUCCESSFUL
        
        return paramiko.AUTH_FAILED


server = sys.argv[1]
ssh_port = int(sys.argv[2])
Beispiel #10
0
    def export_credemtel_fiscal_documents(self):

        invoice = self.env.ref("l10n_it_account.1").id
        credit_note = self.env.ref("l10n_it_account.2").id
        vat_company = self.env.user.company_id.vat
        adattamento_ora = timedelta(hours=2)
        now = datetime.now() + adattamento_ora
        timestamp = datetime.strftime(now, '%Y%m%d%H%M%S')

        exist_nc = False
        exist_f = False

        nome_zip_f = vat_company + '_F_' + timestamp + '.zip'
        zipf = zipfile.ZipFile(PATH + nome_zip_f, 'w')

        nome_zip_nc = vat_company + '_NC_' + timestamp + '.zip'
        zipnc = zipfile.ZipFile(PATH + nome_zip_nc, 'w')

        ftp_service = self.env['sdi.channel'].search([
            ('channel_type', '=', 'ftp'), ('active_web_server', '=', True)
        ])

        key = paramiko.RSAKey(data=base64.decodebytes(SSH_KEY))
        cnopts = pysftp.CnOpts()
        cnopts.hostkeys.add(ftp_service.url, 'ssh-rsa', key)

        with pysftp.Connection(ftp_service.url,
                               username=ftp_service.username,
                               password=ftp_service.password,
                               cnopts=cnopts) as ftp:

            docs = self.env['fatturapa.attachment.out'].search([
                '&', ('create_date', '>=', '2020-10-01 00:00:00'),
                ('exported_zip', '=', False)
            ])
            logging.info(docs)
            for doc in docs:
                if doc.out_invoice_ids[
                        0].fiscal_document_type_id.id == invoice:
                    zipf.writestr(doc.name, base64.b64decode(doc.datas))
                    doc.out_invoice_ids[0].fatturapa_state = 'sent'
                    doc.exported_zip = 1
                    exist_f = True
                if doc.out_invoice_ids[
                        0].fiscal_document_type_id.id == credit_note:
                    zipnc.writestr(doc.name, base64.b64decode(doc.datas))
                    doc.out_invoice_ids[0].fatturapa_state = 'sent'
                    doc.exported_zip = 1
                    exist_nc = True

            zipf.close()
            zipnc.close()

            if exist_f:
                ftp.put(PATH + nome_zip_f, FTP_PATH + nome_zip_f)
                logging.info("File Caricato")
            if exist_nc:
                ftp.put(PATH + nome_zip_nc, FTP_PATH + nome_zip_nc)
                logging.info("File Caricato")

            ftp.close()
Beispiel #11
0
            return paramiko.OPEN_SUCCEEDED
        else:
            return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED

    def check_auth_password(self, username, password):

        if (username == "justin") and (password == "lovesthepython"):
            return paramiko.AUTH_SUCCESSFUL
        else:
            return paramiko.AUTH_FAILED


if __name__ == "__main__":

    # Using the key from the Paramiko demo files: github.com/paramiko/paramiko/blob/master/tests/test_rsa.key
    host_key = paramiko.RSAKey(filename="./test_rsa.key")

    parser = argparse.ArgumentParser()
    parser.add_argument("host_address",
                        default="127.0.0.1",
                        help="IP address of the SSH server")
    parser.add_argument("host_port",
                        type=int,
                        default=22,
                        help="Used port of the SSH server")

    args = parser.parse_args()

    try:
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def connectRouter():
    router = paramiko.SSHClient()
    key = paramiko.RSAKey(data=base64.decodestring(R_key_string))
    router.get_host_keys().add(R_ip, 'ssh-rsa', key)
    router.connect(R_ip, username='******', password=R_pass)
    return router
ZlQfAP+VyuKn1fzaVd6fyg4ObBWbZn2U/Iyp1/6Zw2da4A+/JnkSFp4vbcmAzb7T
Hv724kGPGw/96viGK83l7h2oDGI7RG189sM4HSQKq/fkzfTLoPyZasExjAC4L5Jg
NkpBd73Ai9ZnGRSRly6w8ikvCZjEVrOoHW2L+QKBgEDDshNVtD3LGQVCIuqyHlh0
n/k0vGMGr9XXqdYFAAduAI1ceW8xlaFrvPdJMrp4rs+is4/UjoA1W9pKcz8tviw/
jIV3Lhe0jgCHLrnhjXuILu8JrQttDLGGuWaEuFF2nq+cCZL5nFnFpB7EIk8DA4m9
Iw76HvUwUAE+Yjo2yiP5AoGBAIQE0d3CgtNuZh2Sb4kHw1PjHFBQCaN9UKUTFEjn
sOl+Ku0YRt86jnRyJyJYpvvzgtv6y/57p4S4Z3gSjp98jSjNlIBow+DyjIBpb6Yl
jS3K1uK/EGJhV2cPTiAOsFx9QlJpw3UsirCMn1911Nj7QU3kAsJ6Kt5s+wpKFMsM
3WdLAoGAGBPkHq3TUXEVrQQbGDMsi1b6vBB9sW1xU6uzXVX1zWNxye+7ETazl4+8
YFtBG5fRs86uvQd1gfYZCYkBk+pCh8nsMswuhh5jIEgvnxCKF9OEQugjp/gjAYqc
U81RlNbwezBrqj89Hffq7slsEmc3RECi8TyelimOJck2KD9Kg7g=
-----END RSA PRIVATE KEY-----"""

hostname = "172.16.6.226"
port = 22
username = '******'
passwd = 'edong'
cmd = 'uptime'

priv_key = paramiko.RSAKey(file_obj=StringIO(priv_str))
paramiko.util.log_to_file('paramiko.info')
trans_mode = paramiko.Transport((hostname, port))
trans_mode.connect(username=username, password=passwd, pkey=priv_key)
ssh = paramiko.SSHClient()
ssh._transport = trans_mode
stdin, stdout, stderr = ssh.exec_command(cmd)

res = stdout.read()
print(res.decode())
trans_mode.close()
Beispiel #14
0
class Server(paramiko.ServerInterface):
    # 'data' is the output of base64.b64encode(key)
    # (using the "user_rsa_key" files)
    data = (b'AAAAB3NzaC1yc2EAAAABIwAAAIEAyO4it3fHlmGZWJaGrfeHOVY7RWO3P9M7hp'
            b'fAu7jJ2d7eothvfeuoRFtJwhUmZDluRdFyhFY/hFAh76PJKGAusIqIQKlkJxMC'
            b'KDqIexkgHAfID/6mqvmnSJf0b5W8v5h2pI/stOSwTQ+pxVhwJ9ctYDhRSlF0iT'
            b'UWT10hcuO4Ks8=')
    good_pub_key = paramiko.RSAKey(data=decodebytes(data))

    def __init__(self):
        self.event = threading.Event()

    def check_channel_request(self, kind, chanid):
        if kind == 'session':
            return paramiko.OPEN_SUCCEEDED
        return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED

    def check_auth_password(self, username, password):
        if (username == 'robey') and (password == 'foo'):
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED

    def check_auth_publickey(self, username, key):
        print('Auth attempt with key: ' + u(hexlify(key.get_fingerprint())))
        if (username == 'robey') and (key == self.good_pub_key):
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED

    def check_auth_gssapi_with_mic(self,
                                   username,
                                   gss_authenticated=paramiko.AUTH_FAILED,
                                   cc_file=None):
        """
        .. note::
            We are just checking in `AuthHandler` that the given user is a
            valid krb5 principal! We don't check if the krb5 principal is
            allowed to log in on the server, because there is no way to do that
            in python. So if you develop your own SSH server with paramiko for
            a certain platform like Linux, you should call ``krb5_kuserok()`` in
            your local kerberos library to make sure that the krb5_principal
            has an account on the server and is allowed to log in as a user.

        .. seealso::
            `krb5_kuserok() man page
            <http://www.unix.com/man-page/all/3/krb5_kuserok/>`_
        """
        if gss_authenticated == paramiko.AUTH_SUCCESSFUL:
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED

    def check_auth_gssapi_keyex(self,
                                username,
                                gss_authenticated=paramiko.AUTH_FAILED,
                                cc_file=None):
        if gss_authenticated == paramiko.AUTH_SUCCESSFUL:
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED

    def enable_auth_gssapi(self):
        return True

    def get_allowed_auths(self, username):
        return 'gssapi-keyex,gssapi-with-mic,password,publickey'

    def check_channel_shell_request(self, channel):
        self.event.set()
        return True

    def check_channel_pty_request(self, channel, term, width, height,
                                  pixelwidth, pixelheight, modes):
        return True
Beispiel #15
0
#!/usr/bin/env python2.7
import socket, sys, threading, thread
import paramiko

#generate keys with 'ssh-keygen -t rsa -f server.key'
HOST_KEY = paramiko.RSAKey(filename='/var/log/contrSSH/server.key')
SSH_PORT = 22
LOGFILE = '/var/log/contrSSH/logins.log'  #File to log the user:password combinations to
LOGFILE_LOCK = threading.Lock()


class SSHServerHandler(paramiko.ServerInterface):
    def __init__(self):
        self.event = threading.Event()

    def check_auth_password(self, username, password):
        LOGFILE_LOCK.acquire()
        try:
            logfile_handle = open(LOGFILE, "a")
            print("New login: "******":" + password)
            logfile_handle.write(username + ":" + password + "\n")
            logfile_handle.close()
        finally:
            LOGFILE_LOCK.release()
        return paramiko.AUTH_FAILED

    def get_allowed_auths(self, username):
        return 'password'


def handleConnection(client):
#!/usr/bin/python3

import socket
import paramiko
import threading
import sys

# Load key
# Very good programming
host_key = paramiko.RSAKey(filename='../keys/ssh_host_rsa_key')


class Server(paramiko.ServerInterface):
    def __init__(self):
        self.event = threading.Event()

    def check_channel_request(self, kind, chanid):
        if kind == 'session':
            return paramiko.OPEN_SUCCEEDED
        return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED

    def check_auth_password(self, username, password):
        if (username == 'root') and (password == 'toor'):
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED


server = sys.argv[1]
ssh_port = int(sys.argv[2])
try:
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
Beispiel #17
0
def _importKey(filename, allow_prompt=True, logger=None):
    '''
    Import a RSA or DSA key from file contents
    If the key file requires a passphrase, ask for it only if allow_prompt is
    True. Otherwise, reraise the paramiko.PasswordRequiredException. If the
    key fails to load as a RSA key, try loading as DSA key. If it fails both,
    then raises a ValueError with the reported errors from both RSA and DSA
    attempts.
    '''
    # Try RSA first
    try:
        key = paramiko.RSAKey(filename=filename)
        if logger:
            logger.debug('Loaded unprotected RSA key from %s', filename)
        return key
    except paramiko.PasswordRequiredException:
        # Need passphrase for RSA key
        if not allow_prompt:
            return RuntimeError('RSA Key is Passphrase-Protected')
        retries = 3
        while retries:
            try:
                passphrase = user_password(
                    'Enter passphrase for RSA key [%s]: ' % filename)
                key = paramiko.RSAKey(filename=filename, password=passphrase)
                if logger:
                    logger.debug('Loaded passphrase protected RSA key from %s',
                                 filename)
                return key
            except paramiko.SSHException as e:
                print(repr(e))
                retries -= 1
        return Exception('3 failed passphrase attempts for %s' % filename)
    except paramiko.SSHException as e:
        rsa_exception = e
    if logger:
        logger.debug('Failed to load %s as RSA key\n\t%s', filename,
                     repr(rsa_exception))

    # Format error - could be ECDSA key instead...
    try:
        key = paramiko.ECDSAKey(filename=filename)
        if logger:
            logger.debug('Loaded unprotected ECDSA key from %s', filename)
        return key
    except paramiko.PasswordRequiredException:
        # Need passphrase for ECDSA key
        if not allow_prompt:
            return RuntimeError('ECDSA Key is Passphrase-Protected')
        retries = 3
        while retries:
            try:
                passphrase = user_password(
                    'Enter passphrase for ECDSA key [%s]: ' % filename)
                key = paramiko.ECDSAKey(filename=filename, password=passphrase)
                if logger:
                    logger.debug(
                        'Loaded passphrase protected ECDSA key from %s',
                        filename)
                return key
            except paramiko.SSHException as e:
                print(repr(e))
                retries -= 1
        return Exception('3 failed passphrase attempts for %s' % filename)
    except paramiko.SSHException as e:
        ecdsa_exception = e

    if logger:
        logger.debug('Failed to load %s as ECDSA key\n\t%s', filename,
                     repr(ecdsa_exception))

    # Format error - could be DSA key instead...
    try:
        key = paramiko.DSSKey(filename=filename)
        if logger:
            logger.debug('Loaded unprotected DSA key from %s', filename)
        return key
    except paramiko.PasswordRequiredException:
        # Need passphrase for DSA key
        if not allow_prompt:
            return RuntimeError('DSA Key is Passphrase-Protected')
        retries = 3
        while retries:
            try:
                passphrase = user_password(
                    'Enter passphrase for DSA key [%s]: ' % filename)
                key = paramiko.DSSKey(filename=filename, password=passphrase)
                if logger:
                    logger.debug('Loaded passphrase protected DSA key from %s',
                                 filename)
                return key
            except paramiko.SSHException as e:
                print(repr(e))
                retries -= 1
        return Exception('3 failed passphrase attempts for %s' % filename)
    except paramiko.SSHException as e:
        dsa_exception = e

    if logger:
        logger.debug('Failed to load %s as DSA key\n\t%s', filename,
                     repr(dsa_exception))
    # Give up on using this key
    if logger:
        logger.error(
            'Unable to load key from [%s] | RSA failure: %r | ECDSA failure: %r | DSA failure: %r'
            % (filename, rsa_exception, ecdsa_exception, dsa_exception))
    # Return, rather than raise the exception - Caller just needs something to
    # fill the deferred_keys entry with that's not a paramiko.PKey and not None.
    return RuntimeError('Unrecognized key: %s' % filename)
Beispiel #18
0
    def start(self):
        """This will connect to the server and start port forwarding to the given port of the localhost"""
        self.client.load_system_host_keys()

        logger.debug('Connecting to ssh host %s:%d ...' %
                     (self.server, self.server_ssh_port))
        pk = paramiko.RSAKey(filename=self.private_key_file)

        try:
            self.client.connect(self.server,
                                self.server_ssh_port,
                                username=self.ssh_user,
                                pkey=pk,
                                look_for_keys=False)
            self.stopped = False
        except Exception as e:
            logger.error('*** Failed to connect to %s:%d: %r' %
                         (self.server, self.server_ssh_port, e))
            if self.fallback_server_ssh_port is not None:
                try:
                    logger.debug('Connecting to fallback ssh host %s:%d ...' %
                                 (self.fallback_ssh_server,
                                  self.fallback_server_ssh_port))
                    self.client.connect(self.fallback_ssh_server,
                                        self.fallback_server_ssh_port,
                                        username=self.ssh_user,
                                        pkey=pk,
                                        look_for_keys=False)
                    self.stopped = False
                except Exception as e:
                    logger.error(
                        '*** Failed to fallback connect to %s:%d: %r' %
                        (self.fallback_ssh_server,
                         self.fallback_server_ssh_port, e))
                    if self.error_callback:
                        self.error_callback(e)
                    return
            else:
                if self.error_callback:
                    self.error_callback(e)
                return

        try:
            stdin, stdout, stderr = run_method_with_timeout(
                lambda: self.client.exec_command(self.session_token),
                timeout_s=10)
        except (TimeoutException, paramiko.SSHException):
            raise TunnelError('Connection to the server seems to be lost.')

        try:
            self.portForwardingRequestException = None

            if self.forward_tunnel:
                thr = threading.Thread(target=self._forward_remote_port)
            else:
                thr = threading.Thread(target=self._forward_local_port)
            thr.setDaemon(True)
            thr.start()

            if self.start_callback:
                start_callback_thread = threading.Thread(
                    target=self.start_callback)
                start_callback_thread.setDaemon(True)
                start_callback_thread.start()

            self.keep_alive()
        except KeyboardInterrupt as e:
            self.stop()
            logger.info('Ctrl-c: Port forwarding stopped.')


#            sys.exit(0)
        except EOFError as e:
            # Tunnel is stopped.
            self.stop()
            logger.debug(e)
        except:
            self.stop()
            raise
Beispiel #19
0
 def host_key(self):
     host_key_path = os.path.join(config['ROOT_PATH'], 'keys',
                                  'host_rsa_key')
     if not os.path.isfile(host_key_path):
         self.gen_host_key(host_key_path)
     return paramiko.RSAKey(filename=host_key_path)
Beispiel #20
0
        "(", "").replace(")", "").replace("'", "")
    data = data.split()
    d1 = "-Name: " + data[0]
    d2 = "-FQDN: " + data[1]
    d3 = "-Provider: " + data[2]
    chan.send("   " + d1 + "\r\n")
    chan.send("   " + d2 + "\r\n")
    chan.send("   " + d3 + "\r\n")


logger = logging.getLogger("access.log")
logger.setLevel(logging.INFO)
lh = logging.FileHandler(LOG_FILE)
logger.addHandler(lh)

host_key = paramiko.RSAKey(filename="rsa.key")

print "\nKey: " + u(hexlify(host_key.get_fingerprint()))
print ""


class Server(paramiko.ServerInterface):
    def __init__(self, client_address):
        self.event = threading.Event()
        self.client_address = client_address

    def check_channel_request(self, kind, chanid):
        if kind == "session":
            return paramiko.OPEN_SUCCEEDED
        return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
Beispiel #21
0
def to_paramiko_private_key(pkey):
    """Convert private key (str) to paramiko-specific RSAKey object."""
    return paramiko.RSAKey(file_obj=six.StringIO(pkey))
Beispiel #22
0
def generate_host_key(pkey: paramiko.PKey):
    key_fh = StringIO()
    pkey.write_private_key(key_fh)
    key_fh.seek(0)
    key_obj = paramiko.RSAKey(file_obj=key_fh)
    return key_obj.get_base64()
Beispiel #23
0
import socket
import paramiko
import threading
import sys

host_key = paramiko.RSAKey(filename='/etc/ssh/ssh_host_rsa_key')


class Server(paramiko.ServerInterface):
    data = (
        b'AAAAB3NzaC1yc2EAAAADAQABAAABAQDJSfJAOSf5Hl8AIJaZU1DFDXSkEaci'
        b'BDZTMd2WlhNaGWajADvFDKSjI0Wlp2tpnXmkAuKKuB9cd2fT5EMCNny3BW/5'
        b'p/pmi9TadbP9nwpOJmfH7j0TLRnG2Fhn4CxDOY3RLQIf5nZtk0bTaY4168bG'
        b'G+c4B75sRS4q5/shGs0LELu8NOhdEqbmVteL/51K4rle5N354Fatbnrlpk7j'
        b'JBaKWSLJ8Jk9C5dkNHCtjb/pQ8gt9O6tst7IasU32pB0mWIQWEjd/ZtqZSSq'
        b'uXTq5Xbby+H6BIkbuEKGLzbQc+dwgflwJvZ6MIvbQZR5/wFD41jPtEdF/JlZKeUX8gdMylJ9'
    )

    def _init_(self):
        self.event = threading.Event()

    def check_channel_request(self, kind, chanid):
        if kind == 'session':
            return paramiko.OPEN_SUCCEEDED
        return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED

    def check_auth_password(self, username, password):
        if (username == 'mjlee') and (password == 'mjlee'):
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED
Beispiel #24
0
    def run(self, name, image, entrypoint, command):  # noqa
        """Run a one-off command"""
        self._create_container(name,
                               image,
                               command,
                               copy.deepcopy(RUN_TEMPLATE),
                               entrypoint=entrypoint)

        # wait for the container to get scheduled
        for _ in range(30):
            states = self._get_state(name)
            if states and len(states.get('states', [])) == 1:
                state = states.get('states')[0]
                break
            time.sleep(1)
        else:
            raise RuntimeError('container did not report state')

        try:
            machineID = state.get('machineID')

            # find the machine
            machines = self._get_machines()
            if not machines:
                raise RuntimeError('no available hosts to run command')

            # find the machine's primaryIP
            primaryIP = None
            for m in machines.get('machines', []):
                if m['id'] == machineID:
                    primaryIP = m['primaryIP']
            if not primaryIP:
                raise RuntimeError('could not find host')

            # prepare ssh key
            file_obj = cStringIO.StringIO(base64.b64decode(self.pkey))
            pkey = paramiko.RSAKey(file_obj=file_obj)

            # grab output via docker logs over SSH
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(primaryIP, username="******", pkey=pkey)
            # share a transport
            tran = ssh.get_transport()

            def _do_ssh(cmd):
                chan = tran.open_session()
                # get a pty so stdout/stderr look right
                chan.get_pty()
                out = chan.makefile()
                chan.exec_command(cmd)
                rc, output = chan.recv_exit_status(), out.read()
                return rc, output

            # wait for container to launch
            # we loop indefinitely here, as we have no idea how long the docker pull will take
            while True:
                rc, _ = _do_ssh('docker inspect {name}'.format(**locals()))
                if rc == 0:
                    break
                time.sleep(1)
            else:
                raise RuntimeError('failed to create container')

            # wait for container to start
            for _ in range(2):
                _rc, _output = _do_ssh(
                    'docker inspect {name}'.format(**locals()))
                if _rc != 0:
                    raise RuntimeError('failed to inspect container')
                _container = json.loads(_output)
                started_at = _container[0]["State"]["StartedAt"]
                if not started_at.startswith('0001'):
                    break
                time.sleep(1)
            else:
                raise RuntimeError('container failed to start')

            # wait for container to complete
            for _ in range(1200):
                _rc, _output = _do_ssh(
                    'docker inspect {name}'.format(**locals()))
                if _rc != 0:
                    raise RuntimeError('failed to inspect container')
                _container = json.loads(_output)
                finished_at = _container[0]["State"]["FinishedAt"]
                if not finished_at.startswith('0001'):
                    break
                time.sleep(1)
            else:
                raise RuntimeError('container timed out')

            # gather container output
            _rc, output = _do_ssh('docker logs {name}'.format(**locals()))
            if _rc != 0:
                raise RuntimeError('could not attach to container')

            # determine container exit code
            _rc, _output = _do_ssh('docker inspect {name}'.format(**locals()))
            if _rc != 0:
                raise RuntimeError('could not determine exit code')
            container = json.loads(_output)
            rc = container[0]["State"]["ExitCode"]

        finally:
            # cleanup
            self._destroy_container(name)
            self._wait_for_destroy(name)

        # return rc and output
        return rc, output
Beispiel #25
0
import random
import socket
# import sys
import threading
# import traceback
import paramiko

from binascii import hexlify
from paramiko.py3compat import u, decodebytes
from tests.utils import make_tests_data_path

# setup logging
paramiko.util.log_to_file(make_tests_data_path('sshserver.log'))

host_key = paramiko.RSAKey(filename=make_tests_data_path('test_rsa.key'))
# host_key = paramiko.DSSKey(filename='test_dss.key')

print('Read key: ' + u(hexlify(host_key.get_fingerprint())))

banner = u'\r\n\u6b22\u8fce\r\n'
event_timeout = 5


class Server(paramiko.ServerInterface):
    # 'data' is the output of base64.b64encode(key)
    # (using the "user_rsa_key" files)
    data = (b'AAAAB3NzaC1yc2EAAAABIwAAAIEAyO4it3fHlmGZWJaGrfeHOVY7RWO3P9M7hp'
            b'fAu7jJ2d7eothvfeuoRFtJwhUmZDluRdFyhFY/hFAh76PJKGAusIqIQKlkJxMC'
            b'KDqIexkgHAfID/6mqvmnSJf0b5W8v5h2pI/stOSwTQ+pxVhwJ9ctYDhRSlF0iT'
            b'UWT10hcuO4Ks8=')
Beispiel #26
0
def main():
    # exit script upon CTRL+C
    signal.signal(signal.SIGINT, signal_handler)
    # process script arguments
    args = load_arguments()
    # display version and exit
    if args.version:
        print("ssh_to_telnet_proxy" + " : " + __version__)
        sys.exit(0)

    # set logging basic configuration
    logging.basicConfig(level=args.loglevel.upper(),
                        format='%(asctime)s '
                        '%(filename)s: '
                        '%(levelname)s: '
                        '%(funcName)s(): '
                        '%(lineno)d:\t'
                        '%(message)s')

    # setup paramiko local logging
    paramiko.util.log_to_file(args.logfile)
    # Define server key
    host_key = paramiko.RSAKey(filename=args.key)

    # now connect
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(("", args.port))
    except Exception as e:
        print("*** Bind failed: " + str(e))
        traceback.print_exc()
        sys.exit(1)

    try:
        while True:
            client = None
            try:
                sock.listen(100)
                print("Listening for connection ...")
                client, addr = sock.accept()
            except Exception as e:
                print("*** Listen/accept failed: " + str(e))
                traceback.print_exc()
                sys.exit(1)

            print("Got a connection!")

            try:
                new_thread = threading.Thread(name="ssh_session",
                                              target=start_ssh_session_thread,
                                              kwargs={
                                                  "client": client,
                                                  "host_key": host_key
                                              })
                new_thread.start()
            except Exception as e:
                logger.error("*** Caught exception: " + str(e.__class__) +
                             ": " + str(e))
                traceback.print_exc()
                sys.exit(1)

    except KeyboardInterrupt:
        print('Server closing')
        sock.close()
Beispiel #27
0
class PServer(paramiko.ServerInterface):
    # 'data' is the output of base64.b64encode(key)
    # (using the "user_rsa_key" files)
    data = (
        b"AAAAB3NzaC1yc2EAAAABIwAAAIEAyO4it3fHlmGZWJaGrfeHOVY7RWO3P9M7hp"
        b"fAu7jJ2d7eothvfeuoRFtJwhUmZDluRdFyhFY/hFAh76PJKGAusIqIQKlkJxMC"
        b"KDqIexkgHAfID/6mqvmnSJf0b5W8v5h2pI/stOSwTQ+pxVhwJ9ctYDhRSlF0iT"
        b"UWT10hcuO4Ks8="
    )
    good_pub_key = paramiko.RSAKey(data=decodebytes(data))
    usePty = False
    pty = None

    def __init__(self):
        self.event = threading.Event()

    def check_channel_request(self, kind, chanid):
        if kind == "session":
            return paramiko.OPEN_SUCCEEDED
        return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED

    def check_auth_password(self, username, password):
        if (username == "test") and (password == "password"):
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED

    def check_auth_publickey(self, username, key):
        return paramiko.AUTH_FAILED

    def check_auth_gssapi_with_mic(
        self, username, gss_authenticated=paramiko.AUTH_FAILED, cc_file=None
    ):
        return paramiko.AUTH_FAILED

    def check_auth_gssapi_keyex(
        self, username, gss_authenticated=paramiko.AUTH_FAILED, cc_file=None
    ):
        # if gss_authenticated == paramiko.AUTH_SUCCESSFUL:
        #    return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED

    def enable_auth_gssapi(self):
        return False

    def get_allowed_auths(self, username):
        return "password"

    def check_channel_shell_request(self, channel):
        self.event.set()
        print("Requested a shell")
        return True

    def check_channel_pty_request(
        self, channel, term, width, height, pixelwidth, pixelheight, modes
    ):
        print("Requested a Psuedo-terminal, term: {}, width: {}, height: {}, pixelwidth: {}, pixelheight: {}, modes: {}"
              .format(term, width, height, pixelwidth, pixelheight, modes))
        termString = bytes.decode(term, "ascii")
        if "xterm" in termString:
            self.usePty = True
            self.pty = server.Xterm(channel, term, width, height, pixelwidth, pixelheight, modes)
            return True
        else:
            print("Can only emulate xterm ptys")
            return False

    def check_channel_window_change_request(self, channel, width, height, pixelwidth, pixelheight):
        print("Requested a window resize, width: {}, height: {}, pixelWidth: {}, pixelHeight: {}"
              .format(width, height, pixelwidth, pixelheight))
        self.pty.resize(width, height, pixelwidth, pixelheight)
        return True

    def get_banner(self):
        if server.ServerInfo.banner is None:
            return "", "en-US"
        return server.ServerInfo.banner.join("\r\n"), "en-US"
Beispiel #28
0
#!/usr/bin/env python
"""Fake SSH Server Utilizing Paramiko"""
import argparse
import threading
import socket
import sys
import traceback
import paramiko

LOG = open("logs/log.txt", "a")
HOST_KEY = paramiko.RSAKey(filename='keys/private.key')
SSH_BANNER = "SSH-2.0-OpenSSH_8.2p1 Ubuntu-4ubuntu0.3"


def handle_cmd(cmd, chan):
    """Branching statements to handle and prepare a response for a command"""
    response = ""
    if cmd.startswith("sudo"):
        send_ascii("sudo.txt", chan)
        return
    elif cmd.startswith("ls"):
        response = "pw.txt"
    elif cmd.startswith("version"):
        response = "Super Amazing Awesome (tm) Shell v1.1"
    elif cmd.startswith("pwd"):
        response = "/home/clippy"
    elif cmd.startswith("cd"):
        send_ascii("cd.txt", chan)
        return
    elif cmd.startswith("cat"):
        send_ascii("cat.txt", chan)
Beispiel #29
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket
import paramiko
import threading
import sys

# Paramikoのデモファイルに含まれている鍵ファイルを利用
host_key = paramiko.RSAKey(filename='test_rsa.key')


class Server(paramiko.ServerInterface):
    def __init__(self):
        self.event = threading.Event()

    def check_channel_request(self, kind, chanid):
        if kind == 'session':
            return paramiko.OPEN_SUCCEEDED
        return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED

    def check_auth_password(self, username, password):
        if (username == 'justin') and (password == 'lovesthepython'):
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED


server = sys.argv[1]
port = int(sys.argv[2])

try:
Beispiel #30
0
def Connect(hostname,
            username,
            password=None,
            port=22,
            ssh_keys=(),
            timeout=TIMEOUT_DEFAULT):
    """Makes a paramiko SSH connection to a device.

  Args:
    hostname: A string, the hostname or IP address to connect to.
    username: A string, the username to use on the connection.
    password: A string, the password to use on the connection.
    port: An int, the port number to connect to.
    ssh_keys: A tuple of strings, SSH private keys (optional; may be None).
    timeout: A float, the number of seconds before a connection times out.

  Returns:
    A paramiko.SSHClient() instance
  """

    options = SshOptions()
    hostname, port, username = options.Lookup(hostname, port, username)
    ssh_client = None

    def RaiseError(e, msg):
        """Raises an exception, disconnecting the SSH client.

    Args:
      e: An Exception.
      msg: An object, exception arguments.
    """
        raise e(msg)

    try:
        ssh_client = paramiko.SSHClient()
        # Always auto-add remote SSH host keys.
        ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh_client.load_system_host_keys()
        # Connect using paramiko with a timeout parameter (requires paramiko 1.7)
        if ssh_keys:
            pkeys = []
            for key in ssh_keys:
                logging.debug(
                    'Using SSH private key for device authentication.')
                # Use a virtual temporary file to store the key.
                ssh_key_fileobj = cStringIO.StringIO()
                ssh_key_fileobj.write(key)
                ssh_key_fileobj.reset()
                try:
                    pkeys.append(paramiko.DSSKey(file_obj=ssh_key_fileobj))
                    logging.debug('Using SSH DSA key for %r', hostname)
                except (IndexError, paramiko.SSHException) as e:
                    if (isinstance(e, IndexError)
                            or 'not a valid DSA private key file' in str(e)):
                        ssh_key_fileobj.reset()
                        try:
                            logging.debug('Using SSH RSA key for %r', hostname)
                            pkeys.append(
                                paramiko.RSAKey(file_obj=ssh_key_fileobj))
                        except (IndexError, paramiko.SSHException) as e:
                            raise exceptions.AuthenticationError(str(e))
                    else:
                        raise exceptions.ConnectError('SSHException: %s' %
                                                      str(e))
        else:
            logging.debug('Using password for %r', hostname)
            pkeys = [None]
        for pkey in pkeys:
            saved_exception = None
            try:
                ssh_client.connect(hostname=hostname,
                                   port=port,
                                   username=username,
                                   password=password,
                                   pkey=pkey,
                                   timeout=timeout,
                                   allow_agent=FLAGS.use_ssh_agent,
                                   look_for_keys=False)
                break
            except (paramiko.AuthenticationException,
                    paramiko.SSHException) as e:
                saved_exception = e
        if saved_exception is not None:
            raise saved_exception  # pylint: disable=raising-bad-type
        transport = ssh_client.get_transport()
        # Sometimes we have to authenticate a second time, eg. on Force10
        # we always fail the first authentication (if we try pkey + pass,
        # the pass succeeds; but if we do pass only, we have to do it
        # twice).  connect() above will have authenticated once.
        if not transport.is_authenticated():
            if pkeys != [None]:
                for pkey in pkeys:
                    try:
                        transport.auth_publickey(username, pkey)
                        break
                    except paramiko.SSHException:
                        pass
        if not transport.is_authenticated():
            if password is not None:
                try:
                    transport.auth_password(username, password)
                except paramiko.SSHException:
                    pass
        if not transport.is_authenticated():
            msg = 'Not authenticated after two attempts on %r' % hostname
            RaiseError(exceptions.ConnectError, msg)
    except EOFError:
        msg = 'EOFError connecting to: %r' % hostname
        RaiseError(exceptions.ConnectError, msg)
    except paramiko.AuthenticationException as e:
        msg = 'Authentication error connecting to %s: %s' % (hostname, str(e))
        RaiseError(exceptions.AuthenticationError, msg)
    except paramiko.SSHException as e:
        msg = 'SSHException connecting to %s: %s' % (hostname, str(e))
        RaiseError(exceptions.ConnectError, msg)
    except socket.timeout as e:
        msg = 'Timed-out while connecting to %s: %s' % (hostname, str(e))
        RaiseError(exceptions.ConnectError, msg)
    except socket.error as e:
        msg = 'Socket error connecting to %r: %s %s' % (hostname, e.__class__,
                                                        e)
        RaiseError(exceptions.ConnectError, msg)

    return ssh_client