cmdb之saltstack的使用及python调用salt-api

saltstack 安装

在 centos 系统可以直接使用 epel 源通过 yum 进行安装,也可以选择通过官方的源进行安装(国内速度比较慢)

可以参考官方安装文档
centos 安装 epel 源可以使用下面命令

1
rpm -ivh https://mirrors.tuna.tsinghua.edu.cn/epel/epel-release-latest-7.noarch.rpm

salt-master

安装

1
yum install -y salt-master

salt-minion

安装

1
yum install -y salt-minion

配置saltstack

配置只需要修改 minion 端配置文件
vi /etc/salt/minion

1
2
master: 172.16.0.1
id: salt-01

然后重启服务

1
2
systemctl restart salt-master
systemctl restart salt-minion

此时可以测试 saltstack 是否可以正常使用

  • master 端控制 minion 端命令
    配置正确之后所有 minion 端对应 keys信息会显示,默认为 Unaccepted Keys,需要接受之后才能正常使用

    1
    2
    3
    4
    5
    6
    7
    salt-key -L 列出所有  
    salt-key -a 允许一台 minion
    salt-key -A 允许所有
    salt-key -r 拒绝一台
    salt-key -R 拒绝所有
    salt-key -d 删除指定 minion
    salt-key -D 删除所有
  • 可用性测试

    1
    2
    salt * test.ping
    salt * cmd.run 'free -m'

salt-api 配置

python 调用都是通过 salt-api,需要在 master 端配置 salt-api

1
2
yum install -y salt-api
yum install -y pyOpenSSL

配置自签名证书(master端)
cd /etc/pki/tls/certs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
[root@qqcloud certs]# make testcert
umask 77 ; \
/usr/bin/openssl genrsa -aes128 2048 > /etc/pki/tls/private/localhost.key
Generating RSA private key, 2048 bit long modulus
..................................................................................................................................................................................................+++
..........+++
e is 65537 (0x10001)
Enter pass phrase: #-->此处输入密码,需输入3次
Verifying - Enter pass phrase:
umask 77 ; \
/usr/bin/openssl req -utf8 -new -key /etc/pki/tls/private/localhost.key -x509 -days 365 -out /etc/pki/tls/certs/localhost.crt
Enter pass phrase for /etc/pki/tls/private/localhost.key:
You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [XX]:CN
State or Province Name (full name) []:BeiJing
Locality Name (eg, city) [Default City]:BeiJing
Organization Name (eg, company) [Default Company Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (eg, your name or your server's hostname) []:
Email Address []:

解密 key 文件,生成无密码的 key 文件,过程中需要输入 key 密码,该密码为之前证书的密码

1
2
3
[root@qqcloud private]# openssl rsa -in localhost.key -out localhost_nopass.key
Enter pass phrase for localhost.key:
writing RSA key

修改文件权限

1
2
3
[root@qqcloud private]# chmod 755 /etc/pki/tls/certs/localhost.crt 
[root@qqcloud private]# chmod 755 /etc/pki/tls/private/localhost.key
[root@qqcloud private]# chmod 755 /etc/pki/tls/private/localhost_nopass.ke

添加用户

1
2
3
4
5
6
[root@qqcloud private]# useradd -M -s /sbin/nologin saltapi
[root@qqcloud private]# passwd saltapi
Changing password for user saltapi.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.

修改 /etc/salt/master 文件

1
sed -i '/#default_include/s/#default/default/g' /etc/salt/master

创建 /etc/salt/master.d 目录并新增文件

1
2
3
[root@qqcloud private]# cd /etc/salt/master.d/
[root@qqcloud master.d]# touch eauth.conf
[root@qqcloud master.d]# touch api.conf

编辑 eauth.conf

1
2
3
4
external_auth:
pam:
saltapi: # 用户
- .* # 该配置文件给予saltapi用户所有模块使用权限,出于安全考虑一般只给予特定模块使用权限

指定模块,可以使用

1
- '@runner'

编辑 api.conf

1
2
3
4
rest_cherrypy:
port: 8001
ssl_crt: /etc/pki/tls/certs/localhost.crt
ssl_key: /etc/pki/tls/private/localhost_nopass.key

然后重启服务

1
2
3
systemctl restart salt-master
systemctl restart salt-minion
systemctl restart salt-api

python 调用 salt-api

示例 demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import requests
import json
try:
import cookielib
except:
import http.cookiejar as cookielib

# 使用urllib2请求https出错,做的设置
import ssl
context = ssl._create_unverified_context()

# 使用requests请求https出现警告,做的设置
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

salt_api = "https://172.16.0.19:8001/"


class SaltApi:
"""
定义salt api接口的类
初始化获得token
"""
def __init__(self, url):
self.url = url
self.username = "saltapi"
self.password = "qqsalt2019"
self.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
"Content-type": "application/json"
}
self.params = {'client': 'local', 'fun': '', 'tgt': ''}
self.login_url = salt_api + "login"
self.login_params = {'username': self.username, 'password': self.password, 'eauth': 'pam'}
# self.token = self.get_data(self.login_url, self.login_params)['token']
self.token = self.get_data(self.login_url, self.login_params).get('token')
self.headers['X-Auth-Token'] = self.token

def get_data(self, url, params):
send_data = json.dumps(params)
request = requests.post(url, data=send_data, headers=self.headers, verify=False)
response = request.json()
result = dict(response)
# print result
return result['return'][0]

def salt_command(self, tgt, method, arg=None):
"""远程执行命令,相当于salt 'client1' cmd.run 'free -m'"""
if arg:
params = {'client': 'local', 'fun': method, 'tgt': tgt, 'arg': arg}
else:
params = {'client': 'local', 'fun': method, 'tgt': tgt}
result = self.get_data(self.url, params)
return result


def main():
salt = SaltApi(salt_api)
salt_client = '*'
salt_test = 'test.ping'
salt_method = 'grains.get'
salt_params = ['ip_interfaces',]
result2 = salt.salt_command(salt_client, salt_method, salt_params)
print(result2)


if __name__ == '__main__':
main()

示例 demo 代码来源 https://www.jianshu.com/p/012ccdff93cc

Recommended Posts