哥哥我又回来啦,哈哈··好久没来写博客了,现在慢慢把以前的都补上!最近在学习python,所以会更新一些学习中遇到的问题。
今天的内容是用python实现之前学习shell的时候写的一个简单脚本的功能:选择对应的菜单项,打印当前系统的状态信息。
不罗嗦了,上代码:
#!/bin/bash User () { echo "用户登录记录:" echo "`last`" } Ifcfg () { echo "本机网卡信息如下:" echo "`ifconfig`" } Netstat () { echo "http的并发请求数及其TCP连接状态:" echo "`netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'`" } Nfsstat () { echo " NFS 状态:" echo "`nfsstat -cn`" } System () { echo " 系统版本:" echo "`lsb_release -a`" } Disk () { echo " 磁盘分区使用情况:" echo "`df -h`" } IO () { echo " 磁盘I/O:" echo "`iostat -dx`" } Top () { echo " cpu、内存使用情况:" echo "`vmstat 5`" } PS3="请输入您的选择:" A="查看当前用户:查看当前网卡参数:查看http并发数:查看NFS状态:系统版本:磁盘分区使用情况:磁盘IO :cpu内存使用情况:退出脚本" && IFS=: select i in ${A};do case $i in 查看当前用户) User ;; 查看当前网卡参数) Ifcfg ;; 查看http并发数) Netstat ;; 查看NFS状态) Nfsstat ;; 系统版本) System ;; 磁盘分区使用情况) Disk ;; 磁盘IO) IO ;; cpu内存使用情况) Top ;; 退出脚本) exit 0 ;; *) echo "没有正确的选择"; exit 1;; esac done
python代码实现:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Filename: systemstatus.py
import os
# swich case 实现
# This class provides the functionality we want. You only need to look at
# this if you want to know how this works. It only needs to be defined
# once, no need to muck around with its internals.
class switch(object):
def __init__(self, value):
self.value = value
self.fall = False
def __iter__(self):
"""Return the match method once, then stop"""
yield self.match
raise StopIteration
def match(self, *args):
"""Indicate whether or not to enter a case suite"""
if self.fall or not args:
return True
elif self.value in args: # changed for v1.5, see below
self.fall = True
return True
else:
return False
def print_menu():
menu = {
1: "查看当前用户",
2: "查看当前网卡参数",
3: "查看http并发数",
4: "查看nfs状态",
5: "系统版本",
6: "磁盘分区使用情况",
7: "磁盘IO",
8: "cpu内存使用情况",
9: "打印这个菜单"
}
print('系统信息查看工具菜单:')
# 打印整个菜单
for i in menu:
print(i, menu[i])
return
lst = print_menu()
print(lst)
# while True 的部分实现了一个永远不会自己停止的循环。但是在循环内部的if语句中加入条件是可以的,在条件满足时调用break语句。
# 这样一来就可以早循环内部任何地方而不是只在开头(像普通的while循环一样)终止循环。
# if/break 语句自然地将循环分为两个部分:第一部分负责初始化(在普通的while循环中,这部分需要重复),第二部分则在循环条件
# 为真的情况下使用第一部分内初始化好的数据。
while True:
item = input('请输入菜单编号(1-9,留空退出程序):')
if not item: break
for case in switch(item):
if case('1'):
print('当前用户信息:')
os.system('last')
break
if case('2'):
print('当前网卡参数:')
os.system('ifconfig')
break
if case('3'):
print('http并发数:')
os.system("netstat -n | awk '/^tcp/ {++S[$NF]} END {for(a in S) print a, S[a]}'")
break
if case('4'):
print('nfs状态:')
os.system('nfsstat -cn')
break
if case('5'):
print('系统版本:')
os.system('lsb_release -a')
break
if case('6'):
print("磁盘分区使用情况")
os.system('df -h')
break
if case('7'):
print('磁盘IO:')
os.system('iostat -dx')
break
if case('8'):
print('cpu内存使用情况:')
os.system('vmstat 5')
break
if case('9'):
lst = print_menu( )
print(lst)
break
if case(''):
print("退出!")
exit(1)
转载于:https://blog.51cto.com/centilinux/1785778