有时候我们需要对多台Linux主机执行相同的命令,比如在多台Linux主机上通过yum安装软件包。如果一个个手动执行,不仅低效,而且容易出错。因此,写了一个Python脚本,可以批量通过ssh连接Linux主机并执行命令,同时打印结果。
为什么是Python脚本?Shell脚本当然也可以,而且会更简洁。但是在Shell脚本中直接ssh连接主机,必须手动输入密码,这样就降低了操作效率。而且使用Python进行高级操作,比如多线程执行,要比Shell强大的多
用途
批量通过ssh连接Linux主机并执行命令,同时打印结果
依赖
sudo pip install paramiko
使用示例见注释
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import paramiko
def run(host_ip, username, password, command):
ssh = paramiko.SSHClient()
try:
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host_ip, 22, username, password)
print('===================exec on [%s]=====================' % host_ip)
print(ssh.exec_command(command, timeout=300)[1].read())
except Exception as ex:
print('error, host is [%s], msg is [%s]' % (host_ip, ex.message))
finally:
ssh.close()
if __name__ == '__main__':
# 将需要批量执行命令的host ip地址填到这里
# eg: host_ip_list = ['192.168.1.2', '192.168.1.3']
host_ip_list = ['ip1', 'ip2']
for _host_ip in host_ip_list:
# 用户名,密码,执行的命令填到这里
# eg: run(_host_ip, 'root', 'root123', 'yum install -y redis')
run(_host_ip, 'your_username', 'your_password', 'your command')
github地址
https://github.com/MrCloudPeak/DevOps/blob/master/batch_execution.py