• Python3 写的远程批量修改文件内容的脚本


    一、说明:

    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
    ' >> /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)
    

    结果如下:

      

  • 相关阅读:
    踩坑纪录——Lombok加Builder注解后mybatis无法识别字段正确类型
    安装node
    PostgreSQL DISTINCT ON
    RabbitMQ安装到使用入门
    springboot整合rabbitMQ时遇到的消息无法入列问题
    不同版本springboot上传文件大小设置
    thymeleaf报错元素类型必须由匹配的结束标记终止
    不同版本springboot端点开启方法
    mybatis匹配字符串的坑
    杂记
  • 原文地址:https://www.cnblogs.com/ld1977/p/8145738.html
Copyright © 2020-2023  润新知