从Excel中的列中读取数据

时间:2017-06-01 18:22:40

标签: python python-2.7 loops

我正在使用python脚本从Excel文件中的列读取数据,并使用该数据在Cisco交换机上执行命令。

例如,我有2列以下

Switch        MAC
aaa.com      mac.aaa.000
bbb.com      mac.bbb.000
ccc.com      mac.ccc.000
.....        .....

python现在将切换aaa并将mac mac.aaa.000的端口安全性设置为粘性。

这是命令:

switchport port-security **<mac-address>** sticky

现在我已完成登录部分,我可以执行命令。我需要帮助从文件中读取2列的部分,并知道登录以在相应列上切换和粘贴macaaa。

以下是我在交换机上登录和执行命令的方法:

term_len = "term len 0"
# Need a loop here that gets switchname from coulmn A and assign it to variable host and also corresponding MAC address and assigns it to variable MAC
host = ""
MAC = ""
session = telnetlib.Telnet(host)
session.write(cred.username + '\n')
session.read_until('Password: ')
session.write(cred.password + '\n')
session.read_until('>')
session.write(cred.en + '\n')
session.read_until('Password: ')
session.write(cred.en_pass + '\n')
session.read_until('#')
session.write(term_len + '\n')
session.write(switchport port-security **MAC** sticky + '\n')

请帮忙。循环将从文件读取所有开关和MAC并执行粘滞命令。

3 个答案:

答案 0 :(得分:1)

我一直在使用openpyxl将excel数据读入脚本。

    from openpyxl import *
    from tkinter.filedialog import askopenfilename,askdirectory,asksaveasfilename
    #file selector using tkinter
    file = askopenfilename()
    #load the workbook
    wb=load_workbook(file)
    #get sheets
    sheets = wb.sheetnames
    #select sheet to use by index from sheetnames
    ws=wb[sheets[0]]
    #loop through the rows of worksheet and store in list
    switchMAC=[]
    for r in range (ws.max_row):
        row=[]
        for c in range(ws.max_column):
            row.append(ws.cell(row=r+1,column=c+1).value)
        switchMAC.append(row)

从这里开始,您可以获得一个列表(switchMAC),您可以循环传递命令

    for r in switchMac:
        host=r[0]
        MAC=r[1]
        #add the rest of your code for each host within the loop

答案 1 :(得分:1)

您可以使用xlrd,此脚本允许您将Excel数据表转换为字典列表:

import xlrd

workbook = xlrd.open_workbook('foo.xls')
workbook = xlrd.open_workbook('foo.xls', on_demand = True)
worksheet = workbook.sheet_by_index(0)
first_row = [] # The row where we stock the name of the column
for col in range(worksheet.ncols):
    first_row.append( worksheet.cell_value(0,col) )
# transform the workbook to a list of dictionaries
data =[]
for row in range(1, worksheet.nrows):
    elm = {}
    for col in range(worksheet.ncols):
        elm[first_row[col]]=worksheet.cell_value(row,col)
    data.append(elm)
print data

您也可以使用Pandas

from pandas import *
xls = ExcelFile('foo.xls')
df = xls.parse(xls.sheet_names[0])
print df.to_dict()

答案 2 :(得分:1)

您可以使用此代码从Excel文件中读取数据。

import os
import datetime
import sys
import re
import openpyxl
import uuid
from openpyxl import load_workbook

class ExcelDictSmall(dict):
    '''
    Dictionary with all Sheet Names as key, value is a List of Rows each item in a Row List is a List of Cells
    '''
    def __init__(self,dir,fname):
        fullFname = os.path.join(dir,fname)
        wb = load_workbook(filename=fullFname, read_only=True)
        allSheets= wb.get_sheet_names()
        for sheet in allSheets:
            sheetList = []
            rowlist=[]
            for row in wb[sheet].rows:
                for cell in row:
                    rowlist.append(cell.value)
                sheetList.append(rowlist)
                rowlist=[]
            self[sheet]=sheetList