Python练习(3)

文件练习:

  1. 生成一个大文件ips.txt,要求1200行,每行随机为172.25.254.0/24段的ip

  2. 读取ips.txt文件统计这个文件中ip出现频率排前10的ip

    import random
    
    def create_ip_file(filename):
        ip = ['172.25.254.' + str(i) for i in range(1,255)]
        # print(random.sample(ip,1))
        with open(filename,'a+') as f:
            for i in range(1200):
                f.write(random.sample(ip,1)[0] + '\n')
    
    def sorted_by_ip(filename,count=10):
        ips_dict = dict()
        with open(filename) as f:
            for ip in f:
                ip = ip.strip()
                if ip in ips_dict:
                    ips_dict[ip] += 1
                else:
                    ips_dict[ip] = 1
        sorted_ip = sorted(ips_dict.items(),key=lambda x:x[1],reverse=True)[:count]
    
        return sorted_ip
    
    print(sorted_by_ip('ips.txt'))
    

测试:

Python练习(3)_第1张图片
1. 在当前目录新建目录img, 里面包含100个文件, 100个文件名
各不相同(X4G5.png)
2. 将当前img目录所有以.png结尾的后缀名改为.jpg.

import random
import string
import os
from os.path import splitext
def gen_code(len=4):
    li = random.sample(string.ascii_letters + string.digits,len)
    return ''.join(li)
def create_files():
    li = [gen_code() for i in range(100)]
    os.mkdir('img')
    for i in li:
        os.mknod('img/' + i + '.png')
def modify_suffix(dirname,old_suffix,new_suffix):
    #找出以png结尾的文件名
    pngfile = filter(lambda filename:filename.endswith(old_suffix),os.listdir(dirname))

    #分离文件名和后缀
    basefiles = [os.path.splitext(filename)[0] for filename in pngfile]

    #文件重命名
    for filename in basefiles:
        oldname = os.path.join(dirname,filename + old_suffix)
        newname = os.path.join(dirname,filename + new_suffix)
        os.rename(oldname,newname)
        print('%s重命名为%s成功' %(oldname,newname))

modify_suffix('img','.png','.jpg')

测试:

Python练习(3)_第2张图片

时间转换练习

1.获取当前主机信息: 操作系统名, 主机名, 内核版本, 硬件架构
2.获取开机时长和开机时间
3.获取当前登录用户

		import os
		import psutil
		from datetime import datetime
		
		print('主机信息'.center(50,'*'))
		info = os.uname()
		
		print("""
		    操作系统: %s
		    主机名称: %s
		    内核版本: %s
		    硬件架构: %s
		"""%(info.sysname,info.nodename,info.release,info.machine))
		
		print('开机信息'.center(50,'*'))
		boot_time = psutil.boot_time()
		#将时间戳转换为datetime类型时间
		boot_time_obj = datetime.fromtimestamp(boot_time)
		
		now_time = datetime.now()
		
		delta_time = now_time - boot_time_obj
		
		print('开机时间:',boot_time_obj)
		print('当前时间:',str(now_time).split('.')[0])
		print('开机时长:',str(delta_time).split('.')[0])
		
		print('当前登录用户'.center(50,'*'))
		login_user = psutil.users()
		info = psutil.users()[0]
		print(info.name)

测试:

Python练习(3)_第3张图片

面向对象练习

1.小明体重75.0公斤
2.小明每次跑步会减肥0.5公斤
3.小明每次吃东西体重会增加1公斤

class People():

    def __init__(self,name,weight):
        self.name = name
        self.weight = weight

    def __str__(self):
        return '我的名字叫%s, 体重是 %.2f' %(self.name,self.weight)

    def run(self):
        print('%s选择跑步' %(self.name))
        self.weight -= 0.5

    def eat(self):
        print('%s选择吃东西' %(self.name))
        self.weight += 1

xiaoming = People('小明',75.0)
xiaoming.run()
print(xiaoming)
xiaoming.eat()
print(xiaoming)

测试:
Python练习(3)_第4张图片

1.房子有户型,总面积和家具名称列表
新房子没有任何的家具

2.家具有名字和占地面积,其中
床:占4平米
衣柜:占2平米
餐桌:占1.5平米
3.将以上三件家具添加到房子中
4.打印房子时,要求输出:户型,总面积,剩余面积,家具名称列表

class Furniture(object):

    def __init__(self,name,area):
        self.name = name
        self.area = area

    def __str__(self):
        return '[%s] 占地 %.2f平米' %(self.name,self.area)

class House(object):

    def __init__(self,type,area):
        self.type = type
        self.area = area
        self.free_area = area
        self.fur_list = []

    def __str__(self):
        return ('户型: %s\n总面积: %.2f平米[剩余: %.2f平米]\n家具: %s'
                %(self.type,self.area,self.free_area,self.fur_list))

    def add_fur(self,item):
        self.fur_list.append(item.name)
        self.free_area -= item.area

bed = Furniture('bed',4)
chest = Furniture('chest',2)
table = Furniture('table',1.5)

home = House('两室一厅',100)
home.add_fur(bed)
home.add_fur(chest)
home.add_fur(table)

print(home)

测试:
Python练习(3)_第5张图片

搭建ftp服务器

需先安装pip3

	from pyftpdlib.authorizers import DummyAuthorizer
	from pyftpdlib.handlers import FTPHandler,ThrottledDTPHandler
	from pyftpdlib.servers import FTPServer
	from pyftpdlib.log import LogFormatter
	import logging
	
	#记录日志到文件
	logger = logging.getLogger()
	logger.setLevel(logging.INFO)
	
	#定义handler
	h1 = logging.StreamHandler()
	h2 = logging.FileHandler(filename='ftpserver.log',encoding='utf-8')
	
	#定义日志格式
	h1.setFormatter(LogFormatter())
	h2.setFormatter(LogFormatter())
	
	#使用handler
	logger.addHandler(h1)   #输出到屏幕
	logger.addHandler(h2)   #输出到文件
	
	#实例化虚拟用户
	authorizer = DummyAuthorizer()
	
	authorizer.add_user('user1','123','/tmp/ftpuser',perm='elradfmw')
	
	#添加匿名用户
	authorizer.add_anonymous('/tmp/ftpuser')
	
	#初始化ftp句柄
	handler = FTPHandler
	handler.authorizer = authorizer
	
	#添加被动端口范围
	handler.passive_ports = range(4000,5000)
	
	#上传下载速度控制
	dtp_handler = ThrottledDTPHandler
	dtp_handler.read_limit = 50 * 1024
	dtp_handler.write_limit = 50 * 1024
	handler.dtp_handler = dtp_handler
	
	#监听ip和端口
	server = FTPServer(('0.0.0.0',21),handler)
	
	#最大连接数
	server.max_cons = 5
	#同一个ip最多只能连接2个
	server.max_cons_per_ip = 2
	
	server.serve_forever()

邮件发送

	import smtplib
	from email.mime.text import MIMEText
	from email.mime.multipart import MIMEMultipart
	from email.mime.image import MIMEImage
	from email.header import Header
	
	mail_host = 'smtp.qq.com'   #发件服务器
	mail_user = '381982550'     #用户名
	mail_pass = 'drmcqixpldyjbihd'  #授权码
	
	#发件人
	sender = '[email protected]'
	#收件人
	receivers = ['[email protected]','[email protected]']
	
	message = MIMEMultipart()
	
	message['From'] = sender
	message['To'] = ';'.join(receivers)
	message['Subject'] = '这是邮件主题, 测试邮件!'
	
	#邮件正文内容
	message.attach(MIMEText('

这是正文: 发送图片和附件

图片展示:

','html','utf-8')) #指定图片资源 Picture = open('redhat.jpg','rb') msgImage = MIMEImage(Picture.read()) Picture.close() #定义图片ID,在HTML文本中用 msgImage.add_header('Content-ID','') message.attach(msgImage) #添加文本附件 att1 = MIMEText(open('ftpserver.log','rb').read(),'base64','utf-8') att1['Content-Type'] = 'application/octet-stream' att1.add_header('Content-Disposition','attachment',filename=('utf-8','','warning.txt')) message.attach(att1) try: smtpObj = smtplib.SMTP() smtpObj.connect(mail_host,25) smtpObj.login(mail_user,mail_pass) smtpObj.sendmail(sender,receivers,message.as_string()) print('发送成功') except smtplib.SMTPException as e: print(f'发送失败,错误原因: {e}')

你可能感兴趣的:(Linux系统pyhton)