Python 引用cfg类型的配置文件(configparser)(telnetlib的使用方法)

在引入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

 

 

 

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值