嗨,我有一个txt文件,例如:
IP1 MAC1
IP2 MAC2
IP3 MAC3
等等(这些将是实际的IP地址和MAC地址(
我需要一个知道IP1和MAC1的循环中的帮助,并且是相关的。
我正在尝试编写一个使用循环并使用第一列文本(IP地址(的程序,并将登录到交换机中,并使用第二列值(MAC地址(在端口安全性中分配MAC。然后,它进入下一行并获得第二个IP和Mac,并做同样的事情,依此类推,直到文件结尾。
我有登录和命令设置
要让您入门,我有一个示例。将IP和Mac放在名为" file.txt"的文件中分开的IP和Mac,您可以运行此代码:
with open('file.txt') as input_file:
for i, line in enumerate(input_file):
line = line.strip()
ip, mac = line.split()
print("ip: " + ip + ", mac: " + mac)
将输出以下内容:
ip: IP1, mac: MAC1
ip: IP2, mac: MAC2
ip: IP3, mac: MAC3
我同意斯科特·亨特(Scott Hunter(的观点,但似乎您没有尝试过自己解决这个问题,这很令人惊讶,因为您与IPS和Mac的技术术语是证据表明您可以Google并找到答案(这就是我的答案做到了(。
#Open the file and make a list of tuples [(ip1, mac1), (ip2, mac2)..]
txt_file = open("text.txt", "r")
x = [x.rstrip().split() for x in file.readlines()]
#now make a dictionary where key = ip, v = MAC
dict_ = {k: v for k, v in x}
# You now have a dictionary where you can get the MAC from ip via
>>>dict_['ip address']
>>>MAC
希望会有所帮助。
希望这会为您提供其他方法:
import pandas as pd
filename =r'c:tempinput.txt'
list = pd.read_csv(filename, sep=' ', skiprows=0, header=None).fillna('')
for i, row in list.iterrows():
print '-'.join(p for p in row)
Output
IP1-MAC1
IP2-MAC2
IP3-MAC3