Giter Club home page Giter Club logo

paramiko's Introduction

PyPI - Package Version PyPI - Python Version PyPI - License CircleCI Codecov

Welcome to Paramiko!

Paramiko is a pure-Python1 (3.6+) implementation of the SSHv2 protocol 2, providing both client and server functionality. It provides the foundation for the high-level SSH library Fabric, which is what we recommend you use for common client use-cases such as running remote shell commands or transferring files.

Direct use of Paramiko itself is only intended for users who need advanced/low-level primitives or want to run an in-Python sshd.

For installation information, changelogs, FAQs and similar, please visit our main project website; for API details, see the versioned docs. Additionally, the project maintainer keeps a roadmap on his personal site.


  1. Paramiko relies on cryptography for crypto functionality, which makes use of C and Rust extensions but has many precompiled options available. See our installation page for details.

  2. OpenSSH's RFC specification page is a fantastic resource and collection of links that we won't bother replicating here: https://www.openssh.com/specs.html

    OpenSSH itself also happens to be our primary reference implementation: when in doubt, we consult how they do things, unless there are good reasons not to. There are always some gaps, but we do our best to reconcile them when possible.

paramiko's People

Contributors

akx avatar alanyee avatar alex avatar alexdotc avatar bitprophet avatar bskinn avatar bz2 avatar dorianpula avatar edgsousa avatar glasserc avatar h4ck3rm1k3 avatar jaraco avatar jaredhobbs avatar jbrand42 avatar kalledk avatar lndbrg avatar mgedmin avatar mwilliamson avatar offbyone avatar pghmcfc avatar ploxiln avatar radssh avatar reaperhulk avatar rectalogic avatar scottkmaxwell avatar sunweaver avatar tomerfiliba avatar yarikoptic avatar ykalchevskiy avatar zamiam69 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

paramiko's Issues

Code assumes all socket exceptions have two args.

I had to make the following change at line ~1571 in transport.py to handle the case of a socket timeout exception, where e.args is not 2 items long. (Added str(e.args) and a check for len of e.args)

        except socket.error, e:
            if type(e.args) is tuple and len(e.args) == 2:
                emsg = '%s (%d)' % (e.args[1], e.args[0])
            else:
                emsg = str(e.args)
            self._log(ERROR, 'Socket exception: ' + emsg)
            self.saved_exception = e

Now if only I can work out why this is happening 0.1 seconds after I connect...

2011-06-15 13:38:24,625 transport.py._log[1383]: DEBUG    starting thread (client mode): 0x43aa710L
2011-06-15 13:38:24,711 transport.py._log[1383]: INFO     Connected (version 2.0, client Sun_SSH_1.5)
2011-06-15 13:38:24,811 transport.py._log[1383]: ERROR    Socket exception: ('timed out',)

unlinking a Channel doesn't garbage collect it

While ChannelMap takes care to use a weak dict, the channel itself has a reference to the transport, and it seems that's enough to prevent it from being GC'ed. (I've stumbled upon this with the help of zope.testrunner that somehow prints notifications about uncollected stuff).

Setting self.transport to None in _unlink solves that, like so:

--- channel.py.orig 2012-03-29 08:37:59.291296451 +0200
+++ channel.py  2012-03-29 08:38:03.655296228 +0200
@@ -1127,6 +1127,7 @@
         try:
             self._set_closed()
             self.transport._unlink_channel(self.chanid)
+            self.transport = None
         finally:
             self.lock.release()
 

channels don't work unless a reference to SSHClient is explicitly kept

Using an instance of Channel received from somewhere without a reference to SSHClient being explicitly kept (to prevent it from being garbage collected) sometimes gives unexpected results. For instance, a call to exec_command() raises an exception about the channel being closed, while recv_exit_status() just returns -1.

Here's a synthetic test case.

import paramiko

def exec_remote_command(command, host, username=None, password=None):
    channel = _exec_remote_command(command, host, username=username, password=password)
    return channel.recv_exit_status()

def _exec_remote_command(command, host, username=None, password=None):
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
    client.connect(host, username=username, password=password)
    channel = client.get_transport().open_session()
    channel.exec_command(command)
    return channel

if __name__ == '__main__':
    print exec_remote_command('ls', '127.0.0.1') # prints -1

Fail to re-use SSH session when connecting to Cisco C2960 switcher

Here's my code:

#!/usr/bin/python26

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect('1.2.3.4',username='xxx', password='xxxx',allow_agent=False)
stdin, stdout, stderr = ssh.exec_command('show version')
stdin, stdout, stderr = ssh.exec_command('show mac brief')

result in:

Traceback (most recent call last):
  File "./test.py", line 10, in <module>
    stdin, stdout, stderr = ssh.exec_command('show mac brief')
  File "/usr/lib/python2.6/site-packages/paramiko/client.py", line 363, in exec_command
    chan = self._transport.open_session()
  File "/usr/lib/python2.6/site-packages/paramiko/transport.py", line 658, in open_session
    return self.open_channel('session')
  File "/usr/lib/python2.6/site-packages/paramiko/transport.py", line 746, in open_channel
    raise e
EOFError

athentication failure for doamin users or local users using sshclient.connect(host,username,password)

Hi Below is the code, tel me why PARENT\puser (puser is joined to PARENT.com domain)
fails to authenticate, if i try to authenticate using the below show code. exeption thrown is: raise saved_exception.

if i try to authenticate the same PARENT\puser indipendently authentication succeds successfly,

could any one tell me the ideal way of authenticating users?

import paramiko
import time
import os
import sys

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('10.10.60.68',username ='root',password ='span1234',timeout='10')
transport = ssh.get_transport()
chan = ssh.invoke_shell()
time.sleep(2)
print chan.recv(9999)
ssh.close()
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('10.10.60.68',username ='PARENT\puser',password ='parent@1234',timeout='10')
chan = ssh.invoke_shell()
time.sleep(2)
print chan.recv(9999)
ssh.close()

thanks in advance....

transport randomly errors out on fresh Ubuntu 11.04 installation

$ cat test.py

from fabric.api import run, settings, hide
with settings(hide('everything')):
    print run('egrep sudo /etc/group').succeeded

I get error like this:

$ python test.py
No hosts found. Please specify (single) host string for connection: localhost
[localhost] Login password: 
True
Exception in thread Thread-1 (most likely raised during interpreter shutdown):
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 552, in __bootstrap_inner
  File "/home/swaroop/local/virtualenvs/default/lib/python2.7/site-packages/paramiko/transport.py", line 1574, in run
<type 'exceptions.AttributeError'>: 'NoneType' object has no attribute 'error'

socket.timeout exception badly handled by Transport.run()

You can find the detail of the troubleshooting here :

http://forum.magiksys.net/viewtopic.php?f=5&t=82

In transport.py at line 1581, you are rewriting an error message

    except socket.error, e:
        if type(e.args) is tuple:
            emsg = '%s (%d)' % (e.args[1], e.args[0])  < < < <  This one
        else:
            emsg = e.args
        self._log(ERROR, 'Socket exception: ' + emsg)
        self.saved_exception = e

but e.args is an empty tuple when exception is a socket.timeout() !

maybe you should add this code just before

except socket.timeout, e:
        emsg = 'socket.timeout'
        self._log(ERROR, 'Socket exception: timeout')
        self.saved_exception = e

Alain

Big speed problem using paramiko.SFTPClient

I am using paramiko to send big files between two RHEL5.5 servers and I am seeing a BIG speed gap between paramilo and scp (or sftp).

Here is the code I run in python

t = paramiko.Transport((hostname, 22)) t.connect(username=username, password=password, hostkey=hostkey) sftp = paramiko.SFTPClient.from_transport(t) sftp.put(in_file, out_file)

With this code I get about 6MB/s on a gigabyte connexion.

I also tried using compression

t.use_compression()

I was able to get to 11MB/s

On the same system, scp will reach at least 50MB/s !

Is there something I could tweak to get better speed results?

set_missing_host_key_policy crashes

I tried to use the example in the code samples, to deal with unknown hosts:

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.WarningPolicy)
client.connect("192.168.2.26")

But it fails:

Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/pymodules/python2.6/paramiko/client.py", line 311, in connect
self._policy.missing_host_key(self, server_hostkey_name, server_key)
TypeError: unbound method missing_host_key() must be called with WarningPolicy instance as first argument (got SSHClient instance instead)

This is on Debian "squeeze", the stable version.

Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)
[GCC 4.4.5] on linux2

Paramiko 1.7.6

Can't enable compression via SSHClient

I'd like to enable compression (transport.use_compression), but there's no way in client to enable it after the transport is created, and before start_client is called :-(

Please tag the 1.7.7.1 release

Robey,

First of all, thanks for putting writing and managing such a useful codebase.

Would you mind tagging the 1.7.7.1 so that it's easy to jump right to it instead of having to search the commit log?

Thanks a bunch,
wt

SFTPFile prefetch assumes response order matches requests

SFTPFile._async_response() assumes that the responses arrive in the same order in which the requests were sent, using a simple queue (self._prefetch_reads). The result is that if SFTPFile is used with an SFTP server which does not guarantee that the response order matches the request order, it gets the ordering of prefetched files wrong.

The SFTP v3 specification is very clear that response order is not required not match request order; in section 6.1 of the -02 draft:

There are no restrictions on the order in which responses to
outstanding requests are delivered to the client, except that the
server must ensure fairness in the sense that processing of no
request will be indefinitely delayed even if the client is sending
other requests so that there are multiple outstanding requests all
the time.

There is a restriction that requests have to be processed in order, i.e. a read following a write must reflet the effect of the write if they overlap, but that's not directly relevant to read-only prefetching.

IMHO the best way to fix this would be to have _async_request pass a closure rather than the SFTPFile object, allowing each request to carry the offset/length details with it, and also thereby decoupling SFTPClient from (this aspect of) SFTPFile's interface.

The reason I noticed is of course that I have a reordering-capable server, though currently reordering is partially disabled, precisely to avoid tickling this bug in Paramiko.

Unexpected local key search behavior

I sent this to the mailing list several months ago, but I never got a response.

I'm experiencing trouble trying to get a paramiko.SSHClient to connect without trying to access my private key.

I realize that there is a parameter, look_for_keys, which is True by default. I am setting it to False and am still receiving prompts to decrypt my private key. If GNOME has already placed the key on its keyring for the current session, paramiko will access the key and presumably not use it, because I am able to successfully make connections to my local machine in addition to remote SSH-enabled servers.

Here is code that reproduces my problem without fail on two (very similar, but separate) machines:

import getpass
import paramiko
username = 'brian'
password = getpass.getpass()
host = 'localhost'
port = 22
ssh_client = paramiko.SSHClient()
ssh_client.load_system_host_keys()
ssh_client.set_missing_host_key_policy(paramiko.WarningPolicy())
ssh_client.connect(host, port, username, password, look_for_keys=False)

After the final line in the code above, I am prompted to decrypt my key if GNOME doesn't already have it. When I cancel the prompt, I receive the following traceback from my IPython console:

SSHException                              Traceback (most recent call last)

/home/brian/<ipython console> in <module>()

/usr/local/lib/python2.6/dist-packages/paramiko/client.pyc in connect(self, hostname, port, username, password, pkey, key_filename, timeout, allow_agent, look_for_keys)
    325         else:
    326             key_filenames = key_filename
--> 327         self._auth(username, password, pkey, key_filenames, allow_agent, look_for_keys)
    328
    329     def close(self):

/usr/local/lib/python2.6/dist-packages/paramiko/client.pyc in _auth(self, username, password, pkey, key_filenames, allow_agent, look_for_keys)
    479         # if we got an auth-failed exception earlier, re-raise it

    480         if saved_exception is not None:
--> 481             raise saved_exception
    482         raise SSHException('No authentication methods available')
    483

SSHException: No existing session

I began looking for the problem but didn't delve too deeply. In paramiko/client.py, on line 478 (http://github.com/robey/paramiko/blob/master/paramiko/client.py#L478), there seems to be a function call which eventually leads to some function call that I assume causes the private key to be solicited.

Both of the machines that I mentioned always reproduce this problem are running Ubuntu 10.04 LTS (Lucid Lynx) x86_64 with Python 2.6.5, the version from the Ubuntu repositories. I have not tested it under any other environments. Paramiko is 1.7.6.

Am I doing something incorrectly, or is this a bug? Like I said, it does connect, but probably not with the SSH key, because none of the machines that I've connected to with paramiko used that form of authentication.

With further testing, I've discovered that public key authentication is used even if look_for_keys is False; it is not just opened and ignored. I set up another computer to only accept authentication over SSH via keys, and ssh_client.connect(host, port, username, password, look_for_keys=False), when the private key file was unlocked, successfully connected to the host.

Not working on python 3

Paramiko is not working in python 3.
Pycrypto dep is working on python 3.

It seem that Paramiko need only a 2to3 and some str / bytearray tweeks to work on python 3.

Authentication fails with more than one key in agent

It seems that when I have more than one key held by the agent, any authentication that would require anything but the first key would fail. The trace is copied down below. I also added some dedug info at the packet level. Could it be that there should not be a [service-request] following the [userauth-failure] with the wrong key, but directly a new [userauth-request]?
Thanks,
-Gellule

DEBUG:paramiko.transport:starting thread (client mode): 0x2514550L
INFO:paramiko.transport:Connected (version 2.0, client 3.2.9.1)
Write packet [kexinit], length 406
Read packet [ignore], length 5
Read packet [kexinit], length 461
DEBUG:paramiko.transport:kex algos:['diffie-hellman-group1-sha1'] server key:['ssh-dss'] client encrypt:['aes128-cbc', '3des-cbc', 'twofish128-cbc', 'cast128-cbc', 'twofish-cbc', 'blowfish-cbc', 'aes192-cbc', 'aes256-cbc', 'twofish192-cbc', 'twofish256-cbc', 'arcfour'] server encrypt:['aes128-cbc', '3des-cbc', 'twofish128-cbc', 'cast128-cbc', 'twofish-cbc', 'blowfish-cbc', 'aes192-cbc', 'aes256-cbc', 'twofish192-cbc', 'twofish256-cbc', 'arcfour'] client mac:['hmac-sha1', 'hmac-sha1-96', 'hmac-md5', 'hmac-md5-96'] server mac:['hmac-sha1', 'hmac-sha1-96', 'hmac-md5', 'hmac-md5-96'] client compress:['none', 'zlib'] server compress:['none', 'zlib'] client lang:[''] server lang:[''] kex follows?False
DEBUG:paramiko.transport:Ciphers agreed: local=aes128-cbc, remote=aes128-cbc
DEBUG:paramiko.transport:using kex diffie-hellman-group1-sha1; server key type ssh-dss; cipher: local aes128-cbc, remote aes128-cbc; mac: local hmac-sha1, remote hmac-sha1; compression: local none, remote none
Write packet [kex30], length 133
Read packet [ignore], length 5
Read packet [kex31], length 630
Write packet [newkeys], length 1
Read packet [ignore], length 5
Read packet [newkeys], length 1
DEBUG:paramiko.transport:Switch to new keys ...
DEBUG:paramiko.transport:Trying SSH agent key fbd3bc799a422891ffc58f9212539a13
Write packet [service-request], length 17
Read packet [ignore], length 5
Read packet [service-accept], length 17
DEBUG:paramiko.transport:userauth is OK
Write packet [userauth-request], length 550
Read packet [ignore], length 1005
Read packet [userauth-failure], length 24
INFO:paramiko.transport:Authentication (publickey) failed.
DEBUG:paramiko.transport:Trying SSH agent key 939d6a49f527e8f0c53e9ec509ff913a
Write packet [service-request], length 17
Read packet [ignore], length 5
Read packet [disconnect], length 54
INFO:paramiko.transport:Disconnect (code 2): Protocol error: packet 5 in interactive
paramiko.AuthenticationException: Authentication failed.

Lag.net is down

so I can't use pip to download and install the python egg for paramiko.

I imagine lots of people are running into this as well.

[LibCrypto 2.1.0] RandomPool_DeprecationWarning

Hello,
I upgraded yesterday to pycrypto 2.1.0 (to get rid of two warnings) and I get a new warning from pycrypto about Paramiko is using the deprecated RandomPool operation.

OS : Windows 32 bits (sadly), python 2.6
and latest stable release of paramiko

C:\Python26\lib\site-packages\Crypto\Util\randpool.py:40: RandomPool_DeprecationWarning: This application uses RandomPool, which is BROKEN in older releases. See http://www.pycrypto.org/randpool-broken
RandomPool_DeprecationWarning)

Thanks for your help, and keep up the good work !

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'

Channel.request_x11() either doesn't work or needs a good demo

A number of users report not being able to get Channel.request_x11() to work correctly in situations where ssh -X works fine. We need to figure out whether this functionality is currently broken, or if it simply requires additional non-obvious code in order to work (in which case we need to improve the docs/demos.)

Originally submitted issue from @fatboy92:

Hi all,
first of all: thanks for that module, I feel it gives me more control, than pexpect.

Now, here is my question:
I am trying to use the channel method request_x11 (and yes I looked at the example programs). Just like when you do ssh -X.

When I do, the process is started as expected but no window is displayed. Same behaviour with invoke_shell(), the display variable is set correctly (localhost:10 or similar), but again no window is displayed. I checked with wmctrl, it isn't there, not even outside the visible area of the screen.

Any thoughts?

Many thanks for all answers.
H. Witsch

paramiko does not try all available address families

Forwarded from https://bugs.launchpad.net/paramiko/+bug/579530:

See failure at http://babune.ladeuil.net:24842/job/selftest-lucid/54/testReport/bzrlib.tests.test_transport/TestSSHConnections/test_bzr_connect_to_bzr_ssh/

The situation is a server that is listening on an IPv4 address only, but that host/interface has both IPv4 and IPv6 connectivity, and getaddinfo returns the IPv6 result before the IPv4. bzr asks paramiko to connect to the right (host,port) pair by calling paramiko.Transport.

What should happen is that paramiko should successfully connect to the server.

What does happen is that paramiko attempts to connect via IPv6, that fails with connection refused, and paramiko stops there with a connection refused error.

doesn't fall back on ipv4 route when there is no ipv6 route

I can't connect to a ssh server that has an AAAA record from a client that doesn't have an ipv6 route:

Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

import paramiko
client=paramiko.SSHClient()
client.connect(hostname='ssh.alwaysdata.com')
Traceback (most recent call last):
File "", line 1, in
File "/Library/Python/2.6/site-packages/paramiko/client.py", line 296, in connect
sock.connect(addr)
File "", line 1, in connect
socket.error: [Errno 65] No route to host

I would expect paramiko to use IPv4 in this case. Connecting with os x's default ssh client works as expected.

pageant doesnt work by default on Windows

Pageant can be considered the standard key agent on Windows so it would make sense for paramiko to try to use it for authentication.

While I observed that paramiko has support for pageant, this is not enabled by default.

Also, I was unable to find any example on how to enable pageant support on paramiko,

The documentation from http://www.lag.net/paramiko/docs/ contains only a simple reference to pageant but no example on how to use it.

empty key_filename causes exception in SSHClient.connect

I am not sure if this can be regarded as an IPython bug or Paramiko's but here's the problem

My Setup

Win 7 x64

ipython==0.12.1
paramiko==1.7.7.2

Issue

During an ssh connection, IPython default behavior is to set the path to the private key to an empty string.
In paramiko/client.py/SSHClient.connect method, there are provisions when the key_filename is None which is to try SSH agent, look in ~/.ssh/ and so forth.
When key_filename is an empty string, an exception is raised however as follows:

Traceback (most recent call last):
  File "C:\Python27\lib\site-packages\IPython\frontend\consoleapp.py", line 289, in init_ssh
    newports = tunnel_to_kernel(info, self.sshserver, self.sshkey)
  File "C:\Python27\lib\site-packages\IPython\lib\kernel.py", line 245, in tunnel_to_kernel
    if tunnel.try_passwordless_ssh(sshserver, sshkey):
  File "C:\Python27\lib\site-packages\IPython\external\ssh\tunnel.py", line 87, in try_passwordless_ssh
    return f(server, keyfile)
  File "C:\Python27\lib\site-packages\IPython\external\ssh\tunnel.py", line 123, in _try_passwordless_paramiko
    look_for_keys=True)
  File "C:\Python27\lib\site-packages\paramiko\client.py", line 334, in connect
    self._auth(username, password, pkey, key_filenames, allow_agent, look_for_keys)
  File "C:\Python27\lib\site-packages\paramiko\client.py", line 438, in _auth
    key = pkey_class.from_private_key_file(key_filename, password)
  File "C:\Python27\lib\site-packages\paramiko\pkey.py", line 198, in from_private_key_file
    key = cls(filename=filename, password=password)
  File "C:\Python27\lib\site-packages\paramiko\rsakey.py", line 51, in __init__
    self._from_private_key_file(filename, password)
  File "C:\Python27\lib\site-packages\paramiko\rsakey.py", line 163, in _from_private_key_file
    data = self._read_private_key_file('RSA', filename, password)
  File "C:\Python27\lib\site-packages\paramiko\pkey.py", line 279, in _read_private_key_file
    f = open(filename, 'r')
IOError: [Errno 22] invalid mode ('r') or filename: u''

I have currently edited SSHClient.connect in the following way to handle empty strings:

        if key_filename is None or len(key_filename) == 0 :
            key_filenames = []

I am not sure if that's the best way to do it though

User Interaction after sending a command

I am tryin to login to a brocade switch using jaramiko.
After the command is executed, the switch prompts the user to enter [y/n] to go ahead. I am not able to do this.
After sending the command, my script hangs there.

Plz suggest me a solution to do this

Warning "RandomPool_DeprecationWarning"

When I import paramiko, I get:

/usr/lib/python2.6/dist-packages/Crypto/Util/randpool.py:40: RandomPool_DeprecationWarning: This application uses RandomPool, which is BROKEN in older releases. See http://www.pycrypto.org/randpool-broken
RandomPool_DeprecationWarning)

This is on Debian "squeeze", the stable version.

Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)
[GCC 4.4.5] on linux2

Paramiko 1.7.6

forward.py demo can't handle users without shell on the remote machine

Essentially, it is not possible to emulate the functionality of a plain port forwarding connection, the equivalent of using the -N option with the standard openssh client or plink. If the user has an empty shell assigned to it in "/etc/passwd" (for example /usr/bin/nologin in place of /bin/bash) the connection will open, but each request will fail with the error "ChannelException('Administratively prohibited',)". Another user with an assigned shell will connect fine on the same machine with the same options.

Paramiko 1.7.7.1+PyCrypto 2.3 : AssertionError: PID check failed. RNG must be re-initialized after fork(). Hint: Try Random.atfork()

With Python 2.7 on Redhat 4 32 bit.
After having compiled I ran test.py without problem but my application fails with :
File "prova.py", line 7, in
ftpssh = sshMdn.Connection(host=ip_ad, username=ut)
File "/usr/local/lib/python2.7/site-packages/mdnlib/sshMdn.py", line 64, in init
self._transport.connect(username = username, pkey = rsa_key)
File "build/bdist.linux-i686/egg/paramiko/transport.py", line 1007, in connect
File "build/bdist.linux-i686/egg/paramiko/transport.py", line 1230, in auth_publickey
File "build/bdist.linux-i686/egg/paramiko/auth_handler.py", line 82, in auth_publickey
File "build/bdist.linux-i686/egg/paramiko/auth_handler.py", line 124, in _request_auth
File "build/bdist.linux-i686/egg/paramiko/transport.py", line 1406, in _send_message
File "build/bdist.linux-i686/egg/paramiko/packet.py", line 297, in send_message
File "build/bdist.linux-i686/egg/paramiko/packet.py", line 476, in _build_packet
File "/usr/local/lib/python2.7/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 185, in read
return self._singleton.read(bytes)
File "/usr/local/lib/python2.7/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 161, in read
return _UserFriendlyRNG.read(self, bytes)
File "/usr/local/lib/python2.7/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 120, in read
self._check_pid()
File "/usr/local/lib/python2.7/site-packages/Crypto/Random/_UserFriendlyRNG.py", line 136, in _check_pid
raise AssertionError("PID check failed. RNG must be re-initialized after fork(). Hint: Try Random.atfork()")
AssertionError: PID check failed. RNG must be re-initialized after fork(). Hint: Try Random.atfork()

I saw this problem discussed in some posts but I read that v, 1.7.7.1 should have fixed it....it seems it didn't ?
Thank you

Getting no traceback on CentOS in python2.4

Getting the below error on import. on CentOS in python2.4.
The installation but I am at a lost to debug this error. Any idea how to debug this?

import paramiko
ERROR: Internal Python error in the inspect module.
Below is the traceback from this internal error.

Traceback (most recent call last):
File "/usr/lib/python2.4/site-packages/IPython/ultraTB.py", line 603, in text
records = _fixed_getinnerframes(etb, context,self.tb_offset)
File "/usr/lib/python2.4/site-packages/IPython/ultraTB.py", line 230, in _fixed_getinnerframes
records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
File "/usr/lib64/python2.4/inspect.py", line 811, in getinnerframes
framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
File "/usr/lib64/python2.4/inspect.py", line 775, in getframeinfo
lines, lnum = findsource(frame)
File "/usr/lib64/python2.4/inspect.py", line 437, in findsource
if pat.match(lines[lnum]): break
IndexError: list index out of range

Unfortunately, your original traceback can not be constructed.

Confusing error message when trying to verify unknown host key types

Paramiko only recognises ssh-rsa and ssh-dss keys when reading known_hosts. However, newer versions of openssh use additional key types which Paramiko silently ignores, resulting in very confusing missing host key errors which occur when attempting to connect with Paramiko, even though the same connection via the command line ssh works perfectly.

From the openssh documentation:

For protocol version 2 the keytype is “ecdsa-sha2-nistp256”, “ecdsa-sha2-nistp384”, “ecdsa-sha2-nistp521”, “ssh-dss” or “ssh-rsa”

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...

Create a new mailing list

Candidates for a mailing list or list-like website (ideally one with good email integration):

  • LibreList
    • Highest contender
    • Maybe somewhat confusing for newbies re: posting new mails
    • Some concerns re: stability
  • Google Groups
    • Serious concerns about longevity
  • Python.org mailman
    • Not sure it's a good fit
    • Almost definitely stable
  • Moot.it
    • Only worthwhile if have guarantees of longevity (probably not) & very easy to sign up for / get emails from
  • Discourse
    • Would require self-hosting so probably not

[from @bitprophet]: Create a LibreList mailing list for Paramiko & publicize it:

  • Here
  • My personal twitter
  • My personal blog (meh)
  • Fabric's twitter

Was originally: README file refers to broken mailing list URL

http://www.lag.net/mailman/listinfo/paramiko produces a 404 error.

Issues with the parsing of known_hosts file

I noticed that the parser that handles the records of known_hosts file is rather simplistic and is unable to handle more general cases used by "real" ssh. In particular the problem is with the routine HostKeyEntry.from_line() that has been that way since 2006 (looking at Git history). Some limitations include:

(1) inability to handle multiple spaces as field separator -- they should be valid
(2) apparently, hashed keys are not supported (yet)

I would like to submit a few patches to address these issues.

To address (1) it is actually as simple as replacing this statement:

fields = line.split(' ')

to:

fields = line.split()

(currently on line 55 of hostkeys.py). I wonder why:

"Lines are expected to not have leading or trailing whitespace."

Wirawan

Too difficult to change ciphers, set ssh options in high-level API

The high-level API, while convenient for simple uses, does not scale well into increased complexity. For example, many ssh options that one might set via "ssh -o" are not available. A common and important ssh tuning parameter is which cipher one wants to use. Setting to arcfour within a fairly secure context can be an effective way to reduce CPU load. As far as I've been able to tell, the only way to do this via paramiko's SSHClient class is to subclass and copy and paste the definition of connect, then modify the Transport object before connection. Eg: copy connect and insert
t.get_security_options().ciphers = ('arcfour128',)
at paramiko/client.py:298.

An inexhaustive list of ways this could be handled more maintainably could include:

  • initialisation or modification of the Transport is handled by a function that could be independently overridden in a subclass
  • initialisation of modification the Transport is handled by a callback (possibly via a some registration mechanism)
  • some sort of configuration dict to be passed around that would allow objects such as Transports to initialise themselves in a generally configurable way

PyCrypto dependancy

Hi,

The module claim that he is written entirely with Python : "it is written entirely in python (no C or platform-dependent code). It s true that module is written with Python, but it depends on a c plateform dependent third party module.

Maybe adding precision to the description will be better (or better, avoid pycripto use :) )

SFTP File Handler doesn't raise Exception if the SSH Client or SFTP session are out of scope

Hi,

I had some Python code with two functions, let's call them alice() and bob().

alice() would call bob(), and bob() would open up a SSH session, and return a SFTP file handler to alice().

#!/usr/bin/env python2
import paramiko

def get_instances_cfg():
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect('some_server', username='victorhooi')
    sftp = client.open_sftp()
    file = sftp.file('/tmp/instances.cfg')

    # This would print out the file fine.
    # for row in file:
    #    print(row)

    return file
    #sftp.close()
    #client.close()

def get_root_directory():
    instances_cfg = get_instances_cfg()

    # The following would print out nothing.
    for row in instances_cfg:
        print(row)

if __name__ == '__main__':
    get_root_directory()

I could iterate over the file handler fine in bob(), however in alice() it seemed to silently fail, printing nothing.

Anyhow, somebody pointed out to me that it was probably a scoping issue - when I left bob(), client and sftp would go out of scope, even though I returned file.

I made client, sftp and sftp global, and this then worked fine - I could iterate over file in alice().

My question is - I assume this is by design, right? The SFTP file handler won't work if the client doesn't exist in your current scope?

Should there be some kind of error message or exception raised if you try to access a SFTP file handler that doesn't have the original SSHClient or SFTP session around?

In my case, it seemed to be a valid SFTP file handler, but it just didn't contain any rows.

Cheers,
Victor

Do not raise socket.timeout in a non-blocking channel

Actually the method Channel.recv raises socket.timeout if the channel is on non-blocking mode. I think it:

  • On non-blocking mode:
    • Should return '' (empty string) if no data received;
    • Should return the data received independent on self.timeout.
  • On blocking-mode:
    • Should raises socket.timeout if self.timeout is set and greater than zero;
    • Should raises IOError if socket/channel is closed;
    • Should return the data if any.

The code:

try:
    out = self.in_buffer.read(nbytes, self.timeout)
except PipeTimeout, e:
    raise socket.timeout()

on file paramiko/channel.py, should be changed to something like this:

try:
    out = self.in_buffer.read(nbytes, self.timeout)
except PipeTimeout, e:
    if self.blocking and self.timeout:
        raise socket.timeout('Timeout when reading blocking channel.')

Why is the server unknown?

There is a machine where I log in daily from the command line. So, I'm certain its key is in the OpenSSH files. But Paramiko does not find it:

client = paramiko.SSHClient()
client.load_system_host_keys()
client.load_host_keys("/home/stephane/.ssh/known_hosts")

client.connect("www.example.com, 3442)
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/pymodules/python2.6/paramiko/client.py", line 311, in connect
self._policy.missing_host_key(self, server_hostkey_name, server_key)
File "/usr/lib/pymodules/python2.6/paramiko/client.py", line 85, in missing_host_key
raise SSHException('Unknown server %s' % hostname)
paramiko.SSHException: Unknown server [www.example.com]:3442

It happens with every host I tried.

This is on Debian "squeeze", the stable version.

Python 2.6.6 (r266:84292, Dec 27 2010, 00:02:40)
[GCC 4.4.5] on linux2

Paramiko 1.7.6

algorithm for locating known_hosts differs from the "real" ssh

the "real" ssh uses the .ssh directory that is located under the "home" which is determined from getpwuid(get[e?]uid()). On the other hand, paramico apparently consults the $HOME/.ssh/known_hosts. And if you changed $HOME (which I did in the cronjob script) paramico does not find the known_hosts file.

By the way, the message that is issued in this case is rather confusing:

ssh connection to x failed: Unknown server x

which looks as if it could not resolve the server name. It would be much better if it said "No public key known for server x" or something like that.

Related duplicity bug: https://bugs.launchpad.net/duplicity/+bug/965017

Transfer fails at 1GB: rekey window too small, hard-coded

First off, thanks for the great work with paramiko.

At 1GB of data transferred over sftp, paramiko initiates a ssh rekey request and then sets a limit on the number of packets exchanged before the remote side answers the rekey request. This limit is hard-coded to 20. If you have fat, long pipes, it's pretty easy to consistently exceed this threshold. As a consequence in this context, paramiko is not able to transfer files larger than 1GB in size. OpenSSH does not exhibit this behavior. I manually patched the source to change the 20 to something that was more reasonable based on our RTT and bandwidth. The exceptions immediately went away.

  • What does openssh do in this situation?
  • If doing what openssh does in not suitable or convenient, can this be made a configurable parameter, accessible from the higher-level API (ie SSHClient)?

Daemonizing after importing paramiko breaks the random number generator

Hi,

I'm writing a daemon which uses Paramiko to do SFTP transfers. I do the daemonization according to http://code.activestate.com/recipes/278731/ . When I try to connect to the server I get a "Bad file descriptor" exception from the Random.atfork() call in paramiko.transport.start_client.

The cause seems to be that when importing paramiko it creates a random number generator in paramiko.common, which opens a file descriptor to /dev/urandom (I'm on Linux). The daemonization recipe closes all open file descriptors in the child process, so when atfork() is called the /dev/urandom descriptor is not valid anymore.

I'm working around it by importing paramiko after the daemonization.

Is this an issue with Paramiko/PyCrypto or just with my code organisation?

Kind regards,
Raf

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.