1.增删改查haproxy.conf配置文件

1.查询输入:www.oldboy1.com

2.删除输入:{'backend': 'www.oldboy2.org','record':{'server': ["1.1.1.1","2.2.2.2"],'weight': 20,'maxconn': 30}}

3.增加输入:{'backend': 'www.oldboy2.org','record':{'server': ["1.1.1.1","2.2.2.2"],'weight': 20,'maxconn': 30}}

4.修改输入:{'backend': 'www.oldboy2.org','record':{'server': ["1.1.1.1","2.2.2.2"],'weight': 20,'maxconn': 30}}

 修改之后:{'backend': 'www.oldboy2.org','record':{'server': ["1.1.1.1","2.2.2.2"],'weight': 20,'maxconn': 30}}

 global
log 127.0.0.1 local2
daemon
maxconn 256
log 127.0.0.1 local2 info defaults
log global
mode http
timeout connect 5000ms
timeout client 50000ms
timeout server 50000ms
option dontlognull listen stats :8888
stats enable
stats uri /admin
stats auth admin:1234 frontend oldboy.org
bind 0.0.0.0:80
option httplog
option httpclose
option forwardfor
log global
acl www hdr_reg(host) -i www.oldboy.org
use_backend www.oldboy.org if www backend www.oldboy1.org
server 100.1.7.9 weight 20 maxconn 1111111
server 100.1.7.9 weight 20 maxconn 0
server 10.10.0.10 10.10.0.10 weight 9999 maxconn 33
server 10.10.10.1 10.10.10.1 weight 22 maxconn 2000
server 2.2.2.4 2.2.2.4 weight 20 maxconn 3000 backend www.oldboy2.org
server 1.1.1.1 2.2.2.2 weight 20 maxconn 30
server 10.10.0.10 10.10.0.10 weight 9999 maxconn 33
server 10.10.10.1 10.10.10.1 weight 22 maxconn 2000 backend www.oldboy20.org
server 10.10.0.10 10.10.0.10 weight 9999 maxconn 33

haproxy.conf配置文件

 import os

 def menu():
menu = (
"""
1. 增加
2. 删除
3. 修改
4. 查找""")
print(menu.lstrip('\n')) def InsertConf():
content = eval(input("please input content:"))
server1 = content["record"]["server"][0]
server2 = content["record"]["server"][1]
weight = content["record"]["weight"]
maxconn = content["record"]["maxconn"]
with open("hafile",mode="r",encoding="utf8") as f,open("hafile.bak",mode="w+",encoding="utf8") as f_bak:
for line in f:
if line.startswith("backend") and content["backend"] in line:
f_bak.write(line)
f_bak.write(" server %s %s weight %d maxconn %d\n" % (server1,server2, weight, maxconn))
continue
f_bak.write(line)
os.rename("hafile","hafile.obj")
os.rename("hafile.bak","hafile") def DeleteConf():
flag = False
choice = eval(input("input content"))
with open("hafile", encoding="utf8") as f_read, open("hafile.bak", mode="w", encoding="utf8") as f_write:
for line in f_read:
if line.startswith("backend") and choice["backend"] in line:
flag = True
if choice["record"]["server"][0] in line \
and choice["record"]["server"][1] in line \
and str(choice["record"]["weight"]) in line \
and str(choice["record"]["maxconn"]) in line \
and flag == True:
flag = False
continue
f_write.write(line)
os.rename("hafile","hafile.obj")
os.rename("hafile.bak","hafile") def UpdateConf():
flag = False
Original = eval(input("input Original content"))
Modified = eval(input("input Modified content"))
Modified = "\t\tserver %s %s weight %s maxconn %s\n" % (Modified["record"]["server"][0],\
Modified["record"]["server"][1], \
Modified["record"]["weight"], \
Modified["record"]["maxconn"])
with open("hafile", encoding="utf8") as f_read, open("hafile.bak", mode="w", encoding="utf8") as f_write:
for line in f_read:
if line.startswith("backend") and Original["backend"] in line:
flag = True
print(line)
if Original["record"]["server"][0] in line \
and Original["record"]["server"][1] in line \
and str(Original["record"]["weight"]) in line \
and str(Original["record"]["maxconn"]) in line \
and flag == True:
flag = False
f_write.write(Modified)
continue
f_write.write(line)
def FindConf():
recode = []
flag = False
ipname = input("please input domain name:")
with open("hafile",mode="r",encoding="utf8") as f:
for line in f:
if line.startswith("backend") and ipname in line:
flag = True
continue
if line.startswith("backend")and flag == True:
break
if flag:
recode.append(line.strip())
for value in recode:
print("\t%s"%(value.rstrip())) def Main():
menu()
choice = int(input("input number:"))
return choice if __name__ == "__main__":
while True:
obj = Main()
if obj == 1:
InsertConf()
elif obj ==2:
DeleteConf()
elif obj == 3:
UpdateConf()
elif obj == 4:
FindConf()
else:
continue

实现代码

2.用户认证

 用户输入账号密码三次错误,程序终止

 如果三次都是同一用户错误,锁定用户

1.定义一个字典,用户每次错误向字典增加记录{name count},当用户输入错误3次退出时,      判断字典的值是否大于3,大于3写到锁定文件里
 alex      alex3417
oldboy oldboy110
oldgirl oldgirl110

账号 密码

 accounts = {}

 def lock_user(name):
with open("lock_user", mode="r+", encoding="utf8") as f_lock:
for line in f_lock:
if line.strip().split()[0] == name:
print("Lock user")
exit() def lockd_user(**kwargs):
with open("lock_user",mode="a+",encoding="utf8") as f_lockd_user:
for key in kwargs:
if kwargs[key] >2:
f_lockd_user.write(key + "\n") def check_user(name,passwd):
with open("user",mode="r",encoding="utf8") as f_check:
for line in f_check:
if name == line.strip().split()[0]:
if passwd == line.strip().split()[1]:
print("Success")
exit()
else:
add_error(name)
return name
return name def add_error(name):
if accounts:
if name in accounts:
accounts[name] += 1
else:
accounts[name] = 1
else:
accounts[name] = 1 def main():
count = 0
while True:
name = input("input name: ")
passwd = input("input passwd: ")
lock_user(name) #判断用户是否锁定
name = check_user(name,passwd) #判断用户
count += 1
if count > 2:
lockd_user(**accounts)
print("exit than three")
break if __name__ == '__main__':
main()

代码实现

1.猜年龄,最多输入三次

 count = 1
age = 8
while count <= 3:
guess_age = int(input("please input your age: "))
if guess_age == age:
print("You're right")
exit()
elif count == 3:
exit()
else:
print("try agin..")
count = count + 1

代码

2.猜年龄 ,每隔3次,问他一下,还想不想继续玩,y,n

 count = 1
age = 18
while True:
guess_age = int(input("please input your age: "))
if guess_age == age:
print("You're right")
exit()
elif (count % 3) == 0:
count += 1
play = input("do you want to paly{y|n}")
if play == "y":
continue
else:
exit()
else:
print("you're wrong")
count +=1

代码实现

3.编写登陆接口 输入用户名密码 认证成功后显示欢迎信息 输错三次后锁定

accounts = {}

def lock_user(name):
with open("lock_user", mode="r+", encoding="utf8") as f_lock:
for line in f_lock:
if line.strip().split()[0] == name:
print("Lock user")
exit() def lockd_user(**kwargs):
with open("lock_user",mode="a+",encoding="utf8") as f_lockd_user:
for key in kwargs:
if kwargs[key] >2:
f_lockd_user.write(key + "\n") def check_user(name,passwd):
with open("user",mode="r",encoding="utf8") as f_check:
for line in f_check:
if name == line.strip().split()[0]:
if passwd == line.strip().split()[1]:
print("Success")
exit()
else:
add_error(name)
return name
return name def add_error(name):
if accounts:
if name in accounts:
accounts[name] += 1
else:
accounts[name] = 1
else:
accounts[name] = 1 def main():
count = 0
while True:
name = input("input name: ")
passwd = input("input passwd: ")
lock_user(name) #判断用户是否锁定
name = check_user(name,passwd) #判断用户
count += 1
if count > 2:
lockd_user(**accounts)
print("exit than three")
break if __name__ == '__main__':
main()

用户登录,三次后锁定

4.跳出3层循环

 flag = True

 while flag:
while flag:
while flag:
if 1 != 2:
flag = False print("come on")
flag = False for i in range(10): print("爷爷好") for n in range(10): print("爸爸好") for k in range(10): print("孙子好")
if k == 2:
flag = True
break
if flag:
break
if flag:
break print("come on")

代码实现

5.购物车

 import os

 shop = ["Apple","coffee","book","condom"]
price = [5800,30,50,90]
shopping = [] while True:
try:
salary = int(input("input your salary: "))
break
except:
continue if salary <= min(price):
print("你工资太少了.金额为", salary, "退出吧..老表")
exit() while True:
print("You can buy the following items")
for i in range(len(shop)):
print(i,".",shop[i], " ",price[i])
choice = input("please choice number or input q exit>>").strip()
if choice.isdigit():
choice = int(choice)
if choice in range(len(shop)):
balance = salary - price[choice]
if balance >= 0:
print("your bought",shop[choice],"balance",balance,"元")
shopping.append(shop[choice])
salary = balance
else:
print("you money",salary,"Differ",balance,"you can try")
else:
continue
elif choice == "q":
if len(shopping) == 0:
print("You didn't buy anything")
for i in range(len(shopping)):
print("You bought ",shopping[i])
print("Your balance:",salary)
break
else:
continue

代码实现

 import os

 shop = ["Apple","coffee","book","condom"]
price = [5800,30,50,90]
shopping = {} while True:
try:
salary = int(input("input your salary: "))
break
except:
continue if salary <= min(price):
print("你工资太少了.金额为", salary, "退出吧..老表")
exit() count = 1
total = 0
while True:
print("You can buy the following items")
for i in range(len(shop)):
print("%s %-6s %d" % (i,shop[i],price[i]))
choice = input("please choice number or input q exit>>").strip()
if choice.isdigit():
choice = int(choice)
if choice in range(len(shop)):
balance = salary - price[choice]
if balance >= 0:
print("\033[31;1myour bought\033[0m",shop[choice],"\033[31;1mbalance\033[0m",balance,"元")
if len(shopping) > 0:
if shop[choice] in shopping.keys():
shopping[shop[choice]][0] += 1
shopping[shop[choice]][2] += price[choice]
else:
shopping[shop[choice]] = [1,price[choice],price[choice]]
else:
#print(shop[choice])
shopping[shop[choice]] = [1,price[choice],price[choice]]
salary = balance
else:
print("you money",salary,"Differ",balance,"you can try")
else:
continue
elif choice == "q":
if len(shopping) == 0:
print("You didn't buy anything")
else:
print("id 商品 数量 单价 总价")
for i in shopping.keys():
print("%-4d %-8s %-6d %-6d %-6d" % (count,i,shopping[i][0],shopping[i][1],shopping[i][2]))
count += 1
total += shopping[i][2]
print("\033[31;1myour balance\033[0m",total,"元")
exit()
else:
continue

代码优化

进度条

import sys,time
for i in range(101):
s = "\r%d%% %s"%(i,"#"*i)
sys.stdout.write(s)
sys.stdout.flush()
time.sleep(0.5)

进度条

6.打印三级菜单,省 市 县

可随时退出或跳出上一级

 menu = {
'北京':{
'海淀':{
'五道口':{
'soho':{},
'网易':{},
'google':{}
},
'中关村':{
'爱奇艺':{},
'汽车之家':{},
'youku':{},
},
'上地':{
'百度':{},
},
},
'昌平':{
'沙河':{
'老男孩':{},
'北航':{},
},
'天通苑':{},
'回龙观':{},
},
'朝阳':{},
'东城':{},
},
'上海':{
'闵行':{
"人民广场":{
'炸鸡店':{}
}
},
'闸北':{
'火车战':{
'携程':{}
}
},
'浦东':{},
},
'山东':{},
}

菜单字典

 last_layer = []
current_layer = menu while True:
for i in current_layer:
print(i)
choice = input("please input layer or b:")
if len(choice) == 0: continue
if choice in current_layer:
last_layer.append(current_layer)
current_layer = current_layer[choice]
if choice == "b":
if len(last_layer):
current_layer = last_layer[-1]
last_layer.pop()
else:
current_layer = menu
if choice == 'q':
break

代码实现

python 多个脚本的更多相关文章

  1. python注释、脚本参数、字节码

    python注释.脚本参数.字节码 --道心 python安装 1.下载安装包 https://www.python.org/downloads/ 2.安装 默认安装路径:C:\python27 3. ...

  2. Python数据库备份脚本

    Python数据库备份脚本 #!/usr/bin/env python # author: liudong # -*- coding: utf-8 -*- # filename: db_bak.py ...

  3. 「python」: arp脚本的两种方法

    「python」: arp脚本的两种方法 第一种是使用arping工具: #!/usr/bin/env python import subprocess import sys import re de ...

  4. 老李分享:Python开发性能测试脚本

    老李分享:Python开发性能测试脚本   测试开发工程师的工作主要是根据测试目标来完成,帮助测试人员完成测试目标,测试的业务需求是测试人员提出,但是由于环境的制约,手中没有性能测试工具的时候,性能测 ...

  5. python编写shell脚本详细讲解

    python编写shell脚本详细讲解 那,python可以做shell脚本吗? 首先介绍一个函数: os.system(command) 这个函数可以调用shell运行命令行command并且返回它 ...

  6. 用 Python 替代 Bash 脚本(转)

    add by zhj: 其实作者是想说用Python来做那些Bash实现起来比较麻烦的部分,即将Bash与Python结合使用. 英文原文:http://www.linuxjournal.com/co ...

  7. python监控端口脚本[jkport2.0.py]

    #!/usr/bin/env python #!coding=utf-8 import os import time import sys import smtplib from email.mime ...

  8. centos 7 keepalived故障邮件通知实战(附Python邮件发送脚本)

    centos 7 keepalived故障邮件通知实战(附Python邮件发送脚本) #####################     sendmail.py  begin     ######## ...

  9. Python 调用 Shell脚本的方法

    Python 调用 Shell脚本的方法 1.os模块的popen方法 通过 os.popen() 返回的是 file read 的对象,对其进行读取 read() 的操作可以看到执行的输出. > ...

  10. Python获取当前脚本文件夹(Script)的绝对路径

    Python获取当前脚本绝对路径 Python脚本有一个毛病,当使用相对路径时,被另一个不同目录下的py文件中导入时,会报找不到对应文件的问题.感觉是当前工作目录变成了导入py文件当前目录.如果你有配 ...

随机推荐

  1. qt 安装包生成

    (Qt Installer Framework)程序简易打包教程 2017年06月19日 14:38:47 carman_风 阅读数:3559 标签: installerqt框架 更多 个人分类: 软 ...

  2. sourcetree 免注册

    http://www.cnblogs.com/xiofee/p/sourcetree_pass_initialization_setup.htmlSourceTree 安装之后需要使用账号登陆以授权, ...

  3. 自定义Word颜色主题

    外观 说明 看到这个黑色编辑器的界面,第一印象可能认为是Sublime.Atom. VScode或者其它markdown编辑器.其实仅仅是微软的Word经过了自定义主题. 选择清晰易于辨认的字体和深色 ...

  4. JDK安装与配置(Windows 7系统)

    1.前言 安装之前需弄清JDK.JRE.JVM这几个概念,不然稀里糊涂不知道自己在装什么. (1)什么是java环境:我们知道,想听音乐就要安装音乐播放器,想看图片需要安装图片浏览器,同样道理,要运行 ...

  5. flask 操作数据时,db的要在app.config设置之后声明:如app.config['SQLALCHEMY_DATABASE_URI']

    flask 操作数据时,db的要在app.config设置之后声明:如app.config['SQLALCHEMY_DATABASE_URI'] 否则,运行程序时app.config里面做的设置就不会 ...

  6. Hdu2015 偶数求和

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2015 偶数求和 Time Limit: 2000/1000 MS (Java/Others)    M ...

  7. 常用git命令总结 初始化git库操作 git 子模块

    查看 git status 查看状态 Gitk 界面各个版本查看 添加 Git add filename 添加指定文件 Git add . 操作未暂存的文件 Git add -A 操作所有文件 包括删 ...

  8. linux svn客户端安装

    yum install -y subversion svn checkout使用示例: 先创建一个目录,例如:mkdir test 检出到test目录下 svn checkout svn://192. ...

  9. Git冲突和解决冲突-测试方法

    原文链接:https://www.cnblogs.com/blogslee/p/6828659.html

  10. 剑指offer(57)二叉树的下一个节点

    题目描述 给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回.注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针. 题目分析 这题一定要画图,因为只有画图我们才能分清楚下 ...