question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

SSHException handled but traceback is still displayed in stderr

See original GitHub issue

I am trying to handle the SSHException using the try/except block. It’s handled but the traceback is still printed out! Even if I try Exception or BaseException instead of SSHException, it’s handled but I still get the traceback displayed in the stderr.

I also tried removing Paramiko’s exception and to use the one in Netmiko (I know it’s the same as the one in paramiko)

import sys

from netmiko import ConnectHandler
from netmiko.ssh_exception import (
    NetmikoAuthenticationException,
    NetmikoTimeoutException,
    # SSHException
)
from paramiko.ssh_exception import SSHException

device = {
    "device_type": "cisco_ios",
    "ip": "192.168.1.1",
    "username": "cisco",
    "password": "cisco",
    "secret": "",
    "fast_cli": False,
}

try:
    print(f"Connecting to {device['ip']}...")
    with ConnectHandler(**device) as conn:
        print(f"Connected to {conn.host}:{conn.port}")
        facts = conn.send_command(command_string="show version", use_textfsm=True)
except (
    SSHException,
    NetmikoAuthenticationException,
    NetmikoTimeoutException,
    ConnectionResetError,
    TimeoutError,
) as e:
    print(f"Connection to {device['ip']} failed: {e}", file=sys.stderr)
else:
    print(facts)
Exception: Error reading SSH protocol banner
Traceback (most recent call last):
  File "C:\Users\username\AppData\Roaming\Python\Python39\site-packages\paramiko\transport.py", line 2211, in _check_banner
    buf = self.packetizer.readline(timeout)
  File "C:\Users\username\AppData\Roaming\Python\Python39\site-packages\paramiko\packet.py", line 380, in readline
    buf += self._read_timeout(timeout)
  File "C:\Users\username\AppData\Roaming\Python\Python39\site-packages\paramiko\packet.py", line 622, in _read_timeout
    raise socket.timeout()
socket.timeout

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\username\AppData\Roaming\Python\Python39\site-packages\paramiko\transport.py", line 2039, in run
    self._check_banner()
  File "C:\Users\username\AppData\Roaming\Python\Python39\site-packages\paramiko\transport.py", line 2215, in _check_banner
    raise SSHException(
paramiko.ssh_exception.SSHException: Error reading SSH protocol banner

I want to prevent the traceback being printed out to the stderr.

Thank you!

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
Tes3awycommented, Dec 25, 2021

@Tes3awy Let me know if the logging fix works or not.

I am pretty confident about the underlying cause of the issue being Paramiko using threading in a certain context (as I have seen this issue before).

Yes, using logging does fix the issue. What I actually did is that I added the following lines to my script

import logging

logging.basicConfig(filename="netmiko.log", level=logging.WARNING)
logger = logging.getLogger("netmiko")

However, if you don’t need a log file to be created in the cwd

import logging

logger = logging.getLogger("paramiko")  # paramiko not netmiko
logger.addHandler(logging.NullHandler())

You can also refer to this official Python documentation link for the second method.

Thanks a lot @ktbyers. Have a great day ahead!

1reaction
ktbyerscommented, Dec 25, 2021

@Tes3awy Let me know if the logging fix works or not.

I am pretty confident about the underlying cause of the issue being Paramiko using threading in a certain context (as I have seen this issue before).

Read more comments on GitHub >

github_iconTop Results From Across the Web

Is there a way to not print any traceback error message in Python
You could just finish your try and just do a general catch and then do nothing with it. import paramiko try: client =...
Read more >
Issue 13582: IDLE and pythonw.exe stderr problem
Running IDLE using python.exe will display a traceback in the console, but IDLE keeps running. However, IDLE won't even bring up a window ......
Read more >
paramiko transport problems for remote cluster - Google Groups
I never worked with paramiko, but from the traceback it seems that the Transport method is problematic. I wrote a small python script...
Read more >
Fabric - Read the Docs
Fabric is a high level Python (2.7, 3.4+) library designed to execute shell commands remotely over SSH, yielding useful.
Read more >
Changelog (1.x) — Fabric documentation
Paramiko 1.x still works like it always did; the only change to Paramiko 2 was the ... SSHException and prevent them from being...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found