The leading native Python SSHv2 protocol library.

Overview

Paramiko

https://travis-ci.org/paramiko/paramiko.svg?branch=master
Paramiko: Python SSH module
Copyright: Copyright (c) 2009 Robey Pointer <[email protected]>
Copyright: Copyright (c) 2020 Jeff Forcier <[email protected]>
License: LGPL
Homepage: http://www.paramiko.org/
API docs: http://docs.paramiko.org
Development: https://github.com/paramiko/paramiko

What

"Paramiko" is a combination of the Esperanto words for "paranoid" and "friend". It's a module for Python 2.7/3.4+ that implements the SSH2 protocol for secure (encrypted and authenticated) connections to remote machines. Unlike SSL (aka TLS), SSH2 protocol does not require hierarchical certificates signed by a powerful central authority. You may know SSH2 as the protocol that replaced Telnet and rsh for secure access to remote shells, but the protocol also includes the ability to open arbitrary channels to remote services across the encrypted tunnel (this is how SFTP works, for example).

It is written entirely in Python (though it depends on third-party C wrappers for low level crypto; these are often available precompiled) and is released under the GNU Lesser General Public License (LGPL).

The package and its API is fairly well documented in the docs folder that should have come with this repository.

Installation

For most users, the recommended method to install is via pip:

pip install paramiko

For more detailed instructions, see the Installing page on the main Paramiko website.

Portability Issues

Paramiko primarily supports POSIX platforms with standard OpenSSH implementations, and is most frequently tested on Linux and OS X. Windows is supported as well, though it may not be as straightforward.

Bugs & Support

Bug Reports: Github
Mailing List: [email protected] (see the LibreList website for usage details).
IRC: #paramiko on Freenode

Kerberos Support

Paramiko ships with optional Kerberos/GSSAPI support; for info on the extra dependencies for this, see the GSS-API section on the main Paramiko website.

Demo

Several demo scripts come with Paramiko to demonstrate how to use it. Probably the simplest demo is this:

import base64
import paramiko
key = paramiko.RSAKey(data=base64.b64decode(b'AAA...'))
client = paramiko.SSHClient()
client.get_host_keys().add('ssh.example.com', 'ssh-rsa', key)
client.connect('ssh.example.com', username='strongbad', password='thecheat')
stdin, stdout, stderr = client.exec_command('ls')
for line in stdout:
    print('... ' + line.strip('\n'))
client.close()

This prints out the results of executing ls on a remote server. The host key b'AAA...' should of course be replaced by the actual base64 encoding of the host key. If you skip host key verification, the connection is not secure!

The following example scripts (in demos/) get progressively more detailed:

demo_simple.py: Calls invoke_shell() and emulates a terminal/TTY through which you can execute commands interactively on a remote server. Think of it as a poor man's SSH command-line client.
demo.py: Same as demo_simple.py, but allows you to authenticate using a private key, attempts to use an SSH agent if present, and uses the long form of some of the API calls.
forward.py: Command-line script to set up port-forwarding across an SSH transport.
demo_sftp.py: Opens an SFTP session and does a few simple file operations.
demo_server.py: An SSH server that listens on port 2200 and accepts a login for 'robey' (password 'foo'), and pretends to be a BBS. Meant to be a very simple demo of writing an SSH server.
demo_keygen.py: A key generator similar to OpenSSH ssh-keygen(1) program with Paramiko keys generation and progress functions.

Use

The demo scripts are probably the best example of how to use this package. Also a lot of documentation is generated by Sphinx autodoc, in the doc/ folder.

There are also unit tests here:

$ pip install -r dev-requirements.txt
$ pytest

Which will verify that most of the core components are working correctly.

To test Kerberos/GSSAPI, you need a Kerberos environment. On UNIX you can use the package k5test to setup a Kerberos environment on the fly:

$ pip install -r dev-requirements.txt
$ pip install k5test gssapi pyasn1
$ pytest
Comments
  • Switched everything to use cryptography instead of pyCrypto

    Switched everything to use cryptography instead of pyCrypto

    Motivation:

    • Adds PyPy support
    • Performance improvement
    • OpenSSL and friends are better audited than PyCrypto
    • Easier windows install flow (Cryptography provides statically linked wheels on Windows)

    This PR is basically complete on the code side, of course it can always use more review :-)

    Tests all pass locally (tested with PyPy!)

    Still needs some docs work, and to figure out how to do this with the version numbers so people's stuff doesn't suddenly get broken.

    opened by alex 132
  • Python 3 support

    Python 3 support

    I have Paramiko running on Python 3 at https://github.com/goertzenator/paramiko

    All unit tests, except for sftp, pass. Needs documentation updates for the many str -> bytes changes.

    Looking for advice on what to do with this. Adding a python 3 branch to paramiko would have a lot of complications...

    opened by goertzenator 122
  • client support for RSA ssh certificates

    client support for RSA ssh certificates

    I have extended the RSAKey class to support the [email protected] type of certificate authentication in a new RSACert class. A test case was added to test_pkey.py to test loading an RSA certificate (a signed public key that's the same one given in the tests already). I think this class should be a reasonable example from which DSS and ECDSA certificate classes can also be created.

    Let me know what you think!

    Jason

    Ready for review Feature 
    opened by jasonrig 58
  • fix SSHClient/Transport leak, remove unneeded references

    fix SSHClient/Transport leak, remove unneeded references

    Fix to #949 - thanks @agronick for discovering and debugging the problem.

    Caused by a fix in #891. But, it's a matter of choice and policy.

    This should also be back-ported to 1.17.z

    (This issue description has been updated.)


    The back-reference from Transport to SSHClient was added because the SSHClient had a destructor that would close the Transport, and some users did not want the Transport closed when the SSHClient was garbage collected.

    The SSHClient destructor was not a normal destructor, it was implemented with the ResourceManager singleton. This sometimes prevented the GC cycle detector from freeing the SSHClient and Transport even after the Transport Thread stopped running.

    We can simplify these problems by just getting rid of the ResourceManager, and the back-reference. Transports cannot be garbage-collected while their Thread is running, .close() must be called (on the SSHClient or the Transport).

    opened by ploxiln 57
  • Add rsa-sha2-256 and rsa-sha2-512 algorithms

    Add rsa-sha2-256 and rsa-sha2-512 algorithms

    These are specified in RFC 8332 (https://tools.ietf.org/html/rfc8332) and proposed by recent OpenSSH versions as a drop-in replacement for the deprecated ssh-rsa algorithm. The advantage is that the same RSA keys can be used without relying on the SHA-1 digest now considered insecure.

    Keys Feature 
    opened by krisztian-kovacs 56
  • Patches to support sha256 based hmac and kexgex

    Patches to support sha256 based hmac and kexgex

    This is based on forks by EtiennePerot and ashb who did most of the work. Changing the remaining sha1 references in transport.py let's me connect to hardened openssh servers again.

    Ready for review High priority Keys Feature 
    opened by zamiam69 55
  • Merged-to-master Python 3 branch

    Merged-to-master Python 3 branch

    How I got here:

    $ git checkout scottkmaxwell/py3-support-without-py25
    $ python test.py # verified
    $ git checkout -b python3 master
    $ git merge scottkmaxwell/py3-support-without-py25 -Xignore-space-change
    

    Then poking at all the conflicts, some of which required the following (given that I shuffled some files around in #256, this made it a lot easier to figure out what the incoming branch had actually changed):

    $ git show master:paramiko/<module>.py > paramiko/<module>.py
    $ vim paramiko/<module>.py
    $ git diff 28d78e4e6a33d2e23af196db632e6eeda4167e24 scottkmaxwell/py3-support-without-py25 -- paramiko/<module>.py
    <manually apply changes as needed>
    

    And now trying to ensure that the test suite passes again.

    opened by bitprophet 48
  • PyPI download url is not working, upload to PyPI instead?

    PyPI download url is not working, upload to PyPI instead?

    Hi Robey,

    Your download url to lag.net is not currently working. Would you mind uploading the 1.7.6 zip file to paramiko's pypi page instead of using the download url that points to lag.net?

    ~Justin

    opened by jtriley 48
  • Smartcard pkcs11 support

    Smartcard pkcs11 support

    This adds pkcs11 support to enable using paramiko with smartcards. I have a forked version of Ansible that uses this feature and its working great.

    I have tested on python 2.7 and python 3.6.2

    Multithreading Example:

    import paramiko
    from multiprocessing import Queue
    from threading import Thread
    
    pkcs11provider="/usr/local/lib/opensc-pkcs11.so"
    smartcard_pin="123456"
    
    def do_it(q):
        session = q.get()
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect("HOSTNAME", username="USERNAME", pkcs11_session=session)
        stdin, stdout, stderr = ssh.exec_command("uname -a")
        for line in stdout:
            print(line)
    
    q = Queue()
    session = paramiko.pkcs11.open_session(pkcs11provider, smartcard_pin)
    mythread = Thread(target=do_it, args=(q,))
    q.put(session)
    mythread.start()
    mythread.join()
    paramiko.pkcs11.close_session(session)
    

    Basic Example:

    import paramiko
    
    pkcs11provider="/usr/local/lib/opensc-pkcs11.so"
    smartcard_pin="123456"
    
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    session = paramiko.pkcs11.open_session(pkcs11provider, smartcard_pin)
    ssh.connect("HOSTNAME", username="USERNAME", pkcs11_session=session)
    paramiko.pkcs11.close_session(session)
    stdin, stdout, stderr = ssh.exec_command("uname -a")
    for line in stdout:
        print(line)
    
    Feature Needs changelog/docs 
    opened by thedavidwhiteside 41
  • Exception in thread

    Exception in thread

    Exception in thread Thread-12 (most likely raised during interpreter shutdown):
    Traceback (most recent call last):
      File "/usr/local/lib/python2.5/threading.py", line 486, in __bootstrap_inner
      File "build/bdist.freebsd-8.2-RELEASE-i386/egg/paramiko/transport.py", line 1574, in run
    <type 'exceptions.AttributeError'>: 'NoneType' object has no attribute 'error'
    Exception in thread Thread-13 (most likely raised during interpreter shutdown):
    Traceback (most recent call last):
      File "/usr/local/lib/python2.5/threading.py", line 486, in __bootstrap_inner
      File "build/bdist.freebsd-8.2-RELEASE-i386/egg/paramiko/transport.py", line 1574, in run
    <type 'exceptions.AttributeError'>: 'NoneType' object has no attribute 'error'
    Exception in thread Thread-9 (most likely raised during interpreter shutdown):
    Traceback (most recent call last):
      File "/usr/local/lib/python2.5/threading.py", line 486, in __bootstrap_inner
      File "build/bdist.freebsd-8.2-RELEASE-i386/egg/paramiko/transport.py", line 1574, in run
    <type 'exceptions.AttributeError'>: 'NoneType' object has no attribute 'error'
    Exception in thread Thread-8 (most likely raised during interpreter shutdown):
    Traceback (most recent call last):
      File "/usr/local/lib/python2.5/threading.py", line 486, in __bootstrap_inner
      File "build/bdist.freebsd-8.2-RELEASE-i386/egg/paramiko/transport.py", line 1574, in run
    <type 'exceptions.AttributeError'>: 'NoneType' object has no attribute 'error'
    Exception in thread Thread-3 (most likely raised during interpreter shutdown):
    Traceback (most recent call last):
      File "/usr/local/lib/python2.5/threading.py", line 486, in __bootstrap_inner
      File "build/bdist.freebsd-8.2-RELEASE-i386/egg/paramiko/transport.py", line 1574, in run
    <type 'exceptions.AttributeError'>: 'NoneType' object has no attribute 'error'
    
    Needs investigation Bug 
    opened by jumping 41
  • Race condition(s) around handshake timeout functionality

    Race condition(s) around handshake timeout functionality

    Edited to add: this ticket began life under assumption the issues were Travis-specific, but it seems more likely that Travis and/or the test suite are just exacerbating underlying, real problems. Specifically, a race condition shown in test_L_handshake_timeout.

    The other issue, centering on test_3_multiple_key_files, seems unrelated & received at least some workarounds/fixes mid-ticket, and should be considered closed for now.

    Original description follows.


    These were most often seen under Python 3.2, which has been nixed, but they pop up on other interpreters as well (for example https://travis-ci.org/paramiko/paramiko/builds/89238099 hit them 3 times in one build!) and it seems to be getting worse.

    The problems appear to be most easily replicated under Python 3 but we've had at least a few confirmed reports of it occurring on Python 2 as well (though as per below comments I've been unable to reproduce it locally - only on Travis).

    The specific examples that appear to occur are:

    • test_L_handshake_timeout fails with AssertionError: EOFError not raised by connect: https://travis-ci.org/paramiko/paramiko/jobs/89548222#L505
    • No output has been received in the last 10 minutes hangs/kills, often (always? needs lots of scanning) while running test_3_multiple_key_files (test_client.SSHClientTest): https://travis-ci.org/paramiko/paramiko/jobs/89548214#L464
    Needs investigation High priority Support 
    opened by bitprophet 40
  • On timeout, exception is raised without a message

    On timeout, exception is raised without a message

    When timeout exception is being raises from channel.py with raise socket.timeout() , it does not contain any message, it would be great to include at least some information there.

    Exception handling 
    opened by HonzaCech 1
  • update pins to support python 3.10, add to test matrix

    update pins to support python 3.10, add to test matrix

    This is a minimally invasive fix to get py310 testing going. py311 will require https://github.com/pyinvoke/invoke/commit/406a45e854f6e8df4aa0de01e3b731fea2b1f1ec to be in the next invoke release, sorry @bitprophet 😄

    Needs policy decision 
    opened by reaperhulk 1
  • Paramiko cannot connect to tamte server

    Paramiko cannot connect to tamte server

    I'm trying to ssh to Tmate, a popular terminal sharing server. Via ssh, the process is easy: ssh {user_name}/{sess_name}@sgp1.tmate.io

    But Paramiko doesn't seem to be able to do that. I get those types of errors:

    IncompatiblePeer: Incompatible ssh server (no acceptable compression) [] [] ('none',)
    
    or 
    
    SSHException: Error reading SSH protocol banner
    
    

    Is this possible at all? What is missing here?

    opened by thisismygitrepo 1
  • Paramiko not connecting on Solaris 11

    Paramiko not connecting on Solaris 11

    On Linux & Solaris 10, the following code works but if it is Solaris 11, it throws the following error message paramiko.ssh_exception.AuthenticationException: Authentication failed.. The credentials/authentication details are correct. The host, username and password are all correct but for some reason it complains about Authentication failure. I know that Solaris 11 has much more beefed up security. Is there any thing else I need to add to my code to get this to work? (more details below):

    ` def setup_remote_gateway_client_connection(self, gateway_host, gateway_username, gateway_password, client_host, client_username, client_password, gateway_port=22, client_port=22): self.gateway_host=paramiko.SSHClient() self.gateway_host.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.gateway_host.connect(gateway_host, username=gateway_username, password=gateway_password )

        gateway_transport = self.gateway_host.get_transport()
        src_addr = (gateway_host, gateway_port)
        dest_addr = (client_host, client_port)
        gateway_channel = gateway_transport.open_channel("direct-tcpip", dest_addr, src_addr)
    
        client_host=paramiko.SSHClient()
        client_host.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client_host.connect(client_host, username=client_username, password=client_password, sock=gateway_channel)
    
        stdin, stdout, stderr = client_host.exec_command('ls -la')
        for line in stdout.read().split(b'\n'):
          print(str(line))
    
        stdin, stdout, stderr = client_host.exec_command('hostname')
        for line in stdout.read().split(b'\n'):
          print(str(line))
    
        client_host.close()
        self.gateway_host.close()`
    

    Upon execution, I get the following:

    `fixture.py:28: in setup_remote_gateway_client_connection client_host.connect(client_host, username=client_username, password=client_password, sock=gateway_channel) /usr/local/lib/python3.10/site-packages/paramiko/client.py:450: in connect self._auth( /usr/local/lib/python3.10/site-packages/paramiko/client.py:781: in _auth raise saved_exception /usr/local/lib/python3.10/site-packages/paramiko/client.py:768: in _auth self._transport.auth_password(username, password) /usr/local/lib/python3.10/site-packages/paramiko/transport.py:1564: in auth_password return self.auth_handler.wait_for_response(my_event)


    self = <paramiko.auth_handler.AuthHandler object at 0x107691ae0> event = <threading.Event object at 0x107691a20>

    def wait_for_response(self, event):
        max_ts = None
        if self.transport.auth_timeout is not None:
            max_ts = time.time() + self.transport.auth_timeout
        while True:
            event.wait(0.1)
            if not self.transport.is_active():
                e = self.transport.get_exception()
                if (e is None) or issubclass(e.__class__, EOFError):
                    e = AuthenticationException("Authentication failed.")
                raise e
            if event.is_set():
                break
            if max_ts is not None and max_ts <= time.time():
                raise AuthenticationException("Authentication timeout.")
    
        if not self.is_authenticated():
            e = self.transport.get_exception()
            if e is None:
                e = AuthenticationException("Authentication failed.")
            # this is horrible.  Python Exception isn't yet descended from
            # object, so type(e) won't work. :(
            if issubclass(e.__class__, PartialAuthentication):
                return e.allowed_types
    
          raise e
    

    E paramiko.ssh_exception.AuthenticationException: Authentication failed.

    /usr/local/lib/python3.10/site-packages/paramiko/auth_handler.py:259: AuthenticationException`

    Support 
    opened by asarkisian 7
  • NoValidConnectionsError not raised when socket.getaddrinfo() fails as a direct cause of client.connect()

    NoValidConnectionsError not raised when socket.getaddrinfo() fails as a direct cause of client.connect()

    Documentation for the NoValidConnectionsError states that:

    This exception class wraps multiple “real” underlying connection errors, all of which represent failed connection attempts. Because these errors are not guaranteed to all be of the same error type (i.e. different errno, socket.error subclass, message, etc) we expose a single unified error message and a None errno so that instances of this class match most normal handling of socket.error objects.

    IOW it wraps all various kinds of socket errors. However, this doesn't include calls to getaddrinfo in the _self._families_and_addresses method. IMO issuing getaddr is an inherent part of establishing connection and hence socket.gaierror exceptions should be wrapped like any other exception coming from socket.socket. This forces library users to handle both types of errors not just NoValidConnectionsError which is IMO in contradiction to the docs linked above since from client's POV both exceptions came from the same library (paramiko in this case).

    To provide a bit more background, I'm using paramiko to test whether a fresh VM I created is ready to be connected to over SSH. It takes a little while until the VM reaches a state where the network is up and the VM got a DHCP lease, so naturally getaddr must fail, but that is expected, it doesn't change anything on the fact, that gaierror caused as part of client.connect should not be wrapped with NoValidConnectionsError.

    Exception handling Needs policy decision 
    opened by eskultety 0
A Python library for the Docker Engine API

Docker SDK for Python A Python library for the Docker Engine API. It lets you do anything the docker command does, but from within Python apps – run c

Docker 6.1k Dec 31, 2022
Official Python client library for kubernetes

Kubernetes Python Client Python client for the kubernetes API. Installation From source: git clone --recursive https://github.com/kubernetes-client/py

Kubernetes Clients 5.4k Jan 2, 2023
Asynchronous parallel SSH client library.

parallel-ssh Asynchronous parallel SSH client library. Run SSH commands over many - hundreds/hundreds of thousands - number of servers asynchronously

null 1.1k Dec 31, 2022
CI repo for building Skia as a shared library

Automated Skia builds This repo is dedicated to building Skia binaries for use in Skija. Prebuilt binaries Prebuilt binaries can be found in releases.

Humble UI 20 Jan 6, 2023
A job launching library for docker, EC2, GCP, etc.

doodad A library for packaging dependencies and launching scripts (with a focus on python) on different platforms using Docker. Currently supported pl

Justin Fu 55 Aug 27, 2022
Python IMDB Docker - A docker tutorial to containerize a python script.

Python_IMDB_Docker A docker tutorial to containerize a python script. Build the docker in the current directory: docker build -t python-imdb . Run the

Sarthak Babbar 1 Dec 30, 2021
Honcho: a python clone of Foreman. For managing Procfile-based applications.

___ ___ ___ ___ ___ ___ /\__\ /\ \ /\__\ /\ \ /\__\ /\

Nick Stenning 1.5k Jan 3, 2023
Cross-platform lib for process and system monitoring in Python

Home Install Documentation Download Forum Blog Funding What's new Summary psutil (process and system utilities) is a cross-platform library for retrie

Giampaolo Rodola 9k Jan 2, 2023
Python job scheduling for humans.

schedule Python job scheduling for humans. Run Python functions (or any other callable) periodically using a friendly syntax. A simple to use API for

Dan Bader 10.4k Jan 2, 2023
A cron monitoring tool written in Python & Django

Healthchecks Healthchecks is a cron job monitoring service. It listens for HTTP requests and email messages ("pings") from your cron jobs and schedule

Healthchecks 5.8k Jan 2, 2023
Python utility function to communicate with a subprocess using iterables: for when data is too big to fit in memory and has to be streamed

iterable-subprocess Python utility function to communicate with a subprocess using iterables: for when data is too big to fit in memory and has to be

Department for International Trade 5 Jul 10, 2022
Linux, Jenkins, AWS, SRE, Prometheus, Docker, Python, Ansible, Git, Kubernetes, Terraform, OpenStack, SQL, NoSQL, Azure, GCP, DNS, Elastic, Network, Virtualization. DevOps Interview Questions

Linux, Jenkins, AWS, SRE, Prometheus, Docker, Python, Ansible, Git, Kubernetes, Terraform, OpenStack, SQL, NoSQL, Azure, GCP, DNS, Elastic, Network, Virtualization. DevOps Interview Questions

Arie Bregman 35.1k Jan 2, 2023
Push Container Image To Docker Registry In Python

push-container-image-to-docker-registry 概要 push-container-image-to-docker-registry は、エッジコンピューティング環境において、特定のエッジ端末上の Private Docker Registry に特定のコンテナイメー

Latona, Inc. 3 Nov 4, 2021
Get Response Of Container Deployment Kube with python

get-response-of-container-deployment-kube 概要 get-response-of-container-deployment-kube は、例えばエッジコンピューティング環境のコンテナデプロイメントシステムにおいて、デプロイ元の端末がデプロイ先のコンテナデプロイ

Latona, Inc. 3 Nov 5, 2021
Containerize a python web application

containerize a python web application introduction this document is part of GDSC at the university of bahrain you don't need to follow along, fell fre

abdullah mosibah 1 Oct 19, 2021
A simple python application for running a CI pipeline locally This app currently supports GitLab CI scripts

?? Simple Local CI Runner ?? A simple python application for running a CI pipeline locally This app currently supports GitLab CI scripts ⚙️ Setup Inst

Tom Stowe 0 Jan 11, 2022
A Python Implementation for Git for learning

A pure Python implementation for Git based on Buliding Git

shidenggui 42 Jul 13, 2022
A repository containing a short tutorial for Docker (with Python).

Docker Tutorial for IFT 6758 Lab In this repository, we examine the advtanges of virtualization, what Docker is and how we can deploy simple programs

Arka Mukherjee 0 Dec 14, 2021
Simple ssh overlay for easy, remote server management written in Python GTK with paramiko

Simple "ssh" overlay for easy, remote server management written in Python GTK with paramiko

kłapouch 3 May 1, 2022