demo

作者: butters001 | 来源:发表于2020-09-11 09:20 被阅读0次
    import tornado.ioloop
    import tornado.web
    import subprocess
    import sys
    import constant
    import MySQLdb
    import time
    import logging
    
    
    # 格式化日志
    logging.basicConfig(level=logging.DEBUG, filename='main.log')
    # 1. 创建一个logger
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)  # Log等级总开关
    # 2. 创建一个handler,用于写入日志文件
    rq = time.strftime('%Y%m%d%H%M', time.localtime(time.time()))
    fh = logging.FileHandler("/var/log/kickout/kickout.log", mode='w')
    fh.setLevel(logging.DEBUG)  # 输出到file的log等级的开关
    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)  # 输出到console的log等级的开关
    # 3. 定义handler的输出格式
    formatter = logging.Formatter("%(asctime)s [%(threadName)s:%(thread)d] [%(name)s:%(lineno)d] [%(module)s:%(funcName)s] [%(levelname)s]- %(message)s")
    fh.setFormatter(formatter)
    # 4. 将logger添加到handler里面
    logger.addHandler(fh)
    ch.setFormatter(formatter)
    logger.addHandler(ch)
    
    sys.path.append("..")
    
    
    def kickout_login_users():
        """
        踢出其他登录用户
    
        :param subprocess_kill: bool, 标志是否kill掉用户启动的所有子进程, 默认KILL
        """
        logger.info("正在遍历......")
    
        # 遍历数据库 产看状态 解禁用户
        # 打开数据库连接
        db = MySQLdb.connect(host=constant.mysql_host, user=constant.mysql_user, passwd=constant.mysql_password,
                             db=constant.mysql_db, charset='utf8')
    
        # 使用cursor()方法获取操作游标
        cursor = db.cursor()
        try:
            cursor.execute("select * from ssher where status=1 and host_ip='%s'" % constant.host_ip)
            infos = cursor.fetchall()
            if not infos:
                return
            for info in infos:
                # 查看status=1 禁止时间是否超时
                if int(time.time()) - info[3] > info[4]:  # time.time() - start > expire
                    # 解禁
                    sub = subprocess.Popen("iptables -I INPUT -s %s -j ACCEPT" % info[1], shell=True, stdout=subprocess.PIPE)
                    sub.wait()
                    # 更改数据库状态 哈哈
                    cursor.execute("update ssher set status=0 where host_ip='%s' and remote_ip='%s'" % (constant.host_ip, info[1]))
                    db.commit()
                    logger.info("宿主: %s 解封了远程IP: %s" % (constant.host_ip, info[1]))
                else: # 还没到时间
                    continue
        except Exception as e:
            logger.error("ERROR: " + str(e))
            db.rollback()
    
        # 关闭数据库连接
        cursor.close()
        db.close()
    
    class MainHandler(tornado.web.RequestHandler):
        def get(self):
            self.write('Hello Tornado')
    
    
    def make_app():
        return tornado.web.Application([
            (r"/", MainHandler),
        ])
    
    
    if __name__ == '__main__':
        app = make_app()
        app.listen(8888)
        tornado.ioloop.PeriodicCallback(kickout_login_users, constant.interval_time).start()
        tornado.ioloop.IOLoop.current().start()
    

    相关文章

      网友评论

          本文标题:demo

          本文链接:https://www.haomeiwen.com/subject/qhxbaftx.html