获取IndentationError:应为缩进块
我故意尝试使用错误的凭据连接到设备,以测试身份验证异常。如果我删除了try块,并确保代码块是用正确的语法编写的enter code here,那么它运行得很好。这意味着程序会崩溃,就像它想要的那样。但是,如果我使用了正确的用户名和密码,它就可以正常工作。只有当我执行try块时,我才会得到上面的错误。
from napalm import get_network_driver
from getpass import getpass
from netmiko import NetMikoAuthenticationException
username = input('username')
password = getpass('password')
driver = get_network_driver('ios')
with open('devices.txt','r') as switch_db:
for switch in switch_db:
#set up to connect to a switch from switch_db
try:
with driver(switch, username, password) as device:
except NetMikoAuthenticationException:
print('Authentication Error!')发布于 2019-08-24 23:27:05
原来,我使用的with context管理器行被认为是一个空的try块,所以我更改了代码,以采取一个操作来设置连接调用的变量。当然,这是可行的,但您必须记住在您的代码中关闭连接。
from pprint import pprint
from napalm import get_network_driver
from getpass import getpass
from netmiko import NetMikoAuthenticationException
import json
username = input('username')
password = getpass('password')
driver = get_network_driver('ios')
with open('devices.txt','r') as switch_db:
for switch in switch_db:
#set up to connect to a switch from switch_db
try:
device = driver(switch, username, password)
device.open()
except NetMikoAuthenticationException:
print('Authentication Error!')
username = input('username')
password = getpass('password')
device = driver(switch, username, password)
device.open()
else:
print('line after try block')
pprint(device.get_interfaces())
device.close()
print('switch is closed')'发布于 2019-08-25 02:01:07
在这里回复,所以也可以看到这一点。
在try/except块中有一个空的with构造函数。这是可行的,并针对思科DevNet沙盒进行了测试。
#!/usr/bin/env python3
from napalm import get_network_driver
from getpass import getpass
from netmiko import NetMikoAuthenticationException
from napalm.base.exceptions import ConnectionException
from pprint import pprint
username = input('username: ')
password = getpass('password: ')
driver = get_network_driver('ios')
with open('devices.txt','r') as switch_db:
for switch in switch_db:
#set up to connect to a switch from switch_db
try:
with driver(switch, username, password, optional_args={'port': 8181}) as device:
pprint(device.get_facts())
except NetMikoAuthenticationException:
print('Authentication Error!')
except ConnectionException:
print(f'Could not connect to {switch}')https://stackoverflow.com/questions/57634847
复制相似问题