import paramiko
import sys
def sshExecCMD(hostname, username, password, port, cmd):
# 创建一个ssh对象
ssh_client = paramiko.SSHClient()
# 设置丢失主机key时的策略为自动添加
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
try:
ssh_client.connect(hostname=hostname, username=username, password=password, port=port)
except Exception as e:
print("服务器{}连接失败".format(hostname))
print(e)
sys.exit()
# 执行linux命令
stdin, stdout, stderr = ssh_client.exec_command(cmd)
print("服务器{},「 {} 」执行结果:".format(hostname, cmd))
print(stdout.read().decode("utf-8"))
# 关闭ssh连接
ssh_client.close()
if __name__ == "__main__":
servers = {
"47.xx.xx.x3": {
"username": "root",
"password": "Cmzw@13579",
"port": 22,
}
}
cmd = "df -hT"
for ip,info in servers.items():
sshExecCMD(hostname=ip, username=info.get("username"), password=info.get("password"), port=info.get("port"), cmd=cmd)
网友评论