Python 学习.. 将持续更新
2016年,开始学习python的基础知识,然后是 python 自动化运维.从最基础的出发..
第一个python 脚本..(mysql 备份脚本)
#!/usr/bin/python #coding:utf-8 import os import time backup = '/opt/jicki/' today = backup + time.strftime('%Y%m%d') now = time.strftime('%H%M%S') if not os.path.exists(today): os.mkdir(today) target = today + os.sep + now + '.sql' sqldump = "mysqldump -uroot -pxxxxxx -A -R > '%s' " % (target) os.system(sqldump)
第二个 验证脚本
#-*- coding:utf-8 –*- import sys user = "jicki" passwd = "12345" cou = 0 while True: name = raw_input('请输入用户名:').strip() passwds = raw_input('请输入密码:') if cou < 3: if len(name) == 0: print "用户名不能为空,请重新输入" continue elif len(passwds) == 0: print "密码不能为空,请重新输入" continue elif name == user and passwds == passwd : pass else: print "用户名或密码错误" cou = cou + 1 print cou continue break else: cou > 3 print "密码错误超过三次!" sys.exit() print "%s 登陆成功" % (name)
一个邮件发送的方法:
import smtplib from email.mime.text import MIMEText from email.utils import formataddr def mail(): ret = True try: msg =MIMEText('邮件内容','plain','utf-8') msg['From'] = formataddr(['jicki'],'jicki@qq.com') msg['To'] = formataddr(['50207121'],'50207121@qq.com') msg['Subject'] = '主题' server = smtplib.SMTP('smtp.126.com', 25) server.login('jicki@qq.com', '邮箱密码') server.sendmail('jicki@qq.com', ['50207121@qq.com',], msg.as_string()) server.quit() except Exception: ret = False return ret ret = mail() if ret: print('邮件发送成功') else: print('邮件发送失败')
第三个 列表的应用 获取本地war包名称,判断列表中对应IP与端口 , 并更新至服务器,并执行命令。
#-*- coding:utf-8 –*- import os import paramiko def sshlogin(ip,port,username,passwd): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip,int(port),username,passwd) return ssh IP = [ 'bbcc.war:192.168.0.2:22', 'aabb.war:192.168.0.3:22' ] file_name = os.listdir(".") if len(file_name) > 1: for b in IP: remoteID = b.split(":")[0] remoteIP = b.split(":")[1] remotePORT = b.split(":")[2] for name in file_name: if name == remoteID: ssh = sshlogin(remoteIP,remotePORT,'root','xxxx') stdin,stdout,stderr = ssh.exec_command('/opt/local/tomcat/bin/shutdown.sh ; rm -rf /opt/local/tomcat/work/Catalina/* ') stdin,stdout,stderr = ssh.exec_command('rm -rf /opt/local/tomcat/webapp/'+remoteID ) stdin,stdout,stderr = ssh.exec_command('rm -rf /opt/local/tomcat/webapp/'+remoteID[:-4] ) push = paramiko.Transport((remoteIP,int(remotePORT))) push.connect(username = 'root', password = 'xxxx') sftp = paramiko.SFTPClient.from_transport(push) remotepath = '/opt/local/tomcat/webapp/'+remoteID localpath = remoteID sftp.put(localpath,remotepath) push.close ssh = sshlogin(remoteIP,remotePORT,'root','xxxx') stdin,stdout,stderr = ssh.exec_command('/opt/local/tomcat/bin/startup.sh') print stdout.readlines() print remoteID,remoteIP,remotePORT ssh.close()
SSH key 登陆执行命令,与 上传文件
#-*- coding:utf-8 –*- import os import paramiko def sshlogin(ip,port,username,passwd,pkey_file): ssh = paramiko.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) key = paramiko.RSAKey.from_private_key_file(pkey_file) ssh.connect(ip,int(port), username, pkey=key, timeout=5) return ssh IP = { 'bbcc.war':['192.168.0.2':'22'], 'aabb.war':['192.168.0.3':'22'] } file_name = os.listdir(".") pkey_file = '/root/.ssh/id_rsa' if len(file_name) > 1: for name1, ip in IP.items(): remoteID = name1 remoteIP = ip[0] remotePORT = ip[1] for name2 in file_name: if name2 == remoteID: print "===================================================" print('开始更新 %s ' %remoteID) localpath = remoteID remotepath = '/opt/local/tomcat/webapp/'+remoteID ssh = sshlogin(remoteIP,remotePORT,'root','', pkey_file = pkey_file) stdin,stdout,stderr = ssh.exec_command('/opt/local/tomcat/bin/shutdown.sh ; rm -rf /opt/local/tomcat/work/Catalina/* ') stdin,stdout,stderr = ssh.exec_command('rm -rf /opt/local/tomcat/webapp/'+remoteID ) stdin,stdout,stderr = ssh.exec_command('rm -rf /opt/local/tomcat/webapp/'+remoteID[:-4] ) t = ssh.get_transport() sftp = paramiko.SFTPClient.from_transport(t) d = sftp.put(localpath, remotepath) stdin,stdout,stderr = ssh.exec_command('/opt/local/tomcat/bin/startup.sh') print(stdout.readlines()) print "更新 %s 完成 ,服务器为 %s , 端口为%s" % (remoteID,remoteIP,remotePORT) print "===================================================" ssh.close()
第四 购物商城,程序
import pickle def main(): while True: print(''' 1. 注册帐号 2. 登陆系统 3. 退出程序 ''') main_input = input('请选择服务,请输入数字:').strip() if main_input == "1": reg() elif main_input == "2": login() elif main_input == "3": quit() else: print("数字都不会选,请重新输入数字。") def quit(): print('再见,Good Bye !') exit() def reg(): with open('user.txt', 'rb') as f: user = pickle.load(f) while True: reg_input = input("请输入注册用户:").strip() if len(reg_input) < 5: print("用户名不能于5个字符,请重新输入!") continue if reg_input in user.keys(): print("用户名已存在,请重新输入!") continue else: user[reg_input] = {'passwd':'', 'money': 10000, 'lock': '0'} while True: reg_pwd = input("请输入注册密码:").strip() if len(reg_pwd) < 5: print("密码不能少于5个字符,请重新输入!") continue reg_pwd2 = input("请再次输入注册密码:").strip() if reg_pwd == reg_pwd2: user[reg_input]['passwd'] = reg_pwd2 print(''' 注册成功,请牢记你的用户信息,用户名 %s, 密码 %s''' %(reg_input, reg_pwd2)) with open('user.txt', 'wb') as f: pickle.dump(user, f) main() else: print("两次输入的密码不相同,请重新输入!") continue def login(): with open('user.txt', 'rb') as f: user = pickle.load(f) con = 0 cart =[] while True: user_input = input("请输入用户名:").strip() money = user[user_input]['money'] if user_input in user.keys(): if user[user_input]["lock"] == '1': print("%s 帐号已被锁定!" %user_input) continue while con < 3: user_passwd = input("请输入密码:").strip() user_pwd = user[user_input]['passwd'] if user_passwd == user_pwd: username = user_input print(''' 登陆成功!, 欢迎[ %s ]光临''' %username) while True: print(''' 1. 查询信息 2. 购买商品 3. 购物车 4. 充值金额 5. 退出程序 ''') system_input = input('请选择服务,输入数字编号:').strip() if system_input == '1': print(''' 个人信息: 用户名:[ %s ] 余额:[ %s ] ''' %(username,user[user_input]['money'])) elif system_input == '2': shoplist = [ ["三星 S7 ",5700], ["小米 5 ",2000], ["iPhone 6s ",4600], ["Mac Pro ",9300], ["iPad Pro ",5900], ["玛莎拉蒂 ",2900000], ] print('''商品编号 商品名称 价格''') for i,p in enumerate(shoplist): print('''%s %s %s ''' %(i, p[0], p[1])) while True: try: shop_input = input('请输入[ 购物编号 ], 返回请输入[ exit ]: ').strip() if shop_input.isdigit(): shop_input = int(shop_input) shop_money = shoplist[shop_input][1] if money > shop_money: money -= shop_money cart.append(shoplist[shop_input]) print(''' 添加商品[ %s ]至购物车,你的余额为[ %s ]'''%(shoplist[shop_input][0],money)) else: print(''' 你的余额不足,请充值后购买!''') elif shop_input == 'exit': break else: print(''' 请输入正确的商品编号!''') except IndexError: print(''' 请输入正确的商品编号!''') elif system_input == '3': if len(cart) > 0: print('''商品名称 价格''') for i,k in cart: print('''%s %s''' %(i,k)) while True: cart_input = input('结算请输入 [y], 退出请输入[n], 清空购物车请输入[e]') if cart_input == 'y': user[user_input]['money'] = money with open('user.txt', 'wb') as f: pickle.dump(user,f) cart = [] print(''' 购买成功!你的余额为 [%s]''' %user[user_input]['money'] ) break elif cart_input == 'n': break elif cart_input == 'e': cart = [] money = user[user_input]['money'] print(''' 购物车已清空!''' ) else: print('请输入正确的命令!') else: print(''' 你的购物车为空,请购买商品! ''') elif system_input == '4': money_input = input('请输入充值金额, 返回请输入[ exit ]: ').strip() if money_input.isdigit(): money_input = int(money_input) user[user_input]['money'] += money_input print(''' 充值后你的余额为:[ %s ] ''' %user[user_input]['money'] ) with open('user.txt', 'wb') as f: pickle.dump(user, f) elif money_input == 'exit': continue else: print(''' 输入有误,请正确输入! ''') elif system_input == '5': quit() else: print(''' 数字都不会选,请重新输入数字!''') else: con += 1 if con == 3: user[user_input]['lock'] = "1" with open('user.txt','wb') as f: pickle.dump(user, f) print("%s 帐号已经被锁定!" %user_input ) break print("密码错误, 错误三次将锁定帐号, 错误 %s 次" %con ) else: print("用户名不存在!") if __name__ == "__main__": main()