Python通过多进程,批量修改linux中文件配置。只需要修改命令内容即可

该代码示例使用Python的paramiko库和multiprocessing模块,实现对多台服务器的Zabbix配置文件进行批量修改,替换Server和ServerActive的IP地址,并重启zabbix-agent服务。通过SSH连接进行账号密码认证,并在连接失败时给出提示。整个过程采用5个进程并行执行,提高效率。
摘要由CSDN通过智能技术生成
import paramiko
from multiprocessing import Pool

#只需要修改列表中的每个命令即可
cmd_change = [
    "sed -i 's/^Server=127.0.0.1/Server=zabbix.xxxxx.com,zabbix1.xxxxx.com,zabbix2.xxxxx.com/g' /etc/zabbix/zabbix_agent.conf",
    "sed -i 's/^ServerActive=127.0.0.1/ServerActive=zabbix.xxxxx.com,zabbix1.xxxxx.com,zabbix2.xxxxx.com/g' /etc/zabbix/zabbix_agent.conf",
    "systemctl restart zabbix-agent",
]

# [[ip,账号,密码],[ip,账号,密码]]
zhanghao = [['10.1x.2xx.5x', 'root', 'xxxxxxx'], ['10.1x.2xx.5x', 'root', 'xxxxxxx'],]

def ssh_login_linux(host, user, passwd, cmd, port=22):
    sshc = paramiko.SSHClient()
    sshc.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        sshc.connect(hostname=host, port=port, username=user, password=passwd)
    except BaseException:
        print("ssh账号密码认证错误", host, port, user, passwd)
    print("\n----remote execute command")
    for command in cmd:
        stdin, stdout, stderr = sshc.exec_command(command)
        stdout.channel
        return_code = stdout.channel.recv_exit_status()
        if return_code != 0:
            print(host,"命令执行失败 :" + command)
            break
        print(host,"----done: ", command)
    sshc.close()


if __name__ == '__main__':
	#5个进程同时运行
    pool = Pool(5)
    for i in zhanghao:
         pool.apply_async(func=ssh_login_linux, args=(i[0],i[1],i[2],cmd_change))
    pool.close()
    pool.join()
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

信飞翔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值