通过python批量修改服务器系统日志发送地址

2020-09-21  本文已影响0人  ArthurIsUsed

问题

近期迁移服务器,拿到40台虚拟机后,安全团队反馈采用就的模板,目前需要把系统日志发送到其他设备上。确认后需要修改的文件/etc/rsyslog.conf

思路

[root@console home]# cat test_sed.txt 
hello
192.168.120.163
world
192.168.132.155
hello 酷狗

[root@console home]# 
[root@console home]# sed -i 's/192.168.120.163/10.6.6.112/g' test_sed.txt 
[root@console home]# cat test_sed.txt 
hello
10.6.6.112
world
192.168.132.155
hello 酷狗

执行

执行后发现有两个IP错误,其他的成功, 原因是其中一个没做免密登录,另一个authorized_keys文件名称少了一个s

[root@tempcentos7 ~]# tail -n 3 /etc/rsyslog.conf 
# remote host is: name/ip:port, e.g. 192.168.0.1:514, port optional
*.* @10.6.6.112:514
# ### end of the forwarding rule ###


10.6.9.226 执行成功
10.6.9.227 Error
10.6.9.228 执行成功
10.6.9.229 执行成功
10.6.9.230 Error
10.6.9.231 执行成功

代码

#!/usr/bin/env python3
#-*-coding: utf-8 -*-
import paramiko


config_file = "/root/.ssh/config"
sed_command = "sed -i 's/192.168.120.163/10.6.6.112/g' /etc/rsyslog.conf"
restart_rsyslog = 'systemctl restart rsyslog'
host_ip = []
key_file = '/root/.ssh/id_rsa'


def ssh_remote(host_ip, command):
    # 实例化SSH客户端
    ssh_remote = paramiko.SSHClient()
    # 设置白名单
    policy = paramiko.AutoAddPolicy()
    ssh_remote.set_missing_host_key_policy(policy)
    key = paramiko.RSAKey.from_private_key_file(key_file)
    try:
        ssh_remote.connect(
            hostname = host_ip,
            port = 36622,
            username = 'root',
            pkey = key
        )
        # 执行sed命令
        stdin, stdout, stderr = ssh_remote.exec_command(command)
        if stdout.read():
            print('{} 执行失败'.format(host_ip))
        else:
            print('{} 执行成功'.format(host_ip))
    except:
        print('{} Error'.format(host_ip))
        

# 读取ssh目录下的config文件,获取HostName字段
# 获取的IP,以字符串的形式保存到host_ip列表中
def host_name(file_path):
    with open(config_file, 'r') as cf:
        for lines in cf.readlines():
            if "HostName" in lines:
                host_ip.append(lines.split(' ')[1].strip('\n'))
    return host_ip
        


def connect_remote(ssh_remote, host_ip):
    # 依次连接到远端服务器, 修改配置
    for host_ip in host_ip:
        ssh_remote(host_ip, sed_command)
    for host_ip in host_ip:
        ssh_remote(host_ip, restart_rsyslog)

if __name__ == "__main__":
    host_ip = host_name(config_file)
    connect_remote(ssh_remote, host_ip)
上一篇下一篇

猜你喜欢

热点阅读