出现异常错误“线程 Thread-1 中的异常(很可能在解释器关闭期间引发)";其中使用 Paramiko [英] Got Exception Error "Exception in thread Thread-1 (most likely raised during interpreter shutdown)" which using Paramiko

查看:60
本文介绍了出现异常错误“线程 Thread-1 中的异常(很可能在解释器关闭期间引发)";其中使用 Paramiko的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个简单的程序,通过paramiko创建一个SSH连接,然后执行一个简单的命令.但它总是抛出异常错误:-

I wrote a simple program to create an SSH Connection through paramiko and then execute a simple command. But it always throws an Exception error:-

线程 Thread-1 中的异常(最有可能在解释器期间引发关机):回溯(最近一次调用最后一次):文件/usr/lib/python2.7/threading.py",第 530 行,在 __bootstrap_inner
文件/usr/lib/python2.7/site-packages/paramiko/transport.py",行1574,在运行中:'NoneType' 对象具有没有属性错误"

Exception in thread Thread-1 (most likely raised during interpreter shutdown): Traceback (most recent call last): File "/usr/lib/python2.7/threading.py", line 530, in __bootstrap_inner
File "/usr/lib/python2.7/site-packages/paramiko/transport.py", line 1574, in run : 'NoneType' object has no attribute 'error'

我写的程序如下:-

    class Session:

      def __init__(self, ipaddr, username, password):
        self.ipaddr = ipaddr
        self.username = username
        self.password = password

        self.connect()

      def connect(self):
        try:
          time.sleep(1)
          self.ssh = paramiko.SSHClient()
          self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

          try:
            self.ssh.connect(self.ipaddr, username=self.username, password=self.password)
            time.sleep(2)
          except socket.error, e:
            print e
            self.ssh.close()
            sys.exit()

        except Exception, e:
          print e

  def executeCmd(self, cmd):
    data = ""
    try:
      stdin, stdout, stderr = self.ssh.exec_command(cmd)
      data = stdout.read()
    except SSHException, e:
      print "Error: ", e
      errorMsg = "Error: %s" %traceback.format_exc()
      print errorMsg

    return data

  def __del__(self):
    self.ssh.close()

如何解决这个异常?请帮忙.

How to resolve this exception? Please help.

谢谢

推荐答案

这是我之前找到并使用的示例代码,对我来说看起来不错.

Here is a Sample code I have found and used earlier and it looks fine to me.

import os
import tempfile
import paramiko

class Connection(object):
        """Connects and logs into the specified hostname. 
        Arguments that are not given are guessed from the environment.""" 

        def __init__(self,
         host,
         username = None,
         private_key = None,
         password = None,
         port = 22,
         ):
                self._sftp_live = False
                self._sftp = None
                if not username:
                        username = os.environ['LOGNAME']

                # Log to a temporary file.
                templog = tempfile.mkstemp('.txt', 'ssh-')[1]
                paramiko.util.log_to_file(templog)

                # Begin the SSH transport.
                self._transport = paramiko.Transport((host, port))
                self._tranport_live = True
                # Authenticate the transport.
                if password:
                # Using Password.
                        self._transport.connect(username = username, password = password)
                else:
                # Use Private Key.
                        if not private_key:
                        # Try to use default key.
                                if os.path.exists(os.path.expanduser('~/.ssh/id_rsa')):
                                        private_key = '~/.ssh/id_rsa'
                                elif os.path.exists(os.path.expanduser('~/.ssh/id_dsa')):
                                        private_key = '~/.ssh/id_dsa'
                        else:
                                raise TypeError, "You have not specified a password or key."
                        private_key_file = os.path.expanduser(private_key)
                        rsa_key = paramiko.RSAKey.from_private_key_file(private_key_file)
                        self._transport.connect(username = username, pkey = rsa_key)

        def _sftp_connect(self):
                """Establish the SFTP connection."""
                if not self._sftp_live:
                        self._sftp = paramiko.SFTPClient.from_transport(self._transport)
                        self._sftp_live = True
        def get(self, remotepath, localpath = None):
                """Copies a file between the remote host and the local host."""
                if not localpath:
                        localpath = os.path.split(remotepath)[1]
                self._sftp_connect()
                self._sftp.get(remotepath, localpath)

        def put(self, localpath, remotepath = None):
                """Copies a file between the local host and the remote host."""
                if not remotepath:
                        remotepath = os.path.split(localpath)[1]
                self._sftp_connect()
                self._sftp.put(localpath, remotepath)

        def execute(self, command):
                """Execute the given commands on a remote machine."""
                channel = self._transport.open_session()
                channel.exec_command(command)
                output = channel.makefile('rb', -1).readlines()
                if output:
                        return output
                else:
                        return channel.makefile_stderr('rb', -1).readlines()
        def close(self):
                """Closes the connection and cleans up."""
                # Close SFTP Connection.
                if self._sftp_live:
                        self._sftp.close()
                        self._sftp_live = False
        # Close the SSH Transport.
                if self._tranport_live:
                        self._transport.close()
                        self._tranport_live = False
        def __del__(self):
                """Attempt to clean up if not explicitly closed."""
                self.close()

这篇关于出现异常错误“线程 Thread-1 中的异常(很可能在解释器关闭期间引发)";其中使用 Paramiko的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆