在引入from configparser import ConfigParser 时需要先使用pip3 install configparser 安装一下
import os
import telnetlib
from configparser import ConfigParser
##引入配置文件导入模块
from TestModel.models import Democtl
##引入数据库配置
#初始化类 ConfigUtils
class ConfigUtils(object):
def __init__(self, fileName):
super(ConfigUtils, self).__init__()
#try:
self.config = ConfigParser()
self.config.read(fileName)
#if __name__ == '__main__':
def socron():
state_run = '运行中'
state_stop = ''
##引入配置文件中的区块名
section_list = ['test1', 'test2']
for section in section_list:
##引用ConfigUtils 在当前目前寻找section_list.cfg文件,可以写成绝对路径
cfg = ConfigUtils('section_list.cfg').config
##引入每个区块里的变量并赋值给新的变量
DemoName = cfg.get(section, 'DemoName')
HostIP = cfg.get(section, 'HostIP')
DemoPort = cfg.get(section, 'DemoPort')
##进行telnet 监测
try:
tel = telnetlib.Telnet(HostIP, port=DemoPort, timeout=5)
tel.close()
##监测端口失败时调用此函数
writeTodb( DemoName, HostIP, DemoPort, state_run)
except:
##监测端口成时调用此函数
writeTodb(DemoName, HostIP, DemoPort, state_stop)
##函数writeTodb ,引入初始参数值
def writeTodb(DemoName, HostIP, DemoPort, status):
#print(Demoname, HostIP, DemoPort, status)
##python objects 数据库管理方法,通过()内的索引,查询指定数据,并在第二行进行字段修改,第三行进行保存语句动作
##或者用下面一条命令
##Democtl.objects.filter(demoname=DemoName,demohost=HostIP,demoport=DemoPort).update(demostate=status)
changedb = Democtl.objects.get(demoname=DemoName,demohost=HostIP,demoport=DemoPort)
changedb.demostate = status
changedb.save()
##读取所有数据,相当于select * from
response = ""
list = Democtl.objects.all()
for var in list:
response += var.demoname + ";" + var.demohost + ";" +var.demoport
print(response)
section_list.cfg的内容如下:
[test1]
DemoName = redis
HostIP = 192.168.3.68
DemoPort = 6379
[test2]
DemoName = test
HostIP = 192.168.3.68
DemoPort = 8000