一、說明:
1、利用Python的paramiko模塊,調用遠程的shell命令去修改相應文件。
2、有一個專用配置文件,列出服務器清單。
3、Python循環讀取配置文件的服務器IP去連接它,並執行相應的命令。
4、主要是有一個正則,匹配Zabbix agent中的IP設置。
[root@mysql-m ~]# sed -i 's/^Server=[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*/Server=33.66.88.99/g' zabbix_agentd.conf
腳本的內容如下:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "life"
# Email: batistuta1977@163.com
# Date: 2017/12/28
import paramiko
list_file_content = []
def read_file():
with open('ip-list','rU',encoding='utf-8') as f1:
for i in f1.readlines():
list_file_content.append(i.strip())
print(list_file_content)
def ssh_conn(hosts):
for host in hosts:
print(host)
ssh = paramiko.SSHClient() # 創建ssh對象
# 允許連接不在know_hosts文件中的主機
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 連接服務器
ssh.connect(hostname=host, port=22, username='root', password='1')
# 執行追加文件內容命令
# stdin, stdout, stderr = ssh.exec_command("echo 'nameserver 172.16.50.11' >> /tmp/1.txt")
# stdin,stdout,stderr = ssh.exec_command("echo 'nameserver 172.18.50.11\n' >> /tmp/1.txt")
# 修改zabbix agent內容
stdin, stdout, stderr = ssh.exec_command\
("sed -i 's/^Server=[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*/Server=33.66.88.99/g' /etc/zabbix/zabbix_agentd.conf")
if __name__ == '__main__':
read_file()
ssh_conn(list_file_content)
結果如下:

