哥哥我又回來啦,哈哈··好久沒來寫博客了,現在慢慢把以前的都補上!最近在學習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)