早上好球員循環通過CSV文件分期目的
這一次我沒有與特定代碼的問題,而是一個「我是在正確的軌道上」的問題來了。
我想寫一個腳本來暫存網絡設備。我會得到一個有兩列的CVS列表:主機名+ HW類型,類似於:
Hostname,Type
TestAP-1,AP250
TestAP-2,AP250
TestAP-3,AP250
TestSW-1,SW100
TestSW-2,SW100
TestAP-4,AP250
真正的列表顯然會更長。
我的想法到現在爲止是解析調用硬件類型腳本獲取主機名列表的參數。然後連接到硬件(IP地址將始終是相同的默認IP或通過串行控制檯),向硬件發送一些命令(設置主機名,系統日誌服務器IP等),再次從機器讀取值(使用show命令)並將結果寫入另一個csv文件。
類似:
staging.py AP250
get a list with all hostnames where the HW Type is AP250
loop
connect (ssh or serial) to the hardware
commands:
set hostname 'hostname'
set syslog ip (fixed ip address, the same for all devices)
set whatever need to be set as well
the do a show on these settings and parse the value
write the value to a output csv file (create or append)
我在正確的軌道上?現在,我的腳本如下所示:
import csv
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('Type', type=str,
help='REQUIRED: Please enter the Hardware Type (AP250, SW100, etc)')
args = parser.parse_args()
Manager = "manager.domain.com"
MACAddress = "aa:bb:cc:dd:ee:ff"
with open("input.csv", 'r', newline='') as f:
reader = csv.DictReader(f)
for row in reader:
if row['Type'] == args.Type:
print(row['Hostname']) # This will later on be replaced by some paramiko code
h = (row['Hostname'])
t = (row['Type'])
outdict = {}
print (outdict)
"""
with open('output.csv', 'w', newline='') as o:
writer = csv.DictWriter(o, delimiter=',', fieldnames=["Hostname", "Type", "Hivemanager", "MACAddress"])
writer.writeheader()
newrow = (h + "," + t + "," + Manager + "," + MACAddress)
writer.writerow(newrow)
#writer.writerows(['Hostname'], ['Type'], Manager)
print (open('output.csv', 'r').read())
"""
input("Press Enter to continue")
如果我不能確定:
- 正在與字典這樣做的正確方法?
- 正在遍歷主機名列表並以正確的方式執行該循環中的所有操作?
我不希望完整的工作腳本作爲答案。而不是那些,我可以得到一些想法的一些提示或鏈接將會很好。
非常感謝。