非常感谢!! https://blog.csdn.net/qq_43279936/article/details/86533095
1,需要 paramiko 模块
pip3 install paramiko
2,链接远程服务器,并执行df -h
import paramiko
client = paramiko.SSHClient()
'''
这里用的连接方式是秘钥连接,推荐用这种,没有明文密码,比较安全
这种方式需要两台机器之间建立信任关系
关于如何建立信任关系,请百度 'centos建立信任关系'
'''
private_key = paramiko.RSAKey.from_private_key_file('/home/www/.ssh/id_rsa')
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=server_info['host'],username=server_info['user'],pkey= private_key)
stdin, stdout, stderr = client.exec_command('df -h')
result = stdout.read().decode('utf-8')
client.close()
3,解析返回的字符串,封装好了一个方法,直接传入上面的result,会解析好
def analyze(self,data):
arr = data.split('\n')
'''这种格式
Filesystem Size Used Avail Use% Mounted on
/dev/vda1 50G 23G 24G 49% /
devtmpfs 7.8G 0 7.8G 0% /dev
tmpfs 7.8G 316K 7.8G 1% /dev/shm
tmpfs 7.8G 1.2M 7.8G 1% /run
tmpfs 7.8G 0 7.8G 0% /sys/fs/cgroup
/dev/vdb 985G 62G 873G 7% /data
tmpfs 1.6G 0 1.6G 0% /run/user/0
tmpfs 1.6G 0 1.6G 0% /run/user/1000
'''
i = 1
format_data = []
for row in arr:
#第一行不要
if(i == 1):
i+=1
continue
data_row = []
row_arr = row.split(' ')
for item in row_arr:
if(item == ''):
continue
data_row.append(item)
if(len(data_row) > 0):
format_data.append(data_row)
return format_data
4,判断磁盘使用情况
#format_data 是上面封装方法返回的
for row in format_data:
path = row[5] #路径
use = row[4] #使用占比
use_number = int(use.replace('%',''))
self._l.info('use={},path={}'.format(use,path))
if(use_number > 80):
print('磁盘{}路径使用超过{}'.format(path,use))