【python自動化運維】批量安裝salt-minion(2018.03py3)

使用saltstack作集中化管理平臺,有一點不好的就是它屬於C/S類型,每一臺被控minion主機都需要安裝一個salt-minion.

官方提供了一個salt-ssh可以用於批量操作,把賬號密碼等信息按指定格式寫到roster文件裏面,再用salt-ssh命令執行命令。類似這樣:在這裏插入圖片描述在這裏插入圖片描述

在Python2環境上沒什麼問題,然而我master端裝了個2018.03py3的版本之後,各種問題,現成的用不了,那就只能自己開發了,附上腳本代碼:

#!/usr/bin/python3
# author wugf
## 批量安裝salt-minion(2018.03)

import paramiko

#  定義一個函數,用來執行遠程命令
def ssh_cmd(host, user, passwd, port, cmd):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=host, username=user, password=passwd, port=port)
    for command in cmd:
        stdin,stdout,stderr = ssh.exec_command(command)
        result = stdout.read()
        print(result)
    ssh.close()

# 將要執行的命令放入列表中,一個元素代表一個命令。
cmd = [
    "yum remove salt* -y",
    "rm -fr /etc/salt",
    "yum install https://repo.saltstack.com/py3/redhat/salt-py3-repo-latest-2.el7.noarch.rpm -y",
    "yum install salt-minion -y",
    "sed -i \'s/^#master:.*/master: \"10.1.1.96\"/g\' /etc/salt/minion",  # 10.1.1.96替換成對應的master地址
    "",  # 留空,作用:設置minion id
    "sed -i \'s/^#hash_type:.*/hash_type: sha512/g\' /etc/salt/minion", # 更改hash_type
    "systemctl restart salt-minion"
    ]

# 定義一個字典,key值是minion id, value是對應的服務器IP,用戶名,密碼,ssh訪問端口,一個“key:values”對代表一臺機器
info = {
    "minion":["10.1.1.125", "root", "passwd" ,"22"]
    }

for key1 in info.keys():
    cmd[5] = "sed -i \'s/^#id:.*/id: \"" + key1 + "\"/g\' /etc/salt/minion"  # minion id賦值
    ssh_cmd(info[key1][0], info[key1][1], info[key1][2], info[key1][3], cmd)
    print("complete: ",key1)

直接做成一個模板,把10.1.1.96這個IP替換成對應的salt-master機器的ip,拓展的話只要修改info字典裏面的鍵值對就行。格式是:

“minion id”:[“ip”, “賬號”, “密碼”, “端口”]

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章