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文件当前目录.如果你有配 ...
随机推荐
- Python基础(八) yaml在python中的使用
yaml 通常用来存储数据,类似于json YAML 简介 YAML(Yet Another Markup Language),一种直观的能够被电脑识别的数据序列化格式,是一个可读性高并且容易被人类阅 ...
- python使用grpc调用rpc接口
proto文件: syntax = "proto3"; package coupon; // //message UnsetUseC2URequest { // int64 bid ...
- HTML5入门教程:响应式页面布局
摘自:https://www.sohu.com/a/225633935_647584 随着互联网时代的发展,我们对网页布局有了新的要求,大气,美观,能够在不同的设备上呈现令人焕然一新的效果.此时,一个 ...
- json-server基本使用
**一.前后端并行开发的痛点** 前端需要等待后端开发完接口以后 再根据接口来完成前端的业务逻辑 **二.解决方法** 在本地模拟后端接口用来测试前端效果 这种做法称之为构建前端Mock **三.js ...
- GoldenGate for Java adapter介绍二(代码篇)
本示例主要介绍通过实现OGG的接口函数,实现自定义处理增量数据,将数据实时写入到mariadb (OGG官方不支持此数据库,所以只能采用自定义方式实现).以下是本次示例的4个类: Connection ...
- LOJ #10130 点的距离
在LOJ做的第一道题. 最开始想复杂了qwq 想的是在求LCA的过程中统计向上的步数 其实此题很裸--就是求出u,v的LCA, 再分别用两点深度减去LCA的深度,再加起来就好了qwq---化简--- ...
- Dijkstra双栈算术表达式求值
在看algs4的时候偶然发现了这个算法,又回顾了一遍当时数据结构课程里讲过的知识,当时很不在意.迟早是要还的,哎 用python实现了,比较麻烦的是我现在没有解决bash传参的问题,''(" ...
- jquery easyui的应用-1
下载地址是: www.jeasyui.com/download 当前版本是1.6.7 是由 jquery ui 扩展而来的. 像jquery ui, bootstrap, jquery easyui三 ...
- SpringBoot HttpServletResponse Header Cookie输出问题
问题: 在一次Response写入header和cookie的时候,发现部分信息没有被输出 工具类: CookieUtils: import java.io.IOException; import j ...
- postgresql:terminate hung query
--Find the PID by running this sql: SELECT pid , query, * from pg_stat_activity WHERE state != 'idle ...