Python 使用paramiko获取Linux远程端电脑挂载空间使用情况
安装paramiko
pip install paramiko
代码演示
import json as JSON import re import paramiko import suds from suds.wsse import *
class LinuxMntListen(): """Linux系统""" def getSpaceInfo(self, P_IP, P_Port, P_User, P_Password): """ 获取Linux挂载空间使用情况 :return: """ IP = P_IP Port = int(P_Port) User = P_User Password = P_Password # 初始化返回数据格式 Ret = {"code": "0", "msg": "OK", "data": []} try: # 创建SSHClient对象 SSHCli = paramiko.SSHClient() # 允许将信任的主机自动保存到“known_hosts”文件中,此方法必须放在connect方法的前面 # SSHCli.load_system_host_keys() SSHCli.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 开始连接 SSHCli.connect(IP, Port, User, Password, timeout=10) except Exception as e: Ret["code"] = "-1" Ret["msg"] = "目标服务器" + IP + "连接失败!" + str(e) return JSON.dumps(Ret, ensure_ascii=False) # 指定查看的挂载列表 # MntList = ['/','/stand','/var','/usr','/tmp','/opt','/home','/cachesys','/journal','/wij','/dthealth','/backup','/data'] MntList = ['/', '/dev', '/dev/shm', '/run', '/sys/fs/cgroup', '/home', '/boot', '/journal', '/wij', '/data', '/cachesys', '/backup', '/dthealth', '/run/user/0'] Data = [] for Mnt in MntList: # 执行命令 Cmd = "df -lh " stdin, stdout, stderr = SSHCli.exec_command(Cmd + Mnt) try: OutStr = stdout.read().decode().splitlines()[1] Usage = re.findall(r'\S{1,}', OutStr)[4] DicTmp = {} DicTmp[Mnt] = Usage Data.append(DicTmp) except: pass # 关闭连接 SSHCli.close() Ret["data"] = Data return JSON.dumps(Ret, ensure_ascii=False) class Msg(): """短信接口""" @classmethod def sendListenMsg(cls, Contetn, Phone=""): """调用短信平台,发送短信""" Wsdl_Url = "http://100.169.130.50:57772/dthealth/web/wcw.soap.ShortMsg.cls?WSDL=1&CacheUserName=dhwebservice&CachePassword=dhwebservice&CacheNoRedirect=1" Soap = suds.Client(Wsdl_Url) # 设置Token安全登录验证 security = Security() token = UsernameToken('dhwebservice', 'dhwebservice') security.tokens.append(token) Soap.set_options(wsse=security) # 接收电话(多个手机号用","拼接) if Phone=="": Phone = "180***65,156***67,176***69" # 调用接口 Ret = Soap.service.sendMsg(Contetn, Phone) return Ret def runLinux(P_IP, P_Port, P_User, P_Password): """执行Linux监测程序并发送预警短信""" IP = P_IP Port = int(P_Port) User = P_User Password = P_Password Lixmnt = LinuxMntListen() MntList = JSON.loads(Lixmnt.getSpaceInfo(IP, Port, User, Password)) # print(MntList["data"]) NeedSendCont = [] for Item in MntList["data"]: for MntName, MntPct in Item.items(): # print(float(MntPct.strip("%"))) if float(MntPct.strip("%")) >= 90: NeedSendCont.append("挂载空间【" + MntName + "】使用率为【" + MntPct.replace("%", "%") + "】,空间不足。") # 短息内容 MsgContent = "服务器监测预警:服务器" + IP + "".join(NeedSendCont) + "请及时报给信息科处理!" # 发短信 MsgRet = "" if len(NeedSendCont): MsgRet = Msg.sendListenMsg(MsgContent) if MsgRet == "1": MsgRet = "发送短信成功。" else: MsgRet = "未发送短信,或发送短信失败。" print(MsgRet + "短信内容为:" + MsgContent) if __name__ == '__main__': # 程序入口 runLinux("192.168.1.22", "22", "root", "Huawei@2022")