2017-05-01 3 views
0

以下のスクリプトを作成しました。このスクリプトは、Linuxシステム用に定義されたファイルシステムの使用法を提供します。私は、それが単純にFSが90%以上であり、正常に動作しているということを上回っている場合、ステータスを確認するためのしきい値を設定しました。したがって、閾値90または100の後に来るものは、単にit's more than 90%と表示されます。if条件の値を取得してPythonの変数に格納する方法

今のところ私はif条件から取得した実際の値を入れたいと思っていますが、どういうわけかこの時点では取得できません。 それで、知りたい、How to get the value of if condition and store in a variable in python。 は、これに関するヘルプやスクリプトの変更を感謝します。

import subprocess 
import socket 
threshold = 90 
hst_name = (socket.gethostname()) 

def fs_function(usage): 
    return_val = None 
    try: 
     return_val = subprocess.Popen(['df', '-Ph', usage], stdout=subprocess.PIPE) 
    except IndexError: 
     print "Mount point not found." 
    return return_val 

def show_result(output, mount_name): 
    if len(output) > 0: 
     for x in output[1:]: 
     if int(x.split()[-2][:-1]) >= threshold: 
      print "Service Status: Filesystem For " + mount_name + " is not normal & it's more than " + str(threshold) + "% on the host",hst_name 
     else: 
      print "Service Status: Filesystem For " + mount_name + " is normal on the host",hst_name 


def fs_main(): 
    rootfs = fs_function("/") 
    varfs = fs_function("/var") 
    tmPfs = fs_function("/tmp") 

    output = rootfs.communicate()[0].strip().split("\n") 
    show_result(output, "root (/)") 

    output = varfs.communicate()[0].strip().split("\n") 
    show_result(output, "Var (/var)") 

    output = tmPfs.communicate()[0].strip().split("\n") 
    show_result(output, "tmp (/tmp)") 
fs_main() 

上記のスクリプトは、以下のような出力に含まを与える:

Service Status: Filesystem For root (/) is not normal & it's more than 90% on the host noi-karn 
Service Status: Filesystem For Var (/var) is normal on the host noi-karn 
Service Status: Filesystem For tmp (/tmp) is normal on the host noi-karn 
+0

あなたは 'int型(x.split()[ - 2] [: - 1])の結果にアクセスできるようにしたいわけ'?次に、テストする前に変数*に入れて、変数を再利用してください。 –

+0

@MartijnPietersはい、正しいです。私は試してみましたが、どういうわけか、それをロジックに正しくフィットさせる方法に焦点を当てていません。 – rocky1981

答えて

1

ただ、変数最初int(x.split()[-2][:-1])式の結果を置く:

for x in output[1:]: 
    perc = int(x.split()[-2][:-1]) 
    if perc >= threshold: 
     # ... 

あなたはホイールの再発明を避けることができます。優れたpsutil projectは、すでにディスク統計情報を読んでサポートしています。

import psutil 

status_normal = "normal" 
status_abnormal = "not normal & it's more than {}%".format(threshold) 
for partition in psutil.disk_partitions(): 
    usage = psutil.disk_usage(partition.mountpoint) 
    status = status_abnormal if usage.percent > threshold else status_normal 
    print "Filesystem For {} is {} on the host {}".format(
     partition.mountpoint, status, hst_name) 
+0

ガイダンスとpsutilと一緒に動く別の提案に感謝します。しかし、私はこのメソッドを使う理由のいくつかの制限のために、そのpsutilを私の環境に使用することができません。 – rocky1981

関連する問題