在做一个自动化测试框架中需要根据不同设备修改IP、username、password等信息,开始使用excel,单使用下来发现excel较死板,不方便后续维护。且功能自动化只针对单台设备,后续需要在UI上实现。确定使用config文件,放在程序中,使用时UI直接修改即可。
先了解ini文件的格式
[common] -----section
ip_addr = 192.168.25.71 ------option=value
username = admin
password = 123456
ssh_port = 22
telnet_port = 1723
读取和设置的代码如下
class Getipcmessage():
def __init__(self): ##获取配置文件路径及打开获取ini文件sections
self.dirpwd = os.path.abspath('..')
self.cfgname = r'%s\Config\IPCconfig.ini' %self.dirpwd
self.cf = ConfigParser.ConfigParser()
self.cf.read(self.cfgname)
secs = self.cf.sections()
opts = self.cf.options("common")
def getcfgmessage(self): ##获取配置文件中信息
self.ip = self.cf.get("common","ip_addr")
self.username = self.cf.get("common","username")
self.password = self.cf.get("common","password")
self.SSH_port = self.cf.get("common","SSH_port")
self.telnet_port = self.cf.get("common","telnet_port")
print self.ip,self.username,self.password,self.SSH_port
def setcfgip(self,value): ##设置IP信息到配置文件
self.cf.set("common", "ip_addr", value)
self.cf.write(open(self.cfgname,"w"))
def setcfgusername(self,value): ##设置username信息到配置文件
self.cf.set("common", "username", value)
self.cf.write(open(self.cfgname,"w"))
def setcfguspassword(self,value): ##设置password信息到配置文件
self.cf.set("common", "password", value)
self.cf.write(open(self.cfgname,"w"))
def setcfgusshport(self,value): ##设置ssh_port信息到配置文件
self.cf.set("common", "ssh_port", value)
self.cf.write(open(self.cfgname,"w"))
def setcfgutelnetport(self,value): ##设置telnet_port信息到配置文件
self.cf.set("common", "telnet_port", value)
self.cf.write(open(self.cfgname,"w"))
def __init__(self): ##获取配置文件路径及打开获取ini文件sections
self.dirpwd = os.path.abspath('..')
self.cfgname = r'%s\Config\IPCconfig.ini' %self.dirpwd
self.cf = ConfigParser.ConfigParser()
self.cf.read(self.cfgname)
secs = self.cf.sections()
opts = self.cf.options("common")
def getcfgmessage(self): ##获取配置文件中信息
self.ip = self.cf.get("common","ip_addr")
self.username = self.cf.get("common","username")
self.password = self.cf.get("common","password")
self.SSH_port = self.cf.get("common","SSH_port")
self.telnet_port = self.cf.get("common","telnet_port")
print self.ip,self.username,self.password,self.SSH_port
def setcfgip(self,value): ##设置IP信息到配置文件
self.cf.set("common", "ip_addr", value)
self.cf.write(open(self.cfgname,"w"))
def setcfgusername(self,value): ##设置username信息到配置文件
self.cf.set("common", "username", value)
self.cf.write(open(self.cfgname,"w"))
def setcfguspassword(self,value): ##设置password信息到配置文件
self.cf.set("common", "password", value)
self.cf.write(open(self.cfgname,"w"))
def setcfgusshport(self,value): ##设置ssh_port信息到配置文件
self.cf.set("common", "ssh_port", value)
self.cf.write(open(self.cfgname,"w"))
def setcfgutelnetport(self,value): ##设置telnet_port信息到配置文件
self.cf.set("common", "telnet_port", value)
self.cf.write(open(self.cfgname,"w"))