python3练习脚本

1.#利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法

#!/usr/bin/env python3
##去除字符串首尾空格
def trim():
    s = input ('请输入要处理的字符串: ') 
    for i in s:
        if i != ' ':
            start_idx = s.index(i)
            # print(start_idx)
            break
    
    for i in list(range(0,len(s)))[::-1]:
        w = s[i]
        if w != ' ':
            end_idx = i
            # print(end_idx)
            break
    print(s[start_idx:end_idx+1])
trim()

2.#判断一个用户是否存在

#!/usr/bin/env python3
##判断一个用户是否存在
def foo():
# 定义函数
    import subprocess
    # 导入模块
    while True:
        use = input('请输入要查询的用户,按q退出 :  ')
        user = use.strip()
        # 获取用户输入,并去除两端空格
        if not user:
            continue
        # 如果输入空,就重新开始新一轮的循环
        if user == 'q':
            break
        # 如果输入 q 就是跳出循环
        tmd = 'id '
        ret = subprocess.getstatusoutput( tmd + user)
        # 多元赋值
        code,result = ret
        # code 状态码,result 执行结果
        if code == 0:
            print ("用户存在")
        else:
            print("用户不存在")
foo()
# 调用函数
exit ("正在退出")

3.#输出目前系统中都监听了哪些端口

#!/usr/bin/env python3
## 输出目前系统中都监听了哪些端口
def foo():
# 定义函数
    port = []
    ports = []
    # 创建空列表
    import subprocess
    # 导入模块
    tmd = 'ss -ntal'
    ret = subprocess.getoutput(tmd)
    # 多元赋值
    for line in ret.splitlines():
        if line.startswith('LISTEN'):
            host_port = line.split()[3]
            get_port = host_port.split(':')[-1]
            # 通过if判断,并切出端口号
            port.append(get_port)
            for i in port:
                if i not in ports:
                    ports.append(i)
                    # 判断值是否存在ports中重复
    print('当前系统监听端口:', ports)
foo()
# 调用函数

4.#输入一个端口,判断服务是否开启

#!/usr/bin/env python3
def foo():
# 定义函数
    import subprocess
    # 导入模块
    while True:
        tmd = 'netstat -anpt | grep '
        ser = input('请输入要查询的服务端口,q退出:')
        if not ser:
            continue
        # 输入为空,重新开始循环
        if ser == 'q':
            break
        # 输入q 则跳出循环
        ret = subprocess.getstatusoutput(tmd + ser)
        # 多元赋值
        code,result = ret
        # code状态码,restlt执行结果
        if code == 0:
            print('服务已开启')
        else:
            print('服务未开启')
foo()
# 调用函数
exit('正在退出')

5.# 输出系统中所有的普通用户

#!/usr/bin/env python3
# 输出系统中所有的普通用户
def foo():
# 定义函数
    import subprocess
    # 调用函数
    tmd = 'cat /etc/passwd'
    ret = subprocess.getoutput(tmd)
    for i in ret.splitlines():
        user_list = i.split(':')[0:4:2]
        # 切出user和uid
        if int(user_list[1]) >= 1000:
        # 判断uid是否大于等于1000,是则输出
            print('普通用户:' + user_list[0])
foo()
# 调用函数

6.# 获取当前系统中非回环接口的 IPv4地址

#!/usr/bin/env  python3
# 获取当前系统中非回环接口的 IPv4地址
def foo():
# 定义函数
    import subprocess
    # 调用模块
    ips = []
    # 创建空列表
    tmd ='ip a'
    ret = subprocess.getoutput(tmd)
    # 多元赋值
    for line in ret.splitlines():
        if 'inet' in line and '127.0.0.1/8' not in line and 'inet6' not in line:
        # 过滤出ipv4元素
            n = line.split()[1]
            ips.append(n)
    print('ip地址为:')
    print(ips)
foo()
# 调用函数

7.#获取当前系统中 CPU 型号, 内核数量

#!/usr/bin/env python3
def foo():
# 定义函数
    import subprocess
    # 调用模块
    cmd = 'cat /proc/cpuinfo'
    ret = subprocess.getoutput(cmd)
    line_ret = ret.splitlines()
    # 通过回车分割,转换成列表
    for i in line_ret:
        if i.strip().startswith('model name'):
            cpu_type = i.strip().split(':')[1]
            # 判断元素是否以model name开头,并切片
        if i.strip().startswith('cpu cores'):
            cpu_num = i.strip().split(':')[1]
            # # 判断元素是否以cpu cores开头,并切片
    print("CPU型号:",cpu_type)
    print("内核数量:",cpu_num)
foo()
# 调用函数

8.#获取当前系统内存使用情况:总容量,可用容量

#!/usr/bin/env python3
# 获取当前系统内存使用情况:总容量,可用容量
def foo():
# 定义函数
    import subprocess
    # 调用模块
    tmd = 'free -m'
    ret = subprocess.getoutput(tmd)
    # 多元赋值
    for line in ret.splitlines():
        if line.startswith('Mem'):
        # 切出以Mem开头的元素
            total = line.split()[1]
            free = line.split()[3]
            print('当前系统内存总容量:' ,total )
            print('当前系统内存可以容量:', free )
foo()
# 调用函数

9.#获取当前系统的磁盘情况,每块磁盘的设备名称和总容量

#!/usr/bin/env python3
# 获取当前系统的磁盘情况,每块磁盘的设备名称和总容量
def foo():
# 定义函数
    import subprocess
    # 调用模块
    tmd = 'lsblk'
    ret = subprocess.getoutput(tmd)
    # 多元赋值
    disks = []
    # 创建空列表
    for line in ret.splitlines():
        if 'disk' in line:
        # 调出有disk的元素并准备切片
            disk_name = line.split()[0]
            disk_total = line.split()[3]
            disks.append([disk_name,disk_total])
    print('当前系统每块磁盘设备名称和容量为: ')        
    print(disks)
foo()
# 调用函数

10.#获取当前系统磁盘的有效分区情况,打印出挂载点和分区容量

#!/usr/bin/env python3
# 获取当前系统磁盘的有效分区情况,打印出挂载点和分区容量
def foo():
# 定义函数
    import subprocess
    # 调用模块
    tmd = 'df -Th'
    ret = subprocess.getoutput(tmd) 
    # 多元赋值
    name= []
    mount = []
    capacity = []
    # 创建新列表
    for i in ret.splitlines():
        name = i.split()[0]
        mount = i.split()[-1]
        capacity = i.split()[2]
        # 切出元素,放入列表
        print('%-30s %-10s %-10s' % (name,mount,capacity))
foo()
# 调用函数

11.#输出当前系统的 CPU 负载情况 1 ,5 ,15 分钟

#!/usr/bin/env python3
# 输出当前系统的 CPU 负载情况 1 ,5 ,15 分钟
def foo():
# 定义函数
    import subprocess
    # 调用模块
    tmd = 'uptime'
    ret = subprocess.getoutput(tmd)
    # 多元赋值
    load1 = ret.split(':')[-1].split(',')[0]
    load5 = ret.split(':')[-1].split(',')[1]
    load15 = ret.split(':')[-1].split(',')[2]
    # 切出1,5,15分钟CPU负载情况
    print('当前系统CPU 1分钟负载情况:' + load1)
    print('当前系统CPU 5分钟负载情况:' + load5)
    print('当前系统CPU 15分钟负载情况:' + load15)
foo()
# 调用函数

12.#将硬盘信息、内存信息,cup 信息,IP 地址信息,分别组合成小字典,之后再汇总一个大字典

#!/usr/bin/env python3
import subprocess
# 调用模块
bdict = {}
# 创建大字典
disk = {}
disk_list = {}
# 创建硬盘字典
tmd = 'lsblk'
ret = subprocess.getoutput(tmd)
for line in ret.splitlines():
    if 'disk' in line:
        disk_name = line.split()[0]
        disk_total = line.split()[3]
        # 切出硬盘信息
disk[disk_name] = disk_total
disk_list['硬盘'] = disk
# 将disk设为key'硬盘'的value

   
total = {}
free = {}
mem = {}
# 创建内存字典
tmd = 'free -h'
ret = subprocess.getoutput(tmd)
for line in ret.splitlines():
    if line.startswith('Mem'):
        mem_total = line.split()[1]
        mem_free = line.split()[3]
total['总量'] = mem_total
free['剩余'] = mem_free
mem['内存'] = total,free
# 将total和free设为mem的value(字典嵌套字典)


name = {}
number = {}
cpu = {}
# 创建cpu字典
tmd = 'cat /proc/cpuinfo'
ret = subprocess.getoutput(tmd)
line = ret.splitlines()
for i in line:
    if i.startswith('model name'):
        cpu_type = i.strip().split(':')[1]
    if i.startswith('cpu cores'):
        cpu_num = i.strip().split(':')[1]
    # 切出CPU型号和数量
name['型号'] = cpu_type
number['数量'] = cpu_num
cpu['CPU'] = name,number
# 将name和number设为cpu的value


ip_name = {}
ip_num = {}
ip = {}
# 创建IP字典
tmd = 'ip a'
ret = subprocess.getoutput(tmd)
for i in ret.splitlines():
    if 'ens' in i:
        line = i.strip()
        if line.startswith('inet'):
            ipn = line.split()[-1]
            ipm = line.split()[1]
        # 切出IP地址信息  
ip_name['名称'] = ipn
ip_num['地址'] = ipm
ip['IP'] = ipn,ipm
# 将ip_name和ip_num设为ip的value

bdict.update(disk_list)
bdict.update(mem)
bdict.update(ip)
bdict.update(cpu)
# 将小字典更新到大字典
for k,v in bdict.items():
    print(k,v)
# 循环打印出大字典的key和value

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
学习Python自动化脚本可以帮助你更高效地完成重复的任务。以下是一些学习Python自动化脚本的方法: 1. 阅读相关的教程和文档:可以通过阅读Python自动化脚本的教程和文档来了解基本的概念和语法。这些资源可以帮助你理解如何使用Python编写自动化脚本,并提供一些示例代码供你参考。 2. 参加在线课程或培训班:有许多在线课程和培训班提供Python自动化脚本的学习。这些课程通常会深入讲解Python自动化脚本的原理和实践,并提供实际项目来帮助你练习。 3. 练习编写自动化脚本:通过实际编写自动化脚本来提高你的技能。你可以选择一些简单的任务开始,例如自动化文件处理、网页爬虫或数据分析等。逐渐增加难度和复杂性,以提高你的编程能力。 4. 参考开源项目和社区资源:Python有一个活跃的开源社区,你可以参考一些开源项目和社区资源来学习Python自动化脚本的最佳实践。这些项目和资源通常提供了一些常见任务的示例代码和解决方案。 5. 实践项目:尝试将Python自动化脚本应用到实际项目中。选择一些你感兴趣或有需求的任务,例如自动化数据处理、自动化测试或自动化部署等。通过实践项目,你可以更好地理解Python自动化脚本的应用场景和技巧。 总之,学习Python自动化脚本需要不断的实践和探索。通过阅读教程、参加课程、练习编写脚本和参考开源项目,你可以逐步提高你的技能,并在实际项目中应用自动化脚本。\[1\]\[2\]\[3\] #### 引用[.reference_title] - *1* [6个实用的 Python 自动化脚本,告别加班,你学会了吗?](https://blog.csdn.net/Python4857/article/details/121631389)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [10个Python脚本来自动化你的日常任务](https://blog.csdn.net/qiqi1220/article/details/127238784)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值