428 字
2 分钟
给Linux进行批量部署
一早上,说什么前阵子装的很多agent,没有发现连接到服务器,可能有些人安装的不对,要重新装一下。
自己以前写过个shell,用于批量配置,这不刚好改改就能用了。
情况是,各个linux的主机有不同的密码,账户都是root,那就需要建立一个账户文件,包含远端机器的IP地址,root,还有密码。
然后逐行读取这三个信息,用来ssh连接远端机器,连接完成后,提前将要执行的动作写入一个shell文件,然后sftp到远端机器去,再进行执行,执行后将输出写入当前的目录的log.txt文件中。
目录结构如下:
├── account.csv
├── command.py
├── install.sh
└── log.txt
其中install.sh是要执行的shell文件,log.txt是执行后生成的日志。
account.csv的格式如下: 用空格隔开,IP地址,账户名和密码
10.1.2.3 root password10.1.2.5 root newpass下面是python的代码:
import csvimport paramiko
def ssh_command(ip, username, password): ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try: ssh_client.connect(ip, username=username, password=password)
sftp = ssh_client.open_sftp() local_sh = "install.sh" remote_path = '/tmp/install.sh' sftp.put(local_sh, remote_path) sftp.close()
stdin, stdout, stderr = ssh_client.exec_command( 'chmod +x {} && {}'.format(remote_path, remote_path))
# stdin, stdout, stderr = ssh_client.exec_command('/tmp/install.sh') # 等待命令执行完成 exit_status = stdout.channel.recv_exit_status() # 处理命令执行结果并记录到 log.txt 文件中 with open('log.txt', 'a') as log_file: log_file.write(f"=== Output for {ip} ===\n") log_file.write(stdout.read().decode("utf-8")) log_file.write(f"Exit status: {exit_status}\n") except paramiko.AuthenticationException: print(f"Failed to log in to {ip} with provided credentials.") finally: ssh_client.close()
with open('account.csv', 'r') as csvfile: csv_reader = csv.reader(csvfile, delimiter=' ') # next(csv_reader) # 跳过标题行 for row in csv_reader: ip = row[0] username = row[1] password = row[2] # command_to_run = "install.sh" # 替换为要执行的脚本命令 ssh_command(ip, username, password)通过测试,可以实现效果。后面也可以用os.remove删掉上传到远端的shell文件。
给Linux进行批量部署
https://dididudu998.github.io/posts/给linux进行批量部署/