{"id":8681,"library":"ssh2-python","title":"ssh2-python","description":"ssh2-python provides Python bindings for the `libssh2` C library, offering a low-level, high-performance interface for SSHv2 protocol operations. It is currently at version 1.2.0.post1 and is actively maintained with regular releases that include updates to embedded libraries like `libssh2` and OpenSSL, and support for newer Python versions.","status":"active","version":"1.2.0.post1","language":"en","source_language":"en","source_url":"https://github.com/ParallelSSH/ssh2-python","tags":["ssh","sftp","libssh2","remote-execution","file-transfer","networking"],"install":[{"cmd":"pip install ssh2-python","lang":"bash","label":"Install with pip"},{"cmd":"conda install -c conda-forge ssh2-python","lang":"bash","label":"Install with Conda"}],"dependencies":[{"reason":"C library binding. Embedded in binary wheels but required for source builds.","package":"libssh2","optional":true},{"reason":"Required for cryptographic operations. Embedded in binary wheels but development libraries needed for source builds.","package":"OpenSSL","optional":true},{"reason":"Required for building from source, particularly for libssh2.","package":"cmake","optional":true}],"imports":[{"symbol":"Session","correct":"from ssh2.session import Session"},{"symbol":"SFTPHandle","correct":"from ssh2.sftp_handle import SFTPHandle"},{"symbol":"Channel","correct":"from ssh2.channel import Channel"},{"symbol":"exceptions","correct":"from ssh2 import exceptions"}],"quickstart":{"code":"import socket\nimport os\nfrom ssh2.session import Session\n\nHOST = os.environ.get('SSH_HOST', 'localhost')\nPORT = int(os.environ.get('SSH_PORT', '22'))\nUSERNAME = os.environ.get('SSH_USERNAME', 'user')\nPASSWORD = os.environ.get('SSH_PASSWORD', 'password')\n\ntry:\n    # 1. Create a socket and connect\n    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n    sock.connect((HOST, PORT))\n\n    # 2. Initialize an SSH2 session\n    session = Session()\n    session.handshake(sock)\n\n    # 3. Authenticate with password\n    session.userauth_password(USERNAME, PASSWORD)\n\n    # 4. Check if authenticated\n    if not session.is_userauth_authenticated():\n        print(\"Authentication failed!\")\n        exit(1)\n\n    print(f\"Successfully authenticated to {HOST} as {USERNAME}\")\n\n    # 5. Open a channel and execute a command\n    channel = session.open_session()\n    channel.execute('echo Hello from ssh2-python; uname -a')\n\n    # 6. Read output\n    size, data = channel.read()\n    while size > 0:\n        print(data.decode('utf-8').strip())\n        size, data = channel.read()\n\n    # 7. Get exit status\n    print(f\"Command exit status: {channel.get_exit_status()}\")\n\n    # 8. Close the channel and session\n    channel.close()\n    session.disconnect()\n    sock.close()\n\nexcept exceptions.SSH2Error as e:\n    print(f\"SSH2 Error: {e}\")\nexcept socket.error as e:\n    print(f\"Socket Error: {e}\")\nexcept Exception as e:\n    print(f\"An unexpected error occurred: {e}\")\n","lang":"python","description":"This quickstart demonstrates how to establish an SSH connection, authenticate with a username and password, execute a remote command, read its output, and gracefully close the connection. Ensure `SSH_HOST`, `SSH_PORT`, `SSH_USERNAME`, and `SSH_PASSWORD` environment variables are set for actual use."},"warnings":[{"fix":"Ensure each thread initializes and manages its own `ssh2.session.Session` object.","message":"The underlying `libssh2` library does not support sharing sessions across multiple threads. While `ssh2-python` itself is thread-safe, each thread should have its own `Session` object to avoid issues.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Update code to use modern alternatives; for SCP, use `scp_recv2` and `scp_send64` if available, or higher-level libraries like `parallel-ssh` for file transfers.","message":"In version 1.2.0, several deprecated `libssh2` functions were removed from `ssh2.channel.Channel` and `ssh2.session.Session`. These include `receive_window_adjust`, `handle_extended_data`, `ignore_extended_data`, `startup`, `scp_recv`, and `scp_send`.","severity":"breaking","affected_versions":">=1.2.0"},{"fix":"For source installs, ensure `libssh2-dev` (or equivalent) and `libssl-dev` (or equivalent OpenSSL development package) are installed on your system, along with `cmake`.","message":"When installing `ssh2-python` from source, users often encounter build failures due to missing `libssh2` and `OpenSSL` development headers or `cmake`. Binary wheels provided via pip usually embed these dependencies.","severity":"gotcha","affected_versions":"All versions (source builds)"},{"fix":"Upgrade to version 1.1.1 or later. Always ensure a successful `session.handshake()` before calling `session.methods()`.","message":"Calling `ssh2.session.Session.methods()` without a valid SSH connection could lead to a segmentation fault in versions prior to 1.1.1.","severity":"gotcha","affected_versions":"<1.1.1"},{"fix":"Consider using `pip install parallel-ssh` if high-level abstractions for SSH operations are preferred over direct `libssh2` interaction.","message":"`ssh2-python` is a low-level binding to the `libssh2` C API. For most common SSH client tasks, a higher-level library like `parallel-ssh` (which uses `ssh2-python` internally) is recommended for ease of use and reduced boilerplate.","severity":"gotcha","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"On Debian/Ubuntu: `sudo apt-get install libssl-dev`. On RedHat/CentOS: `sudo yum install openssl-devel`. Ensure `cmake` is also installed. Alternatively, ensure your `pip` is up-to-date and try installing again to get a binary wheel: `pip install -U pip && pip install ssh2-python`.","cause":"The `ssh2-python` build process (via `cmake` for `libssh2`) cannot locate the OpenSSL development libraries on your system, typically when installing from a source distribution without pre-compiled wheels.","error":"Could NOT find OpenSSL, try to set the path to OpenSSL root folder in the system variable OPENSSL_ROOT_DIR (missing: OPENSSL_INCLUDE_DIR)"},{"fix":"Install `cmake` and the development packages for `libssh2` and `OpenSSL` on your system. For example, on Ubuntu: `sudo apt-get install cmake libssh2-1-dev libssl-dev`. If a binary wheel is available for your platform and Python version, upgrading `pip` might resolve it by allowing the installation of the wheel: `pip install -U pip`.","cause":"Installation from source failed, often due to missing `libssh2` development libraries, `OpenSSL` development libraries, or `cmake`.","error":"ERROR: Failed building wheel for ssh2-python` or `Command 'cmake ...' returned non-zero exit status 1."},{"fix":"Verify the paths to your public and private keys, ensure the public key is added to `~/.ssh/authorized_keys` on the remote server, and provide the correct passphrase if your private key is encrypted. Check `session.userauth_list()` to see available authentication methods on the server.","cause":"The provided public key or private key path is incorrect, the key is not authorized on the remote server, or the passphrase for the private key is wrong.","error":"ssh2.exceptions.AuthenticationError: Publickey authentication failed"},{"fix":"Verify the IP address and port are correct for your SSH server. Check firewall rules on both the client and server. Ensure the remote SSH server is running and accessible.","cause":"The remote host did not respond with a valid SSH protocol banner, or the connection dropped before the banner could be read. This can indicate that the target port is not an SSH server, a firewall issue, or an unresponsive server.","error":"ssh2.exceptions.SocketRecvError: Error reading SSH protocol banner"}]}