當前位置: 首頁>>代碼示例>>Python>>正文


Python paramiko.SSHException方法代碼示例

本文整理匯總了Python中paramiko.SSHException方法的典型用法代碼示例。如果您正苦於以下問題:Python paramiko.SSHException方法的具體用法?Python paramiko.SSHException怎麽用?Python paramiko.SSHException使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在paramiko的用法示例。


在下文中一共展示了paramiko.SSHException方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: fetch_remote_crashes

# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHException [as 別名]
def fetch_remote_crashes(self):
        """
        some exception handling code is taken from https://www.programcreek.com/python/example/105570/scp.SCPClient
        """
        try:
            ssh = SSHClient()
            ssh.load_system_host_keys()
            ssh.connect(hostname=config.remote_system_ip)
            self.copy_crashes_dir_with_scp(ssh)
        except AuthenticationException:
            print("Authentication failed, please verify your credentials: %s")
        except SSHException as sshException:
            print("Unable to establish SSH connection: %s" % sshException)
        except BadHostKeyException as badHostKeyException:
            print("Unable to verify server's host key: %s" % badHostKeyException)
        finally:
            ssh.close() 
開發者ID:fkie-cad,項目名稱:LuckyCAT,代碼行數:19,代碼來源:RemoteCrashFetcher.py

示例2: connect

# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHException [as 別名]
def connect(self):
        """Call to set connection with remote client."""

        try:
            self.paramiko_session = paramiko.SSHClient()
            self.paramiko_session.set_missing_host_key_policy(
                paramiko.AutoAddPolicy())

            self.paramiko_session.connect(
                self.client.ip, username=self.client.user,
                password=self.client.pass_, key_filename=self.client.key,
                allow_agent=True, compress=self.client.compress)

        except (paramiko.AuthenticationException,
                paramiko.ssh_exception.NoValidConnectionsError) as e:
            self.logger.error(e)
            sys.exit(colored("> {}".format(e), 'red'))

        except paramiko.SSHException as e:
            self.logger.error(e)
            sys.exit(colored("> {}".format(e), 'red'))

        self.transfer = network.Network(
            self.paramiko_session, self.client.ip, self.client.port)
        self.transfer.open() 
開發者ID:kd8bny,項目名稱:LiMEaide,代碼行數:27,代碼來源:network.py

示例3: sshInstall

# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHException [as 別名]
def sshInstall(retry,hostname):
    global user
    global password
    global userInsightfinder
    global licenseKey
    global samplingInterval
    global reportingInterval
    global agentType
    if retry == 0:
        print "Install Fail in", hostname
        q.task_done()
        return
    print "Start installing agent in", hostname, "..."
    try:
        s = paramiko.SSHClient()
        s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        if os.path.isfile(password) == True:
            s.connect(hostname, username=user, key_filename = password, timeout=60)
        else:
            s.connect(hostname, username=user, password = password, timeout=60)
        transport = s.get_transport()
        session = transport.open_session()
        session.set_combine_stderr(True)
        session.get_pty()
        session.exec_command("sudo rm -rf insightagent* InsightAgent* \n \
        wget --no-check-certificate https://github.com/insightfinder/InsightAgent/archive/master.tar.gz -O insightagent.tar.gz && \
        tar xzvf insightagent.tar.gz && \
        cd InsightAgent-master && deployment/checkpackages.sh -env\n")
        stdin = session.makefile('wb', -1)
        stdout = session.makefile('rb', -1)
        stdin.write(password+'\n')
        stdin.flush()
        session.recv_exit_status() #wait for exec_command to finish
        s.close()
        print "Install Succeed in", hostname
        q.task_done()
        return
    except paramiko.SSHException, e:
        print "Invalid Username/Password for %s:"%hostname , e
        return sshInstall(retry-1,hostname) 
開發者ID:insightfinder,項目名稱:InsightAgent,代碼行數:42,代碼來源:installInsightAgent.py

示例4: sshStopCron

# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHException [as 別名]
def sshStopCron(retry,hostname):
    global user
    global password
    if retry == 0:
        print "Stop Cron Failed in", hostname
        q.task_done()
        return
    try:
        s = paramiko.SSHClient()
        s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        if os.path.isfile(password) == True:
            s.connect(hostname, username=user, key_filename = password, timeout=60)
        else:
            s.connect(hostname, username=user, password = password, timeout=60)
        transport = s.get_transport()
        session = transport.open_session()
        session.set_combine_stderr(True)
        session.get_pty()
        command = "sudo mv /etc/cron.d/ifagent InsightAgent-master/ifagent."+time.strftime("%Y%m%d%H%M%S")+"\n"
        session.exec_command(command)
        stdin = session.makefile('wb', -1)
        stdout = session.makefile('rb', -1)
        stdin.write(password+'\n')
        stdin.flush()
        session.recv_exit_status() #wait for exec_command to finish
        s.close()
        print "Stopped Cron in ", hostname
        q.task_done()
        return
    except paramiko.SSHException, e:
        print "Invalid Username/Password for %s:"%hostname , e
        return sshStopCron(retry-1,hostname) 
開發者ID:insightfinder,項目名稱:InsightAgent,代碼行數:34,代碼來源:stopcron.py

示例5: sshStopCron

# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHException [as 別名]
def sshStopCron(retry,hostname):
    global user
    global password
    if retry == 0:
        print "Stop Cron Failed in", hostname
        q.task_done()
        return
    try:
        s = paramiko.SSHClient()
        s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        if os.path.isfile(password) == True:
            s.connect(hostname, username=user, key_filename = password, timeout=60)
        else:
            s.connect(hostname, username=user, password = password, timeout=60)
        transport = s.get_transport()
        session = transport.open_session()
        session.set_combine_stderr(True)
        session.get_pty()
        command = "./InsightAgent-master/hypervisor/stopcron.sh -t hypervisor\n"
        session.exec_command(command)
        stdin = session.makefile('wb', -1)
        stdout = session.makefile('rb', -1)
        stdin.write(password+'\n')
        stdin.flush()
        session.recv_exit_status() #wait for exec_command to finish
        s.close()
        print "Stopped Cron in ", hostname
        q.task_done()
        return
    except paramiko.SSHException, e:
        print "Invalid Username/Password for %s:"%hostname , e
        return sshStopCron(retry-1,hostname) 
開發者ID:insightfinder,項目名稱:InsightAgent,代碼行數:34,代碼來源:stopcron.py

示例6: test_connectivity

# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHException [as 別名]
def test_connectivity(self, time_out=None):
        """ Tests if the SSH is active

            Arguments:
            - time_out: Timeout to connect.

            Returns: True if the connection is established or False otherwise

            Raises:
                Exception
        """
        try:
            client, proxy = self.connect(time_out)
            client.close()
            if proxy:
                proxy.close()
            return True
        except paramiko.AuthenticationException:
            raise AuthenticationException("Authentication Error!!")
        except paramiko.SSHException as e:
            if str(e) == "No authentication methods available":
                raise AuthenticationException("Authentication Error!!")
            return False
        except Exception:
            return False 
開發者ID:grycap,項目名稱:im,代碼行數:27,代碼來源:SSH.py

示例7: test_fail_percent

# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHException [as 別名]
def test_fail_percent(self):
        inventory = make_inventory((
            'somehost',
            ('thinghost', {'ssh_hostname': SSHException}),
            'anotherhost',
        ))
        state = State(inventory, Config(FAIL_PERCENT=1))

        # Ensure we would fail at this point
        with self.assertRaises(PyinfraError) as context:
            connect_all(state)

        assert context.exception.args[0] == 'Over 1% of hosts failed (33%)'

        # Ensure the other two did connect
        assert len(state.active_hosts) == 2 
開發者ID:Fizzadar,項目名稱:pyinfra,代碼行數:18,代碼來源:test_api.py

示例8: get_private_keys

# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHException [as 別名]
def get_private_keys():
    """Find SSH keys in standard folder."""
    key_formats = [RSAKey, ECDSAKey, Ed25519Key]

    ssh_folder = os.path.expanduser("~/.ssh")

    available_private_keys = []
    if os.path.isdir(ssh_folder):
        for key in os.listdir(ssh_folder):
            for key_format in key_formats:
                try:
                    parsed_key = key_format.from_private_key_file(
                        os.path.join(ssh_folder, key)
                    )
                    key_details = {
                        "filename": key,
                        "format": parsed_key.get_name(),
                        "bits": parsed_key.get_bits(),
                        "fingerprint": parsed_key.get_fingerprint().hex(),
                    }
                    available_private_keys.append(key_details)
                except (SSHException, UnicodeDecodeError, IsADirectoryError):
                    continue

    return available_private_keys 
開發者ID:Mebus,項目名稱:restatic,代碼行數:27,代碼來源:utils.py

示例9: execute

# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHException [as 別名]
def execute(self, command):
        """
        Executes command on remote hosts

        :type command: str
        :param command: command to be run on remote host
        """
        try:
            if self.ssh.get_transport() is not None:
                logger.debug('{0}: executing "{1}"'.format(self.target_address,
                                                           command))
                stdin, stdout, stderr = self.ssh.exec_command(command)
                return dict(zip(['stdin', 'stdout', 'stderr'],
                                [stdin, stdout, stderr]))
            else:
                raise SSHConnectionError(self.target_address,
                                         "ssh transport is closed")
        except (AuthenticationException, SSHException,
                ChannelException, SocketError) as ex:
            logger.critical(("{0} execution failed on {1} with exception:"
                             "{2}".format(command, self.target_address,
                                               ex)))
            raise SSHCommandError(self.target_address, command, ex) 
開發者ID:ThreatResponse,項目名稱:margaritashotgun,代碼行數:25,代碼來源:remote_shell.py

示例10: execute_async

# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHException [as 別名]
def execute_async(self, command, callback=None):
        """
        Executes command on remote hosts without blocking

        :type command: str
        :param command: command to be run on remote host
        :type callback: function
        :param callback: function to call when execution completes
        """
        try:
            logger.debug(('{0}: execute async "{1}"'
                          'with callback {2}'.format(self.target_address,
                                                     command,
                                                     callback)))
            future = self.executor.submit(self.execute, command)
            if callback is not None:
                future.add_done_callback(callback)
            return future
        except (AuthenticationException, SSHException,
                ChannelException, SocketError) as ex:
            logger.critical(("{0} execution failed on {1} with exception:"
                             "{2}".format(command, self.target_address,
                                               ex)))
            raise SSHCommandError(self.target_address, command, ex) 
開發者ID:ThreatResponse,項目名稱:margaritashotgun,代碼行數:26,代碼來源:remote_shell.py

示例11: upload_file

# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHException [as 別名]
def upload_file(self, local_path, remote_path):
        """
        Upload a file from the local filesystem to the remote host

        :type local_path: str
        :param local_path: path of local file to upload
        :type remote_path: str
        :param remote_path: destination path of upload on remote host
        """
        logger.debug("{0}: uploading {1} to {0}:{2}".format(self.target_address,
                                                            local_path,
                                                            remote_path))
        try:
            sftp = paramiko.SFTPClient.from_transport(self.transport())
            sftp.put(local_path, remote_path)
            sftp.close()
        except SSHException as ex:
            logger.warn(("{0}: LiME module upload failed with exception:"
                         "{1}".format(self.target_address, ex))) 
開發者ID:ThreatResponse,項目名稱:margaritashotgun,代碼行數:21,代碼來源:remote_shell.py

示例12: get_specific_pkey

# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHException [as 別名]
def get_specific_pkey(self, name, offset, password):
        self.iostr.seek(offset)
        logging.debug('Reset offset to {}.'.format(offset))

        logging.debug('Try parsing it as {} type key'.format(name))
        pkeycls = getattr(paramiko, name+'Key')
        pkey = None

        try:
            pkey = pkeycls.from_private_key(self.iostr, password=password)
        except paramiko.PasswordRequiredException:
            raise InvalidValueError('Need a passphrase to decrypt the key.')
        except (paramiko.SSHException, ValueError) as exc:
            self.last_exception = exc
            logging.debug(str(exc))

        return pkey 
開發者ID:huashengdun,項目名稱:webssh,代碼行數:19,代碼來源:handler.py

示例13: get_default_encoding

# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHException [as 別名]
def get_default_encoding(self, ssh):
        commands = [
            '$SHELL -ilc "locale charmap"',
            '$SHELL -ic "locale charmap"'
        ]

        for command in commands:
            try:
                _, stdout, _ = ssh.exec_command(command, get_pty=True)
            except paramiko.SSHException as exc:
                logging.info(str(exc))
            else:
                data = stdout.read()
                logging.debug('{!r} => {!r}'.format(command, data))
                result = self.parse_encoding(data)
                if result:
                    return result

        logging.warning('Could not detect the default encoding.')
        return 'utf-8' 
開發者ID:huashengdun,項目名稱:webssh,代碼行數:22,代碼來源:handler.py

示例14: on_message

# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHException [as 別名]
def on_message(self, message):
        logging.debug('{!r} from {}:{}'.format(message, *self.src_addr))
        worker = self.worker_ref()
        try:
            msg = json.loads(message)
        except JSONDecodeError:
            return

        if not isinstance(msg, dict):
            return

        resize = msg.get('resize')
        if resize and len(resize) == 2:
            try:
                worker.chan.resize_pty(*resize)
            except (TypeError, struct.error, paramiko.SSHException):
                pass

        data = msg.get('data')
        if data and isinstance(data, UnicodeType):
            worker.data_to_dst.append(data)
            worker.on_write() 
開發者ID:huashengdun,項目名稱:webssh,代碼行數:24,代碼來源:handler.py

示例15: ssh_exec_command

# 需要導入模塊: import paramiko [as 別名]
# 或者: from paramiko import SSHException [as 別名]
def ssh_exec_command(ssh_obj, cmd, prefix=''):
    """
        Execute a command on the ssh connection.
    :param ssh_obj: SSH object.
    :param cmd: command to run.
    :param prefix: Prefix to be used for printing
    :return: stdout and stderr
    """
    try:
        print(prefix+ "[*] Running Command:" + cmd)
        _, stdout_obj, stderr_obj = ssh_obj.exec_command(cmd)
        exit_status = stdout_obj.channel.recv_exit_status()
        if exit_status == 0:
            print(prefix + GREEN_PRINT + "[+] Command:" + cmd + " Completed Successfully" + END_PRINT)
        else:
            print(prefix + RED_PRINT + "[*] Command:" + cmd + " Return Code:" + str(exit_status) + END_PRINT)

    except paramiko.SSHException as e:
        print(prefix + RED_PRINT + "[!] Problem occurred while running command: %s, Error: %s" % (cmd, e) + END_PRINT)
        raise e
    return stdout_obj, stderr_obj 
開發者ID:mechaphish,項目名稱:setup,代碼行數:23,代碼來源:vm_setup.py


注:本文中的paramiko.SSHException方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。