1. 连接 linux
import paramiko # pip install paramiko
def main(ip, port, username, password):
res_data = []
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, port, username, password)
shell_in = "df -Tk"
# 执行多条命令直接在exec_command()使用;分隔即可。
stdin, stdout, stderr = ssh.exec_command(shell_in)
# 循环打印每一行输出
if stdout:
data = stdout.readlines()
for line_num, line in enumerate(data):
# print(line, end='')
if line_num > 0:
temp = line.rstrip('\n').split()
if temp[1] in ['ext4']: # 文件系统类型
res_data.append({
'file_system': temp[0], # 文件系统
'file_system_type': temp[1], # 文件系统类型
'total_size': round(int(temp[2])/1024/1024, 2), # 容量
'used_size': round(int(temp[3])/1024/1024, 2), # 已用
'available_size': round(int(temp[4])/1024/1024, 2), # 可用
'used_percent': temp[5], # 已用%
'mount_point': temp[6] # 挂载点
})
if stderr:
data = stdout.readlines()
if data:
ssh.close()
raise ValueError
ssh.close()
return res_data
2. 连接 windows
import winrm # pip install pywinrm
"""
wmic LogicalDisk get Caption,Description,FileSystem,FreeSpace,Size
Caption Description FileSystem FreeSpace Size
C: 本地固定磁盘 NTFS 8858968064 157286395904
D: 本地固定磁盘 NTFS 65570955264 209714147328
E: 本地固定磁盘 NTFS 39923621888 144040783872
"""
def main(ip, port, username, password):
res_data = []
shell_in = 'wmic LogicalDisk get Description,FileSystem,FreeSpace,Name,Size'
win = winrm.Session(ip, auth=(username, password), transport='ntlm')
data = win.run_ps(shell_in)
if data.status_code == 0:
std_out = str(data.std_out, 'gbk') # 打印获取到的信息, cmd默认使用gbk编码,而python默认使用utf-8,所以要用gbk进行解码
if std_out:
for line_num, data in enumerate(std_out.split('\n')):
if line_num > 0:
temp = data.rstrip('\r').split()
if temp:
res_data.append({
'name': temp[3], # 磁盘名称
'description': temp[0], # 描述
'file_system': temp[1], # 文件系统
'available_size': round(int(temp[2]) / 1024 / 1024 / 1024, 2), # 可用
'total_size': round(int(temp[4]) / 1024 / 1024 / 1024, 2), # 总容量
'used_size': round((int(temp[4]) - int(temp[2])) / 1024 / 1024 / 1024, 2), # 已用
'used_percent': str(100 - round(int(temp[2]) / int(temp[4]) * 100, 2)) + '%', # 已用%
})
return res_data
else:
raise ValueError(data.status_code)