0

我正在尝试执行以下代码,但我收到“close_session()”函数的这些错误。如何解决?我是 python 新手。

我正在学习 netconf 并尝试使用 python netconf 配置路由器。我已经导入了库,看来我已经正确完成了所有操作。

from ncclient import manager
from pprint import pprint
import xmltodict
import xml.dom.minidom
from router_info import router



print(router["host"])
print(router["port"])
print(router["username"])
print(router["password"])


netconf_filter = open("/Users/ljames/netconf/netconf-filter.xsd").read()

with manager.connect(host=router["host"], port=router["port"], username=router["username"], password=router["password"], hostkey_verify=False) as m:
   
      interface_netconf = m.get(netconf_filter)
     #   xmlDom = xml.dom.minidom.parseString(str(interface_netconf))
     #   print(xmlDom.toprettyxml(indent=''))
     #   print('*' * 25 + 'Break' + '*' * 25)

interface_python = xmltodict.parse(interface_netconf.xml)["rpc-reply"]["data"]
# pprint(interface_python)
name = interface_python['interfaces']['interface']['name']['#text']
print(name)

config = interface_python["interfaces"]["interface"]
op_state = interface_python["interfaces-state"]["interface"]

print("Start")
print(f"Name: {config['name']['#text']}")
print(f"Description: {config['description']}")
print(f"packets In {op_state['statistics']['in-unicast-pkts']}")
m.close_session() 

以下是错误消息:

mac@user % /Library/Frameworks/Python.framework/Versions/3.8/bin/python3 /Users/ljames/netconf/netconf-5.py
ios-xe-mgmt-latest.cisco.com
10000
developer
C1sco12345
GigabitEthernet2
Start
Name: GigabitEthernet2
Description: YJ-interface
packets In 146
Traceback (most recent call last):
  File "/Users/ljames/netconf/netconf-5.py", line 36, in <module>
    m.close_session() 
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/ncclient/manager.py", line 231, in execute
    return cls(self._session,
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/ncclient/operations/session.py", line 28, in request
    return self._request(new_ele("close-session"))
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/ncclient/operations/rpc.py", line 327, in _request
    self._session.send(req)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/ncclient/transport/session.py", line 167, in send
    raise TransportError('Not connected to NETCONF server')
ncclient.transport.errors.TransportError: Not connected to NETCONF server
4

2 回答 2

1

我有完全相同的问题,这是我的结论:

问题可能是您在块m.close_session()外使用。with事实上,你根本不应该close_sessionwith块内使用,因为清理是自动执行的。只需逐行调试,看看当你退出with块时,m.connected设置为false。

于 2020-10-15T07:23:14.400 回答
0

检查您的 ncclient 管理器的主机和密码

于 2021-10-12T12:18:22.750 回答