├── .gitignore ├── Game-GuessNumbers.py ├── Ops-CheckFileDifferences.py ├── Ops-CheckWebQuality.py ├── Ops-ConnMySQL.py ├── Ops-Smtplib.py ├── Ops-XlsxWriter.py ├── Ops-dnsRoundRobin.py ├── Ops-getLinuxSystemInfo.py ├── Ops-ipHandle.py ├── Program-After_tax_wages.py ├── README.md └── Reptile-zhaiquan.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | README.md 103 | -------------------------------------------------------------------------------- /Game-GuessNumbers.py: -------------------------------------------------------------------------------- 1 | #!python3 2 | #coding: utf-8 3 | 4 | import random 5 | 6 | print ('********* 猜数字游戏规则 *********\n' 7 | '系统生成4次1-30的随机整数,每个用户猜4次,' 8 | '猜对的次数越多,排名越靠前。\n' 9 | '猜完后输入1到下一位用户,' 10 | '输入0结束游戏并打印出排行榜。\n' 11 | '·作者:谢育政 · 版本:Python3.6·\n' 12 | '**********************************') 13 | 14 | names_num = {} # 猜中多少次,key为名字,value为变量count(猜中的次数)。 15 | zhiling = 1 # 指令,2代表猜对了,1代表没猜中。 16 | 17 | while (zhiling == 1): 18 | count = 0 # 猜中的次数 19 | name = str(input('请输入您的用户名:')) # 提示用户输入名字 20 | print ('############## 游戏开始 ##############') 21 | try: 22 | for i in range(1, 5): # 循环4次,代表每个用户有4次猜数字的机会 23 | num = int(random.randint(1, 2)) # 生成1-30的随机数 24 | input_num = int(input('猜一猜数字:')) # 用户输入数字 25 | if input_num == num: # 如果用户输入的数字等于生成的随机数,变量zhiling变为2,输出猜对了,并且猜中的次数+1 26 | zhiling = 2 27 | print('猜对了') 28 | count += 1 29 | elif input_num > num: # 如果用户输入的数字大于生成的随机数,输出太大了 30 | print('太大了') 31 | elif input_num < num: # 如果用户输入的数字小于生成的随机数,输出太小了 32 | print('太小了') 33 | names_num[name] = count # 把用户的名字和猜中的次数存入names_num字典 34 | if zhiling == 1: # 如果用户4次都没有猜中,输出没有猜对 35 | print ('【很遗憾您没有猜对】') 36 | if zhiling == 2: # 如果用户有猜中,输出用户猜对的次数 37 | print ('【您猜对了',count,'次】') 38 | zhiling = int(input('输入 1 继续玩,输入 0或其他 结束游戏并打印排行榜:')) 39 | except ValueError: # 当用户输入的不是数字,变量zhiling置于1,提示用户重新开始 40 | zhiling = 1 41 | print('************** 只能输入数字!请重新开始!!! **************\n') 42 | 43 | print('\n ----------排行榜 ----------') 44 | sorted_names_num = sorted(names_num.items(), key=lambda d:d[1], reverse=True) # 字典排序,对用户的成绩排序 45 | for key, value in dict(sorted_names_num).items(): # 打印排序后的排行榜 46 | print('\t【', key, '】猜对了', value, '次!') 47 | print('\n ---------------------------') 48 | 49 | -------------------------------------------------------------------------------- /Ops-CheckFileDifferences.py: -------------------------------------------------------------------------------- 1 | #!python3 2 | # coding: utf-8 3 | # 4 | 5 | ''' 6 | 有时我们无法确认备份与源目录文件是否保持一致,包括源目录中的新文件或目录、更新文件或目录有无成功同步,定期进行校验,没有成功则希望有针对性地进行补备份。 7 | 8 | 本例使用了filecmp模块的left_only、diff_files方法递归获取源目录的更新项,再通过shutil.copyfile、os.makedirs方法对更新项进行复制,最终保持一致状态。 9 | ''' 10 | 11 | 12 | import os 13 | import sys 14 | import filecmp 15 | import re 16 | import shutil 17 | holderlist=[] 18 | 19 | def compareme(dir1,dir2): #递归获取更新项函数 20 | dircomp = filecmp.dircmp(dir1,dir2) 21 | only_in_one = dircomp.left_only #源目录新文件或目录 22 | diff_in_one = dircomp.diff_files #不匹配文件,源目录文件已经发生变化 23 | dirpath = os.path.abspath(dir1) #定义源目录绝对路径 24 | [holderlist.append(os.path.abspath(os.path.join(dir1,x))) for x in only_in_one] 25 | [holderlist.append(os.path.abspath(os.path.join(dir1,x))) for x in diff_in_one] 26 | 27 | if len(dircomp.common_dirs) > 0: #判断是否存在相同子目录,以便递归 28 | for item in dircomp.common_dirs: #递归子目录 29 | compareme(os.path.abspath(os.path.join(dir1,item)), os.path.abspath(os.path.join(dir2,item))) 30 | return holderlist 31 | def checkargv(): 32 | if len(sys.argv) < 2: #要求输入源目录与备份目录 33 | print ("Usage: ", sys.argv[0], "datadir backupdir") 34 | sys.exit() 35 | else: 36 | dir1 = sys.argv[1] 37 | dir2 = sys.argv[2] 38 | source_files = compareme(dir1,dir2) #对比源目录与备份目录 39 | dir1 = os.path.abspath(dir1) 40 | 41 | if not dir2.endswith('/'): #备份目录路径加“/”符 42 | dir2 = dir2+'/' 43 | dir2 = os.path.abspath(dir2) 44 | destination_files = [] 45 | createdir_bool = False 46 | 47 | for item in source_files: #遍历返回的差异文件或目录清单 48 | destination_dir = re.sub(dir1,dir2,item) #将源目录差异路径清单对应替换成备份目录 49 | destination_files.append(destination_dir) 50 | if os.path.isdir(item): #如果差异路径为目录且不存在,则再备份目录中创建 51 | if not os.path.exists(destination_dir): 52 | os.makedirs(destination_dir) 53 | createdir_bool = True #再次调用compareme函数标记 54 | 55 | if createdir_bool: #重新调用compareme函数,重新遍历新创建目录的内容 56 | destination_files = [] 57 | source_files = [] 58 | source_files = compareme(dir1,dir2) #调用compareme函数 59 | for item in source_files: #获取源目录差异路径清单,对应替换成备份目录 60 | destination_dir = re.sub(dir1,dir2,item) 61 | destination_files.append(destination_dir) 62 | 63 | print ("update item: ") 64 | print (source_files) #输出更新项列表清单 65 | copy_pair = zip(source_files,destination_files) #讲源目录与备份目录文件清单拆分成元组 66 | for item in copy_pair: 67 | if os.path.isfile(item[0]): #判断是否为文件,是则进行复制操作 68 | shutil.copyfile(item[0], item[1]) 69 | 70 | if __name__ == '__main__': 71 | checkargv() 72 | -------------------------------------------------------------------------------- /Ops-CheckWebQuality.py: -------------------------------------------------------------------------------- 1 | #!python3 2 | #coding: utf-8 3 | 4 | ''' 5 | pycurl是一个用C语言写的libcurl Python实现,功能非常强大,支持的操作协议后FTP、HTTP、HTTPS、TELNET等,可以理解成Linux下curl命令功能的Python封装,简单易用 6 | 7 | 本例通过调用pycurl提供的方法,实现探测Web服务质量的情况,比如响应HTTP状态码、请求延时、HTTP头信息、下载速度等,利用这些信息可以定位服务响应慢的具体环节。 8 | ''' 9 | 10 | 11 | import sys,os 12 | import time 13 | import pycurl 14 | 15 | url = "http://fm.mykurol.com" #探测的目标URL 16 | c = pycurl.Curl() #创建一个Curl对象 17 | c.setopt(pycurl.URL,url) #定义请求的URL常量 18 | c.setopt(pycurl.CONNECTTIMEOUT,5) #定义请求连接的等待时间 19 | c.setopt(pycurl.TIMEOUT,5) #定义请求超时时间 20 | c.setopt(pycurl.NOPROGRESS,1) #屏蔽下载进度条 21 | c.setopt(pycurl.FORBID_REUSE,1) #完成交互后强制断开连接,不重用 22 | c.setopt(pycurl.MAXREDIRS,1) #指定HTTP重定向的最大数为1 23 | c.setopt(pycurl.DNS_CACHE_TIMEOUT,30) #设置保存DNS信息的时间为30秒 24 | #创建一个文件对象,以"web"方式打开,用来存储返回的http头部及页面内容 25 | indexfile = open(os.path.dirname(os.path.realpath(__file__))+"/content.txt","wb") 26 | c.setopt(pycurl.WRITEHEADER, indexfile) #将返回的HTTP HEADER定向到indexfile文件 27 | c.setopt(pycurl.WRITEDATA, indexfile) #将返回的HTML内容定向到indexfile文件对象 28 | try: 29 | c.perform() 30 | except Exception as e: 31 | print ("connection error:"+str(e)) 32 | indexfile.close() 33 | c.close() 34 | sys.exit() 35 | 36 | NAMELOOKUP_TIME = c.getinfo(c.NAMELOOKUP_TIME) #获取DNS解析时间 37 | CONNECT_TIME = c.getinfo(c.CONNECT_TIME) #获取建立连接时间 38 | PRETRANSFER_TIME = c.getinfo(c.PRETRANSFER_TIME) #获取从建立连接到准备传输所消耗的时间 39 | STARTTRANSFER_TIME = c.getinfo(c.STARTTRANSFER_TIME) #获取从建立连接到传输开始消耗的时间 40 | TOTAL_TIME = c.getinfo(c.TOTAL_TIME) #获取传输的总时间 41 | HTTP_CODE = c.getinfo(c.HTTP_CODE) #获取HTTP状态码 42 | SIZE_DOWNLOAD = c.getinfo(c.SIZE_DOWNLOAD) #获取下载数据包的大小 43 | HEADER_SIZE = c.getinfo(c.HEADER_SIZE) #获取HTTP头部大小 44 | SPEED_DOWNLOAD = c.getinfo(c.SPEED_DOWNLOAD) #获取平均下载速度 45 | #打印输出相关数据 46 | print ("HTTP状态码:%s" % (HTTP_CODE)) 47 | print ("DNS解析时间:%.2f ms" % (NAMELOOKUP_TIME*1000)) 48 | print ("建立连接时间:%.2f ms" % (CONNECT_TIME*1000)) 49 | print ("准备传输时间:%.2f ms" % (PRETRANSFER_TIME*1000)) 50 | print ("传输开始时间:%.2f ms" % (STARTTRANSFER_TIME*1000)) 51 | print ("传输结束总时间:%.2f ms" % (TOTAL_TIME*1000)) 52 | print ("下载数据包大小:%d bytes/s" % (SIZE_DOWNLOAD)) 53 | print ("HTTP头部大小:%d bytes/s" % (HEADER_SIZE)) 54 | print ("平均下载速度:%d bytes/s" % (SPEED_DOWNLOAD)) 55 | #关闭文件及curl对象 56 | indexfile.close() 57 | c.close() -------------------------------------------------------------------------------- /Ops-ConnMySQL.py: -------------------------------------------------------------------------------- 1 | #!python3 2 | # coding: utf-8 3 | # 4 | 5 | '''连接mysql数据库并执行SQL语句''' 6 | 7 | import os,sys 8 | import pymysql 9 | try: 10 | conn = pymysql.connect(host='localhost',user='root',passwd='',db='db_student') 11 | except Exception as e: 12 | print (e) 13 | sys.exit() 14 | cursor = conn.cursor() 15 | sql = "select * from stu_inf" 16 | cursor.execute(sql) 17 | data = cursor.fetchall() 18 | if data: 19 | for x in data: 20 | print (x[0],x[1],x[2],x[3],x[4],x[5]) 21 | cursor.close() 22 | conn.close()​ -------------------------------------------------------------------------------- /Ops-Smtplib.py: -------------------------------------------------------------------------------- 1 | #!python 2 | # -*- coding: UTF-8 -*- 3 | 4 | ''' 5 | SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,它是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。 6 | python的smtplib提供了一种很方便的途径发送电子邮件。它对smtp协议进行了简单的封装。 7 | 8 | ''' 9 | 10 | 11 | import smtplib 12 | from email.mime.text import MIMEText 13 | from email.header import Header 14 | 15 | # 第三方 SMTP 服务 16 | mail_host = "smtp.163.com" # 设置smtp服务器,例如:smtp.163.com 17 | mail_user = "******@163.com" # 用户名 18 | mail_pass = "****" # 口令 19 | 20 | sender = '******@163.com' # 发送邮件 21 | receivers = '******@qq.com' # 接收邮件 22 | 23 | message = MIMEText('This is a Python Test Text') 24 | message['From'] = sender 25 | message['To'] = receivers 26 | 27 | subject = 'One Test Mail' 28 | message['Subject'] = Header(subject) 29 | 30 | try: 31 | smtpObj = smtplib.SMTP() 32 | smtpObj.connect(mail_host, 25) # 25 为 SMTP 端口号 33 | smtpObj.login(mail_user, mail_pass) 34 | smtpObj.sendmail(sender, receivers, message.as_string()) 35 | print ("邮件发送成功") 36 | except smtplib.SMTPException as e: 37 | print ("Error: 无法发送邮件"+str(e)) -------------------------------------------------------------------------------- /Ops-XlsxWriter.py: -------------------------------------------------------------------------------- 1 | #!python3 2 | # coding: utf-8 3 | 4 | ''' 5 | 利用Python操作Excel的模块XlsxWriter,可以操作多个工作表的文字、数字、公式、图表等。 6 | XlsxWriter模块具有以下功能: 7 | 100%兼容的Excel XLSX文件,支持Excel 2003、Excel 2007等版本; 8 | 支持所有Excel单元格数据格式; 9 | 单元格合并、批注、自动筛选、丰富多格式字符串等; 10 | 支持工作表PNG、JPEG图像,自定义图表; 11 | 内存优化模式支持写入大文件。 12 | ''' 13 | 14 | ''' 此例实现插入文字(中英字符)、数字(求和计算)、图片、单元格格式等 ''' 15 | 16 | import xlsxwriter 17 | 18 | workbook = xlsxwriter.Workbook('test.xlsx') # 创建一个Excel文件 19 | 20 | worksheet = workbook.add_worksheet() # 创建一个工作表对象 21 | 22 | worksheet.set_column('A:A', 20) # 设定第一列(A)宽度为20像素 23 | bold = workbook.add_format({'bold': True}) # 定义一个加粗的格式对象 24 | 25 | worksheet.write('A1', 'Hello') # A1单元格写入'Hello' 26 | worksheet.write('A2', 'World', bold) # A2单元格写入'World'并引用加粗格式对象bold 27 | worksheet.write('B2', u'中文测试', bold) # B2单元格写入中文并引用加粗格式对象bold 28 | 29 | worksheet.write(2, 0, 32) # 用行列表示法写入数字'32'与'35.5' 30 | worksheet.write(3, 0, 35.5) # 行列表示法的单元格下标以0作为起始值,'3,0'等价于'A3' 31 | worksheet.write(4, 0, '=SUM(A3:A4)') # 求A3:A4的和,并将结果写入'4,0',即'A5' 32 | 33 | # worksheet.insert_image('B5', 'img/python-logo.png') # 在B5单元格插入图片 34 | workbook.close() # 关闭Excel文件 35 | -------------------------------------------------------------------------------- /Ops-dnsRoundRobin.py: -------------------------------------------------------------------------------- 1 | #!python3 2 | #coding=utf-8 3 | 4 | ''' 5 | 大部分的DNS解析是一个域名对应一个IP地址,但是通过DNS轮循技术可将一个域名对应多个IP地址,这样可以实现简单且高效的负载平衡,但是轮循技术有一个缺点就是当目标主机不可用时,不能自动的删除,所以引出了要对业务主机的服务的可用性进行监控。 6 | 7 | #本例通过分析当前域名的解析IP,再结合服务端口探测来实现自动监控,在域名解析中添加、删除IP时,无须对监控脚步更改。 8 | ''' 9 | 10 | 11 | import dns.resolver 12 | import os 13 | import http.client 14 | 15 | iplist=[] #定义域名IP列表变量 16 | appdomain="www.google.cn" #定义业务域名 17 | 18 | def get_iplist(domain=""): #域名解析函数,解析成功IP将被追加到iplist 19 | try: 20 | A = dns.resolver.query(domain, 'A') #解析A记录类型 21 | except Exception as e: 22 | print ("dns resolver error: ")+str(e) 23 | return 24 | for i in A.response.answer: 25 | for j in i.items: 26 | iplist.append(j.address) #追加到iplist 27 | return True 28 | 29 | def checkip(ip): 30 | checkurl = ip+":80" 31 | getcontent = "" 32 | http.client.socket.setdefaulttimeout(5) #定义http连接超时时间(5秒) 33 | conn = http.client.HTTPConnection(checkurl) #创建http连接对象 34 | 35 | try: 36 | conn.request("GET", "/", headers = {"Host": appdomain}) #发起url请求,添加host主机头 37 | 38 | r = conn.getresponse() 39 | getcontent = r.read(15) #获取url页面前15个字符,以便做可用性校验 40 | finally: 41 | if getcontent == "": #监控URL页的内容一般是事先定义好的,比如"HTTP200"等 42 | 43 | print (ip+" [OK]") 44 | else: 45 | print (ip+" [Error]") #此处可放告警程序,可以是邮件、短信通知 46 | 47 | if __name__ == "__main__": 48 | if get_iplist(appdomain) and len(iplist)>0: #条件:域名解析正确且至少返回一个IP 49 | for ip in iplist: 50 | checkip(ip) 51 | else: 52 | print ("dns resolver error.") -------------------------------------------------------------------------------- /Ops-getLinuxSystemInfo.py: -------------------------------------------------------------------------------- 1 | #!python2 2 | # encoding: utf-8 3 | 4 | ''' 5 | 收集主机的信息: 6 | 主机名称、IP、系统版本、服务器厂商、型号、序列号、CPU信息、内存信息 7 | ''' 8 | 9 | from subprocess import Popen, PIPE 10 | import os, sys 11 | 12 | ''' 获取 ifconfig 命令的输出 ''' 13 | def getIfconfig(): 14 | p = Popen(['ifconfig'], stdout=PIPE) 15 | data = p.stdout.read() 16 | return data 17 | 18 | 19 | ''' 获取 dmidecode 命令的输出 ''' 20 | def getDmi(): 21 | p = Popen(['dmidecode'], stdout=PIPE) 22 | data = p.stdout.read() 23 | return data 24 | 25 | 26 | ''' 根据空行分段落 返回段落列表''' 27 | def parseData(data): 28 | parsed_data = [] 29 | new_line = '' 30 | data = [i for i in data.split('\n') if i] 31 | for line in data: 32 | if line[0].strip(): 33 | parsed_data.append(new_line) 34 | new_line = line + '\n' 35 | else: 36 | new_line += line + '\n' 37 | parsed_data.append(new_line) 38 | return [i for i in parsed_data if i] 39 | 40 | 41 | ''' 根据输入的段落数据分析出ifconfig的每个网卡ip信息 ''' 42 | def parseIfconfig(parsed_data): 43 | dic = {} 44 | parsed_data = [i for i in parsed_data if not i.startswith('lo')] 45 | for lines in parsed_data: 46 | line_list = lines.split('\n') 47 | devname = line_list[0].split()[0] 48 | macaddr = line_list[0].split()[-1] 49 | ipaddr = line_list[1].split()[1].split(':')[1] 50 | break 51 | dic['ip'] = ipaddr 52 | return dic 53 | 54 | 55 | ''' 根据输入的dmi段落数据 分析出指定参数 ''' 56 | def parseDmi(parsed_data): 57 | dic = {} 58 | parsed_data = [i for i in parsed_data if i.startswith('System Information')] 59 | parsed_data = [i for i in parsed_data[0].split('\n')[1:] if i] 60 | dmi_dic = dict([i.strip().split(':') for i in parsed_data]) 61 | dic['vender'] = dmi_dic['Manufacturer'].strip() 62 | dic['product'] = dmi_dic['Product Name'].strip() 63 | dic['sn'] = dmi_dic['Serial Number'].strip() 64 | return dic 65 | 66 | 67 | ''' 获取Linux系统主机名称 ''' 68 | def getHostname(): 69 | with open('/etc/sysconfig/network') as fd: 70 | for line in fd: 71 | if line.startswith('HOSTNAME'): 72 | hostname = line.split('=')[1].strip() 73 | break 74 | return {'hostname': hostname} 75 | 76 | 77 | ''' 获取Linux系统的版本信息 ''' 78 | def getOsVersion(): 79 | with open('/etc/issue') as fd: 80 | for line in fd: 81 | osver = line.strip() 82 | break 83 | return {'osver': osver} 84 | 85 | 86 | ''' 获取CPU的型号和CPU的核心数 ''' 87 | def getCpu(): 88 | num = 0 89 | with open('/proc/cpuinfo') as fd: 90 | for line in fd: 91 | if line.startswith('processor'): 92 | num += 1 93 | if line.startswith('model name'): 94 | cpu_model = line.split(':')[1].strip().split() 95 | cpu_model = cpu_model[0] + ' ' + cpu_model[2] + ' ' + cpu_model[-1] 96 | return {'cpu_num': num, 'cpu_model': cpu_model} 97 | 98 | 99 | ''' 获取Linux系统的总物理内存 ''' 100 | def getMemory(): 101 | with open('/proc/meminfo') as fd: 102 | for line in fd: 103 | if line.startswith('MemTotal'): 104 | mem = int(line.split()[1].strip()) 105 | break 106 | mem = '%.f' % (mem / 1024.0) + ' MB' 107 | return {'Memory': mem} 108 | 109 | 110 | if __name__ == '__main__': 111 | dic = {} 112 | data_ip = getIfconfig() 113 | parsed_data_ip = parseData(data_ip) 114 | ip = parseIfconfig(parsed_data_ip) 115 | 116 | data_dmi = getDmi() 117 | parsed_data_dmi = parseData(data_dmi) 118 | dmi = parseDmi(parsed_data_dmi) 119 | 120 | hostname = getHostname() 121 | osver = getOsVersion() 122 | cpu = getCpu() 123 | mem = getMemory() 124 | 125 | dic.update(ip) 126 | dic.update(dmi) 127 | dic.update(hostname) 128 | dic.update(osver) 129 | dic.update(cpu) 130 | dic.update(mem) 131 | 132 | ''' 将获取到的所有数据信息并按简单格式对齐显示 ''' 133 | for k, v in dic.items(): 134 | print '%-10s:%s' % (k, v) -------------------------------------------------------------------------------- /Ops-ipHandle.py: -------------------------------------------------------------------------------- 1 | #!python2 2 | #coding=utf-8 3 | 4 | ''' 5 | IPy模块可以很好的辅助我们高效完成IP的规划工作。 6 | 7 | 此例根据输入的IP或子网返回网络、掩码、广播、反向解析、子网数、IP类型等信息 8 | ''' 9 | 10 | from IPy import IP 11 | import sys 12 | reload(sys) 13 | sys.setdefaultencoding('utf-8') 14 | ip_test = raw_input('请输入IP地址或网段地址:') 15 | ips = IP(ip_test) 16 | if len(ips) > 1: 17 | print ('网络地址:%s' % ips.net()) 18 | print ('掩码:%s' % ips.netmask()) 19 | print ('网络广播地址:%s' % ips.broadcast()) 20 | print ('地址反向解析:%s' % ips.reverseNames()) 21 | print ('网络子网数:%s' % len(ips)) 22 | else: 23 | print ('IP反向解析 %s' % ips.reverseNames()) 24 | print ('此IP地址转换成十六进制: %s' % ips.strHex()) 25 | print ('此IP地址转换成二进制: %s' % ips.strBin()) 26 | print ('此IP地址类型: %s' % ips.iptype()) 27 | -------------------------------------------------------------------------------- /Program-After_tax_wages.py: -------------------------------------------------------------------------------- 1 | #!python3 2 | #coding=utf-8 3 | 4 | # 计算税后收入 5 | 6 | wages = float(input("请输入您的税前工资:")) 7 | iit = 0 8 | if (wages > 3500): 9 | if (3500 < wages <= 4500): 10 | iit = (wages - 3500) * 0.03 11 | elif (4500 < wages <= 8000): 12 | iit = (wages - 4500) * 0.1 + 1500 * 0.03 13 | elif (8000 < wages <= 12500): 14 | iit = (wages - 8000) * 0.2 + 3000 * 0.1 + 1500 * 0.03 15 | elif (12500 < wages <= 38500): 16 | iit = (wages - 12500) * 0.25 + 4500 * 0.2 + 3000 * 0.1 + 1500 * 0.03 17 | elif (38500 < wages <= 58500): 18 | iit = (wages - 38500) * 0.3 + 26000 * 0.25 + 4500 * 0.2 + 3000 * 0.1 + 1500 * 0.03 19 | elif (58500 < wages <= 83500): 20 | iit = (wages - 58500) * 0.35 + 20000 * 0.3 + 26000 * 0.25 + 4500 * 0.2 + 3000 * 0.1 + 1500 * 0.03 21 | elif (wages > 83500): 22 | iit = (wages - 83500) * 0.45 + 25000 * 0.35 + 20000 * 0.3 + 26000 * 0.25 + 4500 * 0.2 + 3000 * 0.1 + 1500 * 0.03 23 | 24 | reali = wages - iit 25 | print ("需要缴纳个人所得税:", iit, "扣除税后的实际个人收入:" ,reali) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # python-code 2 | The code of Python. 3 | 4 | @@ [我的个人博客] http://www.mykurol.com 5 | 6 | 7 | 猜数字小游戏: 8 | Game-GuessNumbers.py 9 | 10 | 计算税后工资: 11 | Program-After_tax_wages.py 12 | 13 | Excel操作数据报表: 14 | Ops-XlsxWriter.py 15 | 16 | 电子邮件SMTP: 17 | Ops-Smtplib.py 18 | 19 | DNS域名轮循业务监控: 20 | Ops-dnsRoundRobin.py 21 | 22 | ip地址处理: 23 | Ops-ipHandle.py 24 | 25 | 收集Linux系统信息: 26 | Ops-getLinuxSystemInfo.py 27 | 28 | pyMySQL连接: 29 | Ops-ConnMySQL.py 30 | 31 | 探测Web服务质量: 32 | Ops-CheckWebQuality.py 33 | 34 | 校验源与备份目录差异: 35 | Ops-CheckFileDifferences.py 36 | 37 | 爬取债券网站数据: 38 | Reptile-zhaiquan.py 39 | -------------------------------------------------------------------------------- /Reptile-zhaiquan.py: -------------------------------------------------------------------------------- 1 | #!python3 2 | #coding:utf-8 3 | 4 | ''' 5 | ################################ 6 | @ MyBlog: blog.csdn.net/hjxzt1 7 | www.mykurol.com 8 | github: https://github.com/kurolz 9 | ################################ 10 | 11 | 爬取集思录网站债券数据 12 | 目前可存为txt或xlsx两种格式 13 | 超过定义的涨幅或跌幅,可邮件通知 14 | #### 请填写发送的邮箱密码 #### 15 | ''' 16 | 17 | 18 | 19 | '''邮件通知''' 20 | def sendMail(id,uplift): 21 | import smtplib 22 | from email.mime.text import MIMEText 23 | from email.header import Header 24 | 25 | # 第三方 SMTP 服务 26 | mail_host = "smtp.163.com" # 设置smtp服务器,例如:smtp.163.com 27 | mail_user = "kurolz@163.com" # 发送的邮箱用户名 28 | mail_pass = "******" # 发送的邮箱密码 29 | 30 | sender = 'kurolz@163.com' # 发送的邮箱 31 | receivers = 'kurolz@163.com' # 接收的邮箱 32 | if uplift < format(0, '.0%'): # uplift为涨幅或跌幅 33 | text = '债券代码:' + id + ', 跌幅为:' + uplift 34 | else: 35 | text = '债券代码:' + id + ', 涨幅为:' + uplift # 发送的文本 36 | message = MIMEText(text) 37 | message['From'] = sender 38 | message['To'] = receivers 39 | 40 | subject = text 41 | message['Subject'] = Header(subject) 42 | 43 | try: 44 | smtpObj = smtplib.SMTP() 45 | smtpObj.connect(mail_host, 25) # 25 为 SMTP 端口号 46 | smtpObj.login(mail_user, mail_pass) # login 47 | smtpObj.sendmail(sender, receivers, message.as_string()) # 发送邮件 48 | print("邮件发送成功") 49 | except smtplib.SMTPException as e: 50 | print("Error: 无法发送邮件" + str(e)) 51 | 52 | '''当债券涨幅超过定义的limit值时,发送邮件通知''' 53 | def limitsendMail(limit,i,data): 54 | if limit < 0: 55 | if data < format(0, '.0%'): 56 | limit = format(limit, '.3%') 57 | if data.split('-')[1] > limit.split('-')[1]: 58 | sendMail(i, data) 59 | else: 60 | limit = format(limit, '.0%') 61 | if data > limit: 62 | sendMail(i, data) 63 | 64 | '''定义抓取数据的行''' 65 | def data_row(): 66 | jisilu_id = [] # 要爬取的债券代码 67 | p = 0 # 可选,0为取双行,-1为取单行 68 | 69 | while True: 70 | try: 71 | p += 2 # 可选,2为取单双行,1位取所有行 72 | p = str(p) # 转换为str,用于抓取数据 73 | element = driver.find_element_by_xpath('//*[@id="flex3"]/tbody/tr['+ p +']') 74 | data_id = element.get_attribute("id") # 抓取所有需要爬取的债券代码 75 | p = int(p) # 转换为int,维持增量循环 76 | except: 77 | break 78 | jisilu_id.append(data_id) 79 | return jisilu_id 80 | 81 | '''定义抓取数据的列''' 82 | def data_colum(): 83 | c = [] # 存储要抓取的列 84 | for num in range(1,24): 85 | c.append(str(num)) 86 | # 删除三个无关数据的列 87 | del c[20] 88 | del c[12] 89 | del c[11] 90 | return c 91 | 92 | '''定义爬取的操作''' 93 | try: 94 | from selenium import webdriver 95 | import ssl 96 | 97 | html = 'https://www.jisilu.cn/data/cbnew/#tlink_3' # 定义爬取的网站 98 | ssl._create_default_https_context = ssl._create_unverified_context # 取消证书认证 99 | try: 100 | driver = webdriver.PhantomJS() 101 | driver.get(html) 102 | driver.implicitly_wait(3) # 等待3秒 103 | except: 104 | print ('请安装phantomjs') 105 | 106 | except ImportError: 107 | print ('No module named selenium. 请安装selenium模块') 108 | 109 | 110 | '''抓取数据''' 111 | a = {} # 存储数据,存储格式:a = {债券代码:{title:data,title:data, ...}, ...} 112 | for i in data_row(): 113 | b = {} # 存储格式:b = {title:data, ...} 114 | for lie in data_colum(): 115 | title = driver.find_element_by_xpath('//*[@id="flex3"]/thead/tr[2]/th['+lie+']').text # 抓取title 116 | data = driver.find_element_by_xpath('//*[@id='+i+']/td['+lie+']').text # 抓取数值 117 | title = title.replace("\n", "") # 去掉title中的换行符 118 | b[title] = data 119 | if lie == "4": 120 | limitsendMail(0.05, i, data) 121 | a[i] = b 122 | 123 | 124 | '''数据输出保存''' 125 | class print_data(object): 126 | def __init__(self, filename): 127 | self.filename = filename 128 | 129 | '''输出到TXT''' 130 | def printTxt(self): 131 | import time 132 | with open(self.filename, 'ab+') as w: 133 | nowtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) 134 | w.write(("\n@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ " + nowtime + " @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n").encode()) 135 | w.close() 136 | for key in a: 137 | for key2 in a[key]: 138 | with open(self.filename, 'ab+') as w: 139 | w.write((key2 + ":" + a[key][key2] + ",").encode('utf-8')) 140 | w.close() 141 | with open(self.filename, 'ab+') as w: 142 | w.write(("\n").encode()) 143 | w.close() 144 | 145 | '''输出到Xlsx''' 146 | def printXlsx(self): 147 | try: 148 | import xlsxwriter 149 | workbook = xlsxwriter.Workbook(self.filename) # 创建一个Excel文件 150 | worksheet = workbook.add_worksheet() # 创建一个工作表对象 151 | 152 | colum_len = '' 153 | for key in a: 154 | colum_len = key 155 | if colum_len != '': 156 | break 157 | 158 | '''写入title''' 159 | colum_num = 0 160 | while (colum_num < len(a[colum_len].keys())): 161 | for i in list(a[colum_len].keys()): 162 | worksheet.write(0, colum_num, i) # 写入行列表示法的单元格 163 | colum_num += 1 164 | 165 | '''写入数值''' 166 | row_num = 1 167 | colum_num_2 = 0 168 | while (colum_num_2 < len(a[colum_len].keys())): 169 | for key in a: 170 | colum_num_2 = 0 171 | for key2 in a[key]: 172 | worksheet.write(row_num, colum_num_2, a[key][key2]) # 写入行列表示法的单元格 173 | colum_num_2 += 1 174 | row_num += 1 175 | 176 | except ImportError: 177 | print ('No module named xlsxwriter,输出为xlsx文件需要安装xlsxwriter模块,或重新定义输出为txt文件') 178 | 179 | if __name__ == "__main__": 180 | printfilename = '07150240-2.xlsx' 181 | file = print_data(printfilename) 182 | if printfilename.split('.')[1] == 'xlsx': 183 | file.printXlsx() 184 | elif printfilename.split('.')[1] == 'txt': 185 | file.printTxt() 186 | else: 187 | print ('输出文件名定义错误,无法输出,只能为xlsx或txt格式') 188 | --------------------------------------------------------------------------------