创建将单词与数字连接起来的词典



我正在编写一个适用于一台设备的脚本(进行自动化(。例如,我有一个设备,有一个IP,所以目前我用一个变量设置了代码。CCD_ 1。

但现在我想能够触摸大约100台设备,所以我想创建一个文件或最好的建议,例如:

Device 1 127.0.0.1
Device 2 127.0.0.2

一旦对或进行了调用,代码就会执行。我认为最好的方法是创建一个"字典文件"。有人能为我指明正确的方向吗?或者我会创建一个有两列的CSV文件?最好的推荐方法是什么?似乎有人告诉我创建一个字典文件,但我不确定这意味着什么。

我的代码目前与类似

ip1 = "127.0.0.0.1"
username = "username"
password = "password"
print("nHello, user You are connecting to ", ip, "n")
ssh_conn = paramiko.SSHClient()
ssh_conn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_conn.connect(ip, port=22, username=username,
password=password,
look_for_keys=False, allow_agent=False)

因此,为了再次澄清,我希望用一个可以存储近10-100个IP地址的文件来取代ip1 =,并根据"设备名称"来执行代码。

我知道一个例子如下:

released = {
"iphone": 2007,
"iphone 3G": 2008,
"iphone 3GS": 2009,
"iphone 4": 2010,
"iphone 4S": 2011,
"iphone 5": 2012
}
for item in released:
if "iphone 5" in released:
print("Key found")
break
else:
print("No keys found")

但是,如果我要添加100个键值,我该怎么办?

编辑

我接受这个想法,

with open('inventory.txt', 'r') as f:
answer = {}
for line in f:
line = line.split()
if not line:
continue
answer[line[0]] = line[1:]
id = "1299"
for i in answer[store_num]:
host = i
ssh = ConnectHandler(device_type='cisco_ios', host=host, username='asd', password='asdsssasd')
print("nConnection successful with: ", host, "n")
out = ssh.send_command(command)
print(out)

但我在连接任何东西时都会出错。

我引用你的问题:

似乎有人告诉我创建一个字典文件,但我不确定这意味着什么。

请参阅此。

在你的场景中,它会这样:

ip_adresses = {
"Device 1": "127.0.0.1",
"Device 2": "127.0.0.2"
}

然后你会这样运行它:

for device, ip in ip_adresses.items():
print("This is " + device + ". IP Address: " + ip)

最终代码:

device_you_are_using = "Device 2"
ip_addresses = {
"Device 1": "127.0.0.1",
"Device 2": "127.0.0.2"
}
for device, ip in ip_addresses.items():
if device_you_are_using == device:
print("This is " + device + ". IP Address: " + ip)

您可以使用CSV文件来存储所有IP及其相应的主机名,如

Device 1,127.0.0.1
Device 2,127.0.0.2

然后,您可以使用csv模块中内置的Python将这些数据读取到字典中,如

import csv
info = {}
with open("master.csv", "r") as file:
reader = csv.reader(file)
for item in reader:
info[item[0]] = item[1]

然后你可以问用户,要连接哪个设备名称?

device = input("Device name: ")
ip = info.get(device, None) #--> get the ip address from the info dict

如果IP不是None,则可以连接用户。

最终使用它是为了使用文本文件而不是CSV。

with open('inventory.txt', 'r') as f:
answer = {}
for line in f:
line = line.split()
if not line:
continue
answer[line[0]] = line[1:]
data_number = input("INFO: Enter Device Number: ")
for i in answer[data_number]:
host = i

最新更新