【问题标题】:How to resolve Attribute error in SSH connection using Python?如何使用 Python 解决 SSH 连接中的属性错误?
【发布时间】:2020-12-15 11:35:11
【问题描述】:

我正在尝试下面的代码 sn-p 在后台会话中使用 ssh 运行命令。但它导致“chan = ssh_transport.open_session()属性错误:'NoneType'对象没有属性'open_session'” 任何解决此错误的建议都会非常有帮助,谢谢。

def background(self, cmd, working_directory):
            if hasattr(self, "bkg_sessions") is False:
                self.bkg_sessions = {}
    
            ssh_transport = self.paramiko_client.get_transport()
            chan = ssh_transport.open_session()
            chan.invoke_shell()
            if working_directory:
                chan.send(f'cd {working_directory}\n'.encode())
                time.sleep(1)
            chan.send(f'{cmd}\n'.encode())
    
            self.bkg_sessions[chan] = {}
            return chan

【问题讨论】:

  • 根据报错信息,ssh_transp应该是None。你是否创建了paramiko_client的实例?而且我们也不知道这个变量是指什么。
  • 请添加您提到的self.paramiko_client
  • @HarshanaSerasinghe, self.paramiko_client = 无,已分配给无

标签: python python-3.x ssh serial-port


【解决方案1】:

这是因为您已将 self.paramiko_client 设置为 None。您需要将其设置为 SSHClient() 才能使其工作。

例子:

from paramiko.client import SSHClient

class ExampleClass:
    def __init__(self):
        self.paramiko_client = SSHClient()

    def background(self, cmd, working_directory):
        if hasattr(self, "bkg_sessions") is False:
            self.bkg_sessions = {}

        ssh_transport = self.paramiko_client.get_transport()
        chan = ssh_transport.open_session()
        chan.invoke_shell()
        if working_directory:
            chan.send(f'cd {working_directory}\n'.encode())
            time.sleep(1)
        chan.send(f'{cmd}\n'.encode())

        self.bkg_sessions[chan] = {}
        return chan


【讨论】:

  • 还是没有解决错误,导致同样的错误 chan = ssh_transport.open_session(), 'NoneType' object has no attribute 'open_session'
  • 请将完整代码粘贴到您的问题中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-14
  • 1970-01-01
  • 2013-11-18
  • 2023-04-02
  • 2021-01-23
  • 1970-01-01
  • 2019-09-14
相关资源
最近更新 更多