我正在将交换机映射到一个名为Netbox的工具,它是一个CMDB工具。
我有一个交换机列表,例如:[US-switch01, US-switch02]
如果Netbox中不存在这些设备,我想创建那个设备。这是现在的脚本:
import pynetbox
nb = pynetbox.api(
'http://netbox.domain.com',
token='token'
)
devices = nb.dcim.devices.all() # An object of all devices in my Netbox instance
sites = nb.dcim.sites.all() # An object of all sites in my Netbox instance (EU, US for example)
def getSiteID(site):
for s in sites:
if s.name.upper() == site.upper():
return s.id # Returns the ID of the site given to is. For example US site ID is 1. EU site ID is 2.
def getDeviceID(device):
for d in devices:
if d.name.upper() == device.upper():
return d.id
if __name__ == "__main__":
switch_list = ["US-switch01", "US-switch02"]
for switch in switch_list:
print(f"Working on {switch}")
if getDeviceID(switch) is None:
siteName = switch.split('-')[0]
print(siteName, getSiteID(siteName))
当我运行脚本时,我首先测试它会发现什么:
print(siteName, getSite(siteName))
因此,上面的打印应该返回siteName
和Side ID,这就是getSite()
正在执行的操作。预期输出为:
Working on US-switch01
US 1 #site name is US and the ID in netbox is 1
Working on US-switch02
EU 2 #site name is US and the ID in netbox is 1
出于某种原因,输出是这样的:
Working on US-switch01
US 1
Working on US-switch02
US None
为什么我在第二个循环中得到None
作为返回值?
奇怪的部分
如果我使用这个列表:[US-switch01, EU-switch01]
,那么脚本工作:
Working on US-switch01
US 1
Working on EU-switch02
EU 2
因此,问题似乎是当有两个连续的交换机具有相同的站点时。为什么?我在这里错过了什么?
我怀疑您从方法.all()
中获得了生成器(而不是列表(。因此,在第二次调用中,生成器已经记住了第一次调用的位置。试着列出.all()
的结果。
devices = list(nb.dcim.devices.all())
sites = list(nb.dcim.sites.all())
这应该能解决问题。