31

Using the python interactive shell and openssh running locally, I keep getting an "No existing session" exception using paramiko. My code is below.

import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('localhost',username=name,password=pw)

Results in:

No handlers could be found for logger "paramiko.transport"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.6/dist-packages/paramiko-1.7.7.1-py2.6.egg/paramiko/client.py", line 332, in connect
    self._auth(username, password, pkey, key_filenames, allow_agent, look_for_keys)
  File "/usr/local/lib/python2.6/dist-packages/paramiko-1.7.7.1-py2.6.egg/paramiko/client.py", line 493, in _auth
    raise saved_exception
paramiko.SSHException: No existing session

I was able to connect previously, but had been trying to adjust this to allow for key based authorization. That failed, and since then I have not been able to connect locally. I have tried restarting openssh, and have connected to another server successfully. After searching through here, all I have found are mentions of authorization exceptions, which does not appear to be the case here.

Sam Johnson
  • 943
  • 1
  • 13
  • 19

6 Answers6

50

As you already have password you don't need to talk to agent or look for private keys stored on your machine. So try passing extra parameters allow_agent, look_for_keys:

ssh.connect('localhost',username=name,password=pw,allow_agent=False,look_for_keys=False)
Prashant Borde
  • 1,058
  • 10
  • 21
  • This fixed my issue for connecting to a Cisco ASA 5515X with Paramiko 2.1.2 and Python 3.5.2. – James Apr 06 '17 at 16:07
  • 1
    I already have these set to false but this does not solve the problem for me. `Traceback (most recent call last): File "main.py", line 190, in try_creds_and_get_stdout look_for_keys=False, allow_agent=False, auth_timeout=30` – deed02392 Jan 22 '20 at 16:51
  • This also fixed my problem. paramiko was trying to use public key auth instead of the provided username and password. Thank you – Nico Brenner Jul 06 '23 at 17:19
14

I had a spare public key with a key pass phrase in my ssh-add list. Once I removed it, I was able to execute my paramiko based script properly.

To list:

ssh-add -l

To delete all:

ssh-add -D

To re-add:

ssh-add /FULL/PATH/TO/id_rsa
Cory Ringdahl
  • 522
  • 5
  • 12
  • 1
    ^ This works. Not sure why this isn't marked as the solution yet. – bthoppae Dec 19 '17 at 22:23
  • If anyone is using SSH keys embedded in your GPG key (ssh + gpg agent), make sure you don't have non-existing / no longer used SSH keys in the `~/.gnupg/sshcontrol` file. I wasn't able to remove the SSH keys from the SSH agent with the `ssh-add -D` command. After I found out those keys were defined in the above mentioned `sshcontrol` file and removed them, everything started to work again - even for paramiko library... – Dee'Kej Nov 01 '22 at 11:09
4

Just got the same error ERROR:SSHException('No existing session',) but since it was in a clean docker container, there was no ssh-agent.

After some hours of debugging, I found a different solution: it can happen when there is a timeout during key exchange! In my case, the ssh server is a router over GSM link, which is very slow.

You can enable debug on paramiko with:

logging.getLogger("paramiko").setLevel(logging.DEBUG)

And if you see the exception between the Connected and the Switch to new keys ..., it means the timeout was during the key exchange. In this case, you have to set timeout to a bigger value! (documentation says timeout is only for TCP connect, but in fact, it is also for the whole negotiation before auth!)

Hushen
  • 427
  • 1
  • 4
  • 15
Elektordi
  • 355
  • 2
  • 8
3

https://bugs.launchpad.net/paramiko/+bug/912123

Which OS are you using? Maybe you can check your env variable: SSH_AUTH_SOCK

for "connect", it will try to use ssh agent. in agent.py

 self.conn = None
 self.keys = ()
 if ('SSH_AUTH_SOCK' in os.environ) and (sys.platform != 'win32'):
     conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
     try:
         conn.connect(os.environ['SSH_AUTH_SOCK'])
     except:
     # probably a dangling env var: the ssh agent is gone
         return
         self.conn = conn
 elif sys.platform == 'win32':
     import win_pageant
     if win_pageant.can_talk_to_agent():
         self.conn = win_pageant.PageantConnection()
 else:
     return
Rainman
  • 96
  • 4
0

In my case ,I have try use allow_agent=False,look_for_keys=False, but not work . I ssh to a 2G device, so timeout=10 is Ok, timeout=3 get" Unable to establish SSH connection: No existing session". Not timeout except.

So try timeout= a long time,if connect to a not establish ssh.

try:
     ssh = paramiko.SSHClient()               
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                             ssh.connect(ip,22,username,passwd,timeout=10,allow_agent=True,look_for_keys=True)                     
                print ('%s\tOK\n'%(ip) )
        except socket.timeout:
                print ("%s time out"%(ip))
        except paramiko.AuthenticationException:
                print("Authentication failed, please verify your credentials: %s"%(ip))
        except paramiko.SSHException as sshException:
                print("Unable to establish SSH connection: %s" %(sshException))
        except paramiko.BadHostKeyException as badHostKeyException:
                print("Unable to verify server's host key: %s" %(badHostKeyException))
        finally:
                ssh.close()
-7

Replace 'localhost' by '127.0.0.1'.

Monu
  • 1
  • 1