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. jquery对复选框(checkbox)的操作(精华)

    @{ Layout = null;} <!DOCTYPE html> <html><head> <meta name="viewport" ...

  2. vim代码格式化插件clang-format

    title: vim代码格式化插件clang-format date: 2017-12-12 20:28:26 tags: vim categories: 开发工具 安装vim-clang-forma ...

  3. Linux 安装vsftpd和ftp客户端

    1.下载安装包:ftp-0.17-54.el6.x86_64.zip和vsftpd-2.2.2-11.el6_4.1.x86_64.zip 可以直接在Linux底下用yum install vsftp ...

  4. Google 开发的、最好用、功能最强大的网页测速与网站性能分析工具

    https://www.webpagetest.org/细致到每一个资源的加载都是完全可视化,包含详细的数据分析.开发完成自己的网站后一定要进行一下测试,你会发现还有很多可以优化的点.

  5. python 猜数字游戏

    import random print('==============学无止境==========') secret=random.randint(1,10) print('sec:',secret) ...

  6. Eclipse进度条出现“Remote System Explorer Operation”解决方法

    Eclipse进度条出现“Remote System Explorer Operation”解决方法  

  7. Java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

    在使用response重定向的时候,报以下错误:Java.lang.IllegalStateException: Cannot call sendRedirect() after the respon ...

  8. vue-cli 构建项目在IE中无法运行解决方式(build之后可运行)

    IE浏览器(只考虑IE11,更低版本我没考虑)运行时报 Promise未定义的错误 解决办法: 1. 安装babel-polyfill (1.)  npm install babel-polyfill ...

  9. .NET Core 配置GC工作模式与内存的影响

    .NET Core 配置GC工作模式与内存的影响 .NET Core GC 原文:https://blog.markvincze.com/troubleshooting-high-memory-usa ...

  10. html复习小结

    border-radius可以设置百分比 百分之五十是圆形 class="class1 class2" 无序列表 <ul><li></li>&l ...