首先使用paramiko模块,封装连接服务器,输入命令方法,使用read()读取命令输入后的返回值,并返回为字符串
def server_conn(ip,command):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=ip,username='', password="")
stdin, stdout, stderr = ssh.exec_command(command,get_pty=True)
result = stdout.read()
ssh.close()
return result
创建方法,参数1填入linux服务器IP,参数2填入目录绝对地址
方法中使用df命令读取出linux服务器目录使用情况,返回为一个字典
# df查找目录使用情况,返回为一个列表
def document_used(ip,doc):
read = server_conn(ip, 'df')
dic = {}
for i in read.splitlines():
if doc in i:
dic['total'] = i.split()[1]
dic['used'] = i.split()[2]
dic['percent'] = i.split()[4]
return dic
输出/目录使用情况:
{'total': '36154072', 'percent': '12%', 'used': '4076720'}
附:使用falloc占用目录空间为90%以上
# 使用falloc占用目录空间为90%以上
def doc_falloc(ip, doc, percent = 0.95):
dic = document_used(ip, doc)
total = int(dic['total'])
used = int(dic['used'])
per = int(dic['percent'].split("%")[0])
if per <= 90:
add = int(((total*percent) - used)/1048576)
cmd = 'fallocate '+doc + '/test_image -l '+str(add) + 'G'
server_conn(ip, str(cmd))