python 多个脚本
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 多个脚本的更多相关文章
- python注释、脚本参数、字节码
python注释.脚本参数.字节码 --道心 python安装 1.下载安装包 https://www.python.org/downloads/ 2.安装 默认安装路径:C:\python27 3. ...
- Python数据库备份脚本
Python数据库备份脚本 #!/usr/bin/env python # author: liudong # -*- coding: utf-8 -*- # filename: db_bak.py ...
- 「python」: arp脚本的两种方法
「python」: arp脚本的两种方法 第一种是使用arping工具: #!/usr/bin/env python import subprocess import sys import re de ...
- 老李分享:Python开发性能测试脚本
老李分享:Python开发性能测试脚本 测试开发工程师的工作主要是根据测试目标来完成,帮助测试人员完成测试目标,测试的业务需求是测试人员提出,但是由于环境的制约,手中没有性能测试工具的时候,性能测 ...
- python编写shell脚本详细讲解
python编写shell脚本详细讲解 那,python可以做shell脚本吗? 首先介绍一个函数: os.system(command) 这个函数可以调用shell运行命令行command并且返回它 ...
- 用 Python 替代 Bash 脚本(转)
add by zhj: 其实作者是想说用Python来做那些Bash实现起来比较麻烦的部分,即将Bash与Python结合使用. 英文原文:http://www.linuxjournal.com/co ...
- python监控端口脚本[jkport2.0.py]
#!/usr/bin/env python #!coding=utf-8 import os import time import sys import smtplib from email.mime ...
- centos 7 keepalived故障邮件通知实战(附Python邮件发送脚本)
centos 7 keepalived故障邮件通知实战(附Python邮件发送脚本) ##################### sendmail.py begin ######## ...
- Python 调用 Shell脚本的方法
Python 调用 Shell脚本的方法 1.os模块的popen方法 通过 os.popen() 返回的是 file read 的对象,对其进行读取 read() 的操作可以看到执行的输出. > ...
- Python获取当前脚本文件夹(Script)的绝对路径
Python获取当前脚本绝对路径 Python脚本有一个毛病,当使用相对路径时,被另一个不同目录下的py文件中导入时,会报找不到对应文件的问题.感觉是当前工作目录变成了导入py文件当前目录.如果你有配 ...
随机推荐
- cocos2d-x 贡献一个oss上传脚本
平常写前端项目和H5游戏时特别频繁的一个操作就是上传到oss上,特别浪费时间.所以用ali-oss写了一个脚本.配置属性后直接npm run oss就能上传到oss上了.再也不需要手动操作.现在是脚本 ...
- C# 并发编程 · 经典实例
http://www.cnblogs.com/savorboard/p/csharp-concurrency-cookbook.html 异步基础 任务暂停,休眠 异步方式暂停或者休眠任务,可以使用 ...
- sourcetree 免注册
http://www.cnblogs.com/xiofee/p/sourcetree_pass_initialization_setup.htmlSourceTree 安装之后需要使用账号登陆以授权, ...
- 以选项卡的故事扯扯js面向对象
在现在的网页中,选项卡(我自己这样子叫)是非常普遍的,也是比较基础,学了原型实现选项卡也挺久了,最近在学ES6,学了用类实现选项卡,今天就在此做个总结,别的废话也不多说. 以"貌" ...
- C# 杀掉Windows中所有Excel进程
Process[] procs = Process.GetProcessesByName("excel"); foreach (Process pro in procs) { pr ...
- Flutter 控件之 Routes 和 Navigator. [PopupRoute]
一个 App 通常会有多个界面,每个界面实现不同的功能,并在多个界面之间跳转.在 Flutter 中多个界面的跳转是通过 Navigator 来实现的. 在 Flutter 中定义了一个 Overla ...
- Java爬取B站弹幕 —— Python云图Wordcloud生成弹幕词云
一 . Java爬取B站弹幕 弹幕的存储位置 如何通过B站视频AV号找到弹幕对应的xml文件号 首先爬取视频网页,将对应视频网页源码获得 就可以找到该视频的av号aid=8678034 还有弹幕序号, ...
- Wireshark解析MQTT
Mac下安装lua curl -R -O http://www.lua.org/ftp/lua-5.2.3.tar.gz tar zxf lua-5.2.3.tar.gz cd lua-5.2.3 m ...
- POJ 1390 Blocks(DP + 思维)题解
题意:有一排颜色的球,每次选择一个球消去,那么这个球所在的同颜色的整段都消去(和消消乐同理),若消去k个,那么得分k*k,问你消完所有球最大得分 思路:显然这里我们直接用二位数组设区间DP行不通,我们 ...
- 力扣(LeetCode)605. 种花问题
假设你有一个很长的花坛,一部分地块种植了花,另一部分却没有.可是,花卉不能种植在相邻的地块上,它们会争夺水源,两者都会死去. 给定一个花坛(表示为一个数组包含0和1,其中0表示没种植花,1表示种植了花 ...