Python ssh connect with key

Client¶

A high-level representation of a session with an SSH server. This class wraps Transport , Channel , and SFTPClient to take care of most aspects of authenticating and opening channels. A typical use case is:

client = SSHClient() client.load_system_host_keys() client.connect('ssh.example.com') stdin, stdout, stderr = client.exec_command('ls -l') 

You may pass in explicit overrides for authentication and server host key checking. The default mechanism is to try to use local key files or an SSH agent (if one is running).

Instances of this class may be used as context managers.

load_system_host_keys ( filename = None ) ¶

Load host keys from a system (read-only) file. Host keys read with this method will not be saved back by save_host_keys .

This method can be called multiple times. Each new set of host keys will be merged with the existing set (new replacing old if there are conflicts).

If filename is left as None , an attempt will be made to read keys from the user’s local “known hosts” file, as used by OpenSSH, and no exception will be raised if the file can’t be read. This is probably only useful on posix.

filename (str) – the filename to read, or None

IOError – if a filename was provided and the file could not be read

Load host keys from a local host-key file. Host keys read with this method will be checked after keys loaded via load_system_host_keys , but will be saved back by save_host_keys (so they can be modified). The missing host key policy AutoAddPolicy adds keys to this set and saves them, when connecting to a previously-unknown server.

This method can be called multiple times. Each new set of host keys will be merged with the existing set (new replacing old if there are conflicts). When automatically saving, the last hostname is used.

filename (str) – the filename to read

IOError – if the filename could not be read

Save the host keys back to a file. Only the host keys loaded with load_host_keys (plus any added directly) will be saved – not any host keys loaded with load_system_host_keys .

filename (str) – the filename to save to

IOError – if the file could not be written

Get the local HostKeys object. This can be used to examine the local host keys or change them.

the local host keys as a HostKeys object.

Set the channel for logging. The default is «paramiko.transport» but it can be set to anything you want.

name (str) – new channel name for logging

Set policy to use when connecting to servers without a known host key.

  • A policy is a “policy class” (or instance thereof), namely some subclass of MissingHostKeyPolicy such as RejectPolicy (the default), AutoAddPolicy , WarningPolicy , or a user-created subclass.
  • A host key is known when it appears in the client object’s cached host keys structures (those manipulated by load_system_host_keys and/or load_host_keys ).

policy (MissingHostKeyPolicy) – the policy to use when receiving a host key from a previously-unknown server

connect ( hostname , port = 22 , username = None , password = None , pkey = None , key_filename = None , timeout = None , allow_agent = True , look_for_keys = True , compress = False , sock = None , gss_auth = False , gss_kex = False , gss_deleg_creds = True , gss_host = None , banner_timeout = None , auth_timeout = None , channel_timeout = None , gss_trust_dns = True , passphrase = None , disabled_algorithms = None , transport_factory = None , auth_strategy = None ) ¶

Connect to an SSH server and authenticate to it. The server’s host key is checked against the system host keys (see load_system_host_keys ) and any local host keys ( load_host_keys ). If the server’s hostname is not found in either set of host keys, the missing host key policy is used (see set_missing_host_key_policy ). The default policy is to reject the key and raise an SSHException .

Authentication is attempted in the following order of priority:

  • The pkey or key_filename passed in (if any)
    • key_filename may contain OpenSSH public certificate paths as well as regular private-key paths; when files ending in -cert.pub are found, they are assumed to match a private key, and both components will be loaded. (The private key itself does not need to be listed in key_filename for this to occur — just the certificate.)
    • When OpenSSH-style public certificates exist that match an existing such private key (so e.g. one has id_rsa and id_rsa-cert.pub ) the certificate will be loaded alongside the private key and used for authentication.

    If a private key requires a password to unlock it, and a password is passed in, that password will be used to attempt to unlock the key.

    • hostname (str) – the server to connect to
    • port (int) – the server port to connect to
    • username (str) – the username to authenticate as (defaults to the current local username)
    • password (str) – Used for password authentication; is also used for private key decryption if passphrase is not given.
    • passphrase (str) – Used for decrypting private keys.
    • pkey (PKey) – an optional private key to use for authentication
    • key_filename (str) – the filename, or list of filenames, of optional private key(s) and/or certs to try for authentication
    • timeout (float) – an optional timeout (in seconds) for the TCP connect
    • allow_agent (bool) – set to False to disable connecting to the SSH agent
    • look_for_keys (bool) – set to False to disable searching for discoverable private key files in ~/.ssh/
    • compress (bool) – set to True to turn on compression
    • sock (socket) – an open socket or socket-like object (such as a Channel ) to use for communication to the target host
    • gss_auth (bool) – True if you want to use GSS-API authentication
    • gss_kex (bool) – Perform GSS-API Key Exchange and user authentication
    • gss_deleg_creds (bool) – Delegate GSS-API client credentials or not
    • gss_host (str) – The targets name in the kerberos database. default: hostname
    • gss_trust_dns (bool) – Indicates whether or not the DNS is trusted to securely canonicalize the name of the host being connected to (default True ).
    • banner_timeout (float) – an optional timeout (in seconds) to wait for the SSH banner to be presented.
    • auth_timeout (float) – an optional timeout (in seconds) to wait for an authentication response.
    • channel_timeout (float) – an optional timeout (in seconds) to wait for a channel open response.
    • disabled_algorithms (dict) – an optional dict passed directly to Transport and its keyword argument of the same name.
    • transport_factory – an optional callable which is handed a subset of the constructor arguments (primarily those related to the socket, GSS functionality, and algorithm selection) and generates a Transport instance to be used by this client. Defaults to Transport.__init__ .
    • auth_strategy – an optional instance of AuthStrategy , triggering use of this newer authentication mechanism instead of SSHClient’s legacy auth method.

    Warning This parameter is incompatible with all other authentication-related parameters (such as, but not limited to, password , key_filename and allow_agent ) and will trigger an exception if given alongside them.

    AuthResult if auth_strategy is non- None ; otherwise, returns None .

    • BadHostKeyException – if the server’s host key could not be verified.
    • AuthenticationException – if authentication failed.
    • UnableToAuthenticate – if authentication failed (when auth_strategy is non- None ; and note that this is a subclass of AuthenticationException ).
    • socket.error – if a socket error (other than connection-refused or host-unreachable) occurred while connecting.
    • NoValidConnectionsError – if all valid connection targets for the requested hostname (eg IPv4 and IPv6) yielded connection-refused or host-unreachable socket errors.
    • SSHException – if there was any other error connecting or establishing an SSH session.

    Changed in version 1.15: Added the banner_timeout , gss_auth , gss_kex , gss_deleg_creds and gss_host arguments.

    Changed in version 2.3: Added the gss_trust_dns argument.

    Источник

    Как использовать Python для работы с SSH

    В данной статье мы рассмотрим, как использовать Python для работы с SSH (Secure Shell) – протоколом, используемым для безопасного удаленного управления системами и передачи данных между компьютерами.

    Использование библиотеки Paramiko

    Для работы с SSH в Python одной из наиболее популярных библиотек является Paramiko. Для установки этой библиотеки используйте следующую команду:

    Создание SSH-соединения

    Для создания SSH-соединения с удаленным сервером используйте следующий код:

    import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('example.com', username='your_username', password='your_password')

    🔒 Обратите внимание, что использование пароля для аутентификации может быть небезопасным. Лучше использовать ключи SSH для аутентификации.

    Выполнение команд на удаленном сервере

    После установления SSH-соединения можно выполнить команды на удаленном сервере. Вот пример выполнения команды ls :

    stdin, stdout, stderr = ssh.exec_command('ls') print(stdout.read().decode())

    Закрытие SSH-соединения

    После выполнения всех необходимых операций не забудьте закрыть SSH-соединение:

    Использование библиотеки Fabric

    Еще одной популярной библиотекой для работы с SSH является Fabric. Она предоставляет высокоуровневый интерфейс для работы с SSH и упрощает выполнение многих операций. Для установки Fabric используйте следующую команду:

    Создание SSH-соединения и выполнение команд с использованием Fabric

    Вот пример использования Fabric для создания SSH-соединения и выполнения команды ls на удаленном сервере:

    from fabric import Connection with Connection('example.com', user='your_username', connect_kwargs=) as conn: result = conn.run('ls') print(result.stdout.strip())

    📝 Fabric также поддерживает использование ключей SSH для аутентификации, что является более безопасным вариантом.

    Закрытие SSH-соединения в Fabric

    Когда вы используете Fabric с контекстным менеджером with , SSH-соединение автоматически закрывается при выходе из блока кода.

    Заключение

    Теперь вы знаете, как использовать Python для работы с SSH с помощью таких библиотек, как Paramiko и Fabric. Это позволит вам безопасно управлять удаленными системами и выполнять различные операции с использованием Python-скриптов. Удачного кодирования! 🐍

    Источник

    Читайте также:  DOM интерфейс
Оцените статью