Paramiko是一个用于执行SSH命令的Python第三方库,使用该库可实现自动化运维的所有任务,如下是一些常用代码的封装方式,多数代码为半成品,只是敲代码时的备份副本防止丢失,仅供参考,目前本人巡检百台设备完全无压力。
实现命令执行: 直接使用过程化封装,执行CMD命令.
代码语言:javascript复制import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
def BatchCMD(address,username,password,port,command):
try:
ssh.connect(hostname=address,username=username,password=password,port=port,timeout=2)
stdin , stdout , stderr = ssh.exec_command(command)
result = stdout.read()
if len(result) != 0:
result = str(result).replace("\n", "n")
result = result.replace("b'", "").replace("'", "")
return result
else:
return None
except Exception:
return None
实现磁盘巡检: 获取磁盘空间并返回字典格式
代码语言:javascript复制def GetAllDiskSpace(address,username,password,port):
ref_dict = {}
cmd_dict = {"Linuxn" : "df | grep -v 'Filesystem' | awk '{print $5 ":" $6}'",
"AIXn" : "df | grep -v 'Filesystem' | awk '{print $4 ":" $7}'"
}
# 首先检测系统版本
os_version = BatchCMD(address,username,password,port,"uname")
for version,run_cmd in cmd_dict.items():
if(version == os_version):
# 根据不同版本选择不同的命令
os_ref = BatchCMD(address,username,password,port,run_cmd)
ref_list= os_ref.split("n")
# 循环将其转换为字典
for each in ref_list:
# 判断最后是否为空,过滤最后一项
if each != "":
ref_dict[str(each.split(":")[1])] = str(each.split(":")[0])
return ref_dict
# 磁盘巡检总函数
def DiskMain():
with open("db.json", "r", encoding="utf-8") as read_fp:
load_json = read_fp.read()
js = json.loads(load_json)
base = js.get("base")
count = len(base)
for each in range(0,count):
print("