1.将数据存储到mysql服务器
master端执行命令,minion端将结果存入远程数据库并发送一份到master端
##方法1:
[root@server1 ~]# yum install mysql-server -y
[root@server1 ~]# /etc/init.d/mysqld start
[root@server1 ~]# salt server2 state.sls httpd.install
[root@server1 ~]# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.1.71 Source distribution
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
##授权
mysql> grant all on salt.* to salt@'172.25.52.%' identified by 'westos';
Query OK, 0 rows affected (0.00 sec)
mysql> quit
Bye
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| salt |
| test |
+--------------------+
4 rows in set (0.00 sec)
##删除原有的salt数据库
mysql> drop database salt;
Query OK, 1 row affected (0.05 sec)
mysql> quit
Bye
##直接用脚本导入salt数据库
[root@server1 ~]# vim test.sql
#################
CREATE DATABASE `salt`
DEFAULT CHARACTER SET utf8
DEFAULT COLLATE utf8_general_ci;
USE `salt`;
--
-- Table structure for table `jids`
--
DROP TABLE IF EXISTS `jids`;
CREATE TABLE `jids` (
`jid` varchar(255) NOT NULL,
`load` mediumtext NOT NULL,
UNIQUE KEY `jid` (`jid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- CREATE INDEX jid ON jids(jid) USING BTREE;
--
-- Table structure for table `salt_returns`
--
DROP TABLE IF EXISTS `salt_returns`;
CREATE TABLE `salt_returns` (
`fun` varchar(50) NOT NULL,
`jid` varchar(255) NOT NULL,
`return` mediumtext NOT NULL,
`id` varchar(255) NOT NULL,
`success` varchar(10) NOT NULL,
`full_ret` mediumtext NOT NULL,
`alter_time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
KEY `id` (`id`),
KEY `jid` (`jid`),
KEY `fun` (`fun`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Table structure for table `salt_events`
--
DROP TABLE IF EXISTS `salt_events`;
CREATE TABLE `salt_events` (
`id` BIGINT NOT NULL AUTO_INCREMENT,
`tag` varchar(255) NOT NULL,
`data` mediumtext NOT NULL,
`alter_time` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`master_id` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `tag` (`tag`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
[root@server1 ~]# mysql < test.sql
[root@server2 ~]# yum install -y MySQL-python.x86_64
[root@server2 ~]# vim /etc/salt/minion
#################
815 mysql.host: '172.25.52.1'
816 mysql.user: 'salt'
817 mysql.pass: 'westos'
818 mysql.db: 'salt'
819 mysql.port: 3306
[root@server2 ~]# /etc/init.d/salt-minion restart
Stopping salt-minion:root:server2 daemon: OK
Starting salt-minion:root:server2 daemon: OK
测试:
[root@server1 ~]# salt 'server2' test.ping --return mysql
server2:
True
[root@server1 ~]# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 5.1.71 Source distribution
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| salt |
| test |
+--------------------+
4 rows in set (0.00 sec)
mysql> use salt;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> show tables;
+----------------+
| Tables_in_salt |
+----------------+
| jids |
| salt_events |
| salt_returns |
+----------------+
3 rows in set (0.00 sec)
####查看到刚才执行过的命令信息
mysql> select * from salt_returns;
+-----------+----------------------+--------+---------+---------+-------------------------------------------------------------------------------------------------------------------------------------+---------------------+
| fun | jid | return | id | success | full_ret | alter_time |
+-----------+----------------------+--------+---------+---------+-------------------------------------------------------------------------------------------------------------------------------------+---------------------+
| test.ping | 20180818144243521120 | true | server2 | 1 | {"fun_args": [], "jid": "20180818144243521120", "return": true, "retcode": 0, "success": true, "fun": "test.ping", "id": "server2"} | 2018-08-18 14:42:43 |
+-----------+----------------------+--------+---------+---------+-------------------------------------------------------------------------------------------------------------------------------------+---------------------+
1 row in set (0.00 sec)
mysql> quit
Bye
##方法2:
[root@server1 ~]# yum install -y MySQL-python.x86_64
[root@server1 ~]# vim /etc/salt/master
1059 master_job_cache: mysql
1060 mysql.host: 'localhost'
1061 mysql.user: 'salt'
1062 mysql.pass: 'westos'
1063 mysql.db: 'salt'
1064 mysql.port: 3306
[root@server1 ~]# /etc/init.d/salt-master restart
Stopping salt-master daemon: [ OK ]
Starting salt-master daemon: [ OK ]
[root@server1 ~]# mysql
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 13
Server version: 5.1.71 Source distribution
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
##授权
mysql> grant all on salt.* to salt@localhost identified by 'westos';
Query OK, 0 rows affected (0.00 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
mysql> quit
Bye
##测试:
[root@server1 ~]# salt server3 cmd.run 'df -h'
server3:
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root 19G 1.1G 17G 6% /
tmpfs 499M 64K 499M 1% /dev/shm
/dev/vda1 485M 33M 427M 8% /boot
[root@server1 ~]# mysql -u salt -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 27
Server version: 5.1.71 Source distribution
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> use salt
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
##查看到刚才执行过的命令信息
mysql> select * from salt_returns;
+-----------+----------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------+---------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------+
| fun | jid | return | id | success | full_ret | alter_time |
+-----------+----------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------+---------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------+
| test.ping | 20180818144243521120 | true | server2 | 1 | {"fun_args": [], "jid": "20180818144243521120", "return": true, "retcode": 0, "success": true, "fun": "test.ping", "id": "server2"} | 2018-08-18 14:42:43 |
| cmd.run | 20180818150217056692 | "Filesystem Size Used Avail Use% Mounted on\n/dev/mapper/VolGroup-lv_root 19G 1.1G 17G 6% /\ntmpfs 499M 64K 499M 1% /dev/shm\n/dev/vda1 485M 33M 427M 8% /boot" | server3 | 1 | {"fun_args": ["df -h"], "jid": "20180818150217056692", "return": "Filesystem Size Used Avail Use% Mounted on\n/dev/mapper/VolGroup-lv_root 19G 1.1G 17G 6% /\ntmpfs 499M 64K 499M 1% /dev/shm\n/dev/vda1 485M 33M 427M 8% /boot", "retcode": 0, "success": true, "cmd": "_return", "_stamp": "2018-08-18T07:02:17.236945", "fun": "cmd.run", "id": "server3"} | 2018-08-18 15:02:17 |
+-----------+----------------------+--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------+---------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+---------------------+
2 rows in set (0.00 sec)
[root@server1 ~]# mkdir /srv/salt/_modules
[root@server1 ~]# cd /srv/salt/
[root@server1 salt]# ls
_grains haproxy httpd keepalived _modules nginx pkgs top.sls users
[root@server1 salt]# cd _modules/
[root@server1 _modules]# ls
[root@server1 _modules]# vim my_disk.py
########################
#!/usr/bin/env python
def df():
return __salt__['cmd.run']('df -h')
##测试:
#必须先推送 再检测
[root@server1 _modules]# salt '*' saltutil.sync_modules
server3:
- modules.my_disk
server2:
- modules.my_disk
server1:
- modules.my_disk
server4:
- modules.my_disk
[root@server1 _modules]# salt '*' my_disk.df
server3:
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root 19G 1.1G 17G 6% /
tmpfs 499M 64K 499M 1% /dev/shm
/dev/vda1 485M 33M 427M 8% /boot
server4:
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root 19G 1.1G 17G 7% /
tmpfs 499M 16K 499M 1% /dev/shm
/dev/vda1 485M 33M 427M 8% /boot
server2:
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root 19G 989M 17G 6% /
tmpfs 499M 32K 499M 1% /dev/shm
/dev/vda1 485M 33M 427M 8% /boot
server1:
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root 19G 1.1G 17G 7% /
tmpfs 499M 96K 499M 1% /dev/shm
/dev/vda1 485M 33M 427M 8% /boot
2.salt-syndic
实验环境
server1 : 二级master
server4 : 顶级master
[root@server4 modules]# pwd
/var/cache/salt/minion/extmods/modules
[root@server4 modules]# ls
my_disk.py my_disk.pyc
[root@server4 modules]# ll
total 8
-rw------- 1 root root 74 Aug 18 15:29 my_disk.py
-rw------- 1 root root 317 Aug 18 15:29 my_disk.pyc
[root@server4 modules]# cd ..
[root@server4 extmods]# cd grains/
[root@server4 grains]# pwd
/var/cache/salt/minion/extmods/grains
[root@server4 grains]# ls
my_grains.py my_grains.pyc
[root@server1 _modules]# salt-key -L
Accepted Keys:
server1
server2
server3
server4
Denied Keys:
Unaccepted Keys:
Rejected Keys:
[root@server1 _modules]# salt-key -d server4
The following keys are going to be deleted:
Accepted Keys:
server4
Proceed? [N/y] Y
Key for minion server4 deleteed.
[root@server1 _modules]# salt-key -L
Accepted Keys:
server1
server2
server3
Denied Keys:
Unaccepted Keys:
Rejected Keys:
[root@server4 grains]# /etc/init.d/salt-minion stop
Stopping salt-minion:root:server4 daemon: OK
[root@server4 grains]# chkconfig salt-minion off
[root@server4 grains]# /etc/init.d/haproxy stop
Stopping haproxy: [ OK ]
[root@server4 grains]# /etc/init.d/keepalived stop
Stopping keepalived: [ OK ]
[root@server4 grains]# ps ax
[root@server4 grains]# yum install -y salt-master
[root@server4 grains]# cd /etc/salt
[root@server4 salt]# ls
cloud cloud.maps.d master minion.d proxy
cloud.conf.d cloud.profiles.d master.d minion_id proxy.d
cloud.deploy.d cloud.providers.d minion pki roster
[root@server4 salt]# vim master
###################
857 order_masters: True
[root@server4 salt]# /etc/init.d/salt-master start
Starting salt-master daemon: [ OK ]
[root@server4 salt]# salt-key -L
Accepted Keys:
Denied Keys:
Unaccepted Keys:
Rejected Keys:
[root@server1 _modules]# yum install -y salt-syndic
[root@server1 salt]# pwd
/etc/salt
[root@server1 salt]# vim master
####################
861 syndic_master: 172.25.52.4
[root@server1 ~]# /etc/init.d/salt-master stop
Stopping salt-master daemon: [ OK ]
[root@server1 ~]# /etc/init.d/salt-master start
Starting salt-master daemon: [ OK ]
[root@server1 ~]# /etc/init.d/salt-syndic start
Starting salt-syndic daemon: [ OK ]
##测试:
[root@server4 salt]# salt-key -L
Accepted Keys:
Denied Keys:
Unaccepted Keys:
server1
Rejected Keys:
[root@server4 salt]# salt-key -A
The following keys are going to be accepted:
Unaccepted Keys:
server1
Proceed? [n/Y] Y
Key for minion server1 accepted.
[root@server4 salt]# salt-key -L
Accepted Keys:
server1
Denied Keys:
Unaccepted Keys:
Rejected Keys:
[root@server4 salt]# salt '*' test.ping
server2:
True
server3:
True
server1:
True
排错1:
##如果master打不开了该怎么办?
[root@server1 salt]# /etc/init.d/salt-master start
Starting salt-master daemon: WARNING: Unable to bind socket 0.0.0.0:4505, error: [Errno 98] Address already in use; Is there another salt-master running?
The salt master is shutdown. The ports are not available to bind
[FAILED]
[root@server1 salt]# reboot
[root@server1 salt]#
Broadcast message from root@server1
(/dev/pts/0) at 16:06 ...
The system is going down for reboot NOW!
Connection to 172.25.52.1 closed by remote host.
Connection to 172.25.52.1 closed.
[root@foundation52 kiosk]# ssh root@172.25.52.1
ssh: connect to host 172.25.52.1 port 22: Connection refused
[root@foundation52 kiosk]# ssh root@172.25.52.1
root@172.25.52.1's password:
Last login: Sat Aug 18 09:44:42 2018 from 172.25.52.250
[root@server1 ~]# ps ax
##注意:重启之后需要开启mysql
##排错2:
[root@server4 salt]# salt '*' test.ping
server2:
Minion did not return. [No response]
server3:
Minion did not return. [No response]
[root@server4 salt]# salt '*' test.ping
server2:
Minion did not return. [No response]
server3:
Minion did not return. [No response]
[root@server1 ~]# salt '*' test.ping
[WARNING ] Returner unavailable: MySQL returner could not connect to database: (2002, "Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)")
server2:
True
server3:
True
server1:
True
##开启数据库
[root@server1 ~]# /etc/init.d/mysqld start
Starting mysqld: [ OK ]
[root@server4 salt]# salt '*' test.ping
server2:
True
server3:
True
server1:
True
3.salt-ssh
[root@server3 ~]# /etc/init.d/salt-minion stop
Stopping salt-minion:root:server3 daemon: OK
[root@server1 ~]# yum install -y salt-ssh
[root@server1 ~]# vim /etc/salt/master
################
注释:
1059 #master_job_cache: mysql
1060 #mysql.host: 'localhost'
1061 #mysql.user: 'salt'
1062 #mysql.pass: 'westos'
1063 #mysql.db: 'salt'
1064 #mysql.port: 3306
[root@server1 ~]# vim /etc/salt/roster
#################
10 server3:
11 host: 172.25.52.3
12 user: root
13 passwd: westos
##测试:
[root@server1 ~]# salt-ssh 'server3' test.ping
server3:
----------
retcode:
254
stderr:
stdout:
The host key needs to be accepted, to auto accept run salt-ssh with the -i flag:
The authenticity of host '172.25.52.3 (172.25.52.3)' can't be established.
RSA key fingerprint is fc:68:3f:d9:a8:07:dd:06:20:09:b5:02:fb:33:a9:99.
Are you sure you want to continue connecting (yes/no)?
[root@server1 ~]# salt-ssh 'server3' test.ping -i
server3:
True
[root@server1 ~]# salt-ssh 'server3' my_disk.df
server3:
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/VolGroup-lv_root 19G 1.1G 17G 7% /
tmpfs 499M 80K 499M 1% /dev/shm
/dev/vda1 485M 33M 427M 8% /boot
4.salt-api
[root@server3 ~]# /etc/init.d/salt-minion start
Starting salt-minion:root:server3 daemon: OK
[root@server1 ~]# yum install -y salt-api
[root@server1 ~]# cd /etc/pki/
[root@server1 pki]# ls
CA ca-trust entitlement java nssdb product rpm-gpg rsyslog tls
[root@server1 pki]# cd tls/
[root@server1 tls]# ls
cert.pem certs misc openssl.cnf private
[root@server1 tls]# cd private/
[root@server1 private]# pwd
/etc/pki/tls/private
[root@server1 private]# ls
[root@server1 private]# openssl genrsa 1024
Generating RSA private key, 1024 bit long modulus
......++++++
.........++++++
e is 65537 (0x10001)
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDJQH1Oq2xPToTzFpE+U/chQupaLXS44PqS8Bnup0foZvc2oSj4
tdLthALbHJksuk440ZVQCMaEIjduwHvsZFa9C/6OzGJ442rpfhWoBNoUgYiphTX3
lOTzndeZLZr71w6QwwmaL2QuCRHJfUditTZv8iMfkIgyQcjVrtBWfDwtIQIDAQAB
AoGBAKthCJRytHRAuETN5fe+xweDFVCfvvMlWxy/7EVoHHsTG9hgmyRYqftrXIc8
rlABg1UtXMpf/rVM8gmVTrJ6q8UjFIrxbQywrYBW4BxmNN7bnZjSys7Bh3dILS6l
iEqA/hb5ijbXJyVS0WU+HVwXzrogJq3gS+5XoS02dQNq7dMxAkEA+AFZW5HB+AIt
cAEqIkdXmrVrWsIVi5PkNJmkhVYS0hxx4oCtmsHx/lbQwa9f5ENZOaZw+ibrLdAO
ridrvXdsHQJBAM+9T4qRMTP5yqK1VhKHod4oeSYzv6G9T7k4WLUQFKsqM8u8d6QB
TKk6kxXiC6CQ4Ts5YC9tuC3NxjXwCkW8zdUCQHd5jubCLUOhKOqQZQ/mdpmdVH6A
iYiYUpPUgKGLeb2m3mZTv06SqFXy1Na5+eQpXc6cFEkufpWvaaMUcp7v7TECQQDO
2HnlyDIMxbCtmA9u/dv/n58Zmbc6rYw/Kcqx5qQd1jSirTMXey/A5RDlXiEjrH6H
gNa0AvS7rsOomy0vSRJNAkBnGuSG5nkXmd0GtzRBMHBx+OKcXZQMELDy01PFODWg
u7oaVrNc35G08RusSlnPcfeqUOIynoGeRxVDMI3wyn5z
-----END RSA PRIVATE KEY-----
[root@server1 private]# openssl genrsa 1024 > localhost.key
Generating RSA private key, 1024 bit long modulus
................................................++++++
.....++++++
e is 65537 (0x10001)
[root@server1 private]# ls
localhost.key
[root@server1 private]# cd ..
[root@server1 tls]# cd cert
-bash: cd: cert: No such file or directory
[root@server1 tls]# cd certs/
[root@server1 certs]# ls
ca-bundle.crt ca-bundle.trust.crt make-dummy-cert Makefile renew-dummy-cert
[root@server1 certs]# pwd
/etc/pki/tls/certs
[root@server1 certs]# make testcert
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 -set_serial 0
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) []:shaanxi
Locality Name (eg, city) [Default City]:xi'an
Organization Name (eg, company) [Default Company Ltd]:westos
Organizational Unit Name (eg, section) []:linux
Common Name (eg, your name or your server's hostname) []:server1
Email Address []:root@localhost
[root@server1 certs]# ls
ca-bundle.crt localhost.crt Makefile
ca-bundle.trust.crt make-dummy-cert renew-dummy-cert
[root@server1 certs]# ll localhost.crt
-rw------- 1 root root 1029 Aug 18 17:07 localhost.crt
[root@server1 certs]# cd /etc/salt/
[root@server1 salt]# ls
cloud cloud.maps.d master minion.d proxy
cloud.conf.d cloud.profiles.d master.d minion_id proxy.d
cloud.deploy.d cloud.providers.d minion pki roster
##查看文件
[root@server1 salt]# vim master
[root@server1 salt]# cd master.d/
[root@server1 master.d]# ls
[root@server1 master.d]# pwd
/etc/salt/master.d
[root@server1 master.d]# vim api.conf
########################
1 rest_cherrypy:
2 port: 8000
3 ssl_crt: /etc/pki/tls/certs/localhost.crt
4 ssl_key: /etc/pki/tls/private/localhost.key
##测试文件路径是否正确:
[root@server1 master.d]# ll /etc/pki/tls/certs/localhost.crt
-rw------- 1 root root 1029 Aug 18 17:07 /etc/pki/tls/certs/localhost.crt
[root@server1 master.d]# ll /etc/pki/tls/certs/localhost.crt
-rw------- 1 root root 1029 Aug 18 17:07 /etc/pki/tls/certs/localhost.crt
[root@server1 master.d]# vim auth.conf
########################
external_auth:
pam:
saltapi:
- '.*'
- '@wheel'
- '@runner'
- '@jobs'
[root@server1 master.d]# useradd saltapi
[root@server1 master.d]# passwd saltapi
Changing password for user saltapi.
New password:
BAD PASSWORD: it is based on a dictionary word
BAD PASSWORD: is too simple
Retype new password:
passwd: all authentication tokens updated successfully.
[root@server1 master.d]# /etc/init.d/salt-master stop
Stopping salt-master daemon: [ OK ]
[root@server1 master.d]# /etc/init.d/salt-master status
salt-master is stopped
[root@server1 master.d]# /etc/init.d/salt-master start
Starting salt-master daemon: [ OK ]
[root@server1 ~]# /etc/init.d/salt-api start
Starting salt-api daemon: [ OK ]
[root@server1 ~]# netstat -antlp | grep :8000
tcp 0 0 0.0.0.0:8000 0.0.0.0:* LISTEN 2968/salt-api -d
tcp 0 0 127.0.0.1:51738 127.0.0.1:8000 TIME_WAIT -
##获取地址4d18fe5fcbb1731d6f8117de3c9d70b1aa4c498f
[root@server1 ~]# curl -sSk https://localhost:8000/login -H 'Accept: application/x-yaml' -d username=saltapi -d password=westos -d eauth=pam
return:
- eauth: pam
expire: 1534627950.9950681
perms:
- '*'
- '@wheel'
- '@runner'
- '@jobs'
start: 1534584750.9950669
token: 4d18fe5fcbb1731d6f8117de3c9d70b1aa4c498f
user: saltapi
[root@server1 ~]# curl -sSk https://localhost:8000 -H 'Accept: application/x-yaml' -H 'X-Auth-Token: 4d18fe5fcbb1731d6f8117de3c9d70b1aa4c498f' -d client=local -d tgt='*' -d fun=test.ping
[root@server1 ~]# vim saltapi.py
#################
# -*- coding: utf-8 -*-
import urllib2,urllib
import time
try:
import json
except ImportError:
import simplejson as json
class SaltAPI(object):
__token_id = ''
def __init__(self,url,username,password):
self.__url = url.rstrip('/')
self.__user = username
self.__password = password
def token_id(self):
''' user login and get token id '''
params = {'eauth': 'pam', 'username': self.__user, 'password': self.__password}
encode = urllib.urlencode(params)
obj = urllib.unquote(encode)
content = self.postRequest(obj,prefix='/login')
try:
self.__token_id = content['return'][0]['token']
except KeyError:
raise KeyError
def postRequest(self,obj,prefix='/'):
url = self.__url + prefix
headers = {'X-Auth-Token' : self.__token_id}
req = urllib2.Request(url, obj, headers)
opener = urllib2.urlopen(req)
content = json.loads(opener.read())
return content
def list_all_key(self):
params = {'client': 'wheel', 'fun': 'key.list_all'}
obj = urllib.urlencode(params)
self.token_id()
content = self.postRequest(obj)
minions = content['return'][0]['data']['return']['minions']
minions_pre = content['return'][0]['data']['return']['minions_pre']
return minions,minions_pre
def delete_key(self,node_name):
params = {'client': 'wheel', 'fun': 'key.delete', 'match': node_name}
obj = urllib.urlencode(params)
self.token_id()
content = self.postRequest(obj)
ret = content['return'][0]['data']['success']
return ret
def accept_key(self,node_name):
params = {'client': 'wheel', 'fun': 'key.accept', 'match': node_name}
obj = urllib.urlencode(params)
self.token_id()
content = self.postRequest(obj)
ret = content['return'][0]['data']['success']
return ret
def remote_noarg_execution(self,tgt,fun):
''' Execute commands without parameters '''
params = {'client': 'local', 'tgt': tgt, 'fun': fun}
obj = urllib.urlencode(params)
self.token_id()
content = self.postRequest(obj)
ret = content['return'][0][tgt]
return ret
def remote_execution(self,tgt,fun,arg):
''' Command execution with parameters '''
params = {'client': 'local', 'tgt': tgt, 'fun': fun, 'arg': arg}
obj = urllib.urlencode(params)
self.token_id()
content = self.postRequest(obj)
ret = content['return'][0][tgt]
return ret
def target_remote_execution(self,tgt,fun,arg):
''' Use targeting for remote execution '''
params = {'client': 'local', 'tgt': tgt, 'fun': fun, 'arg': arg, 'expr_form': 'nodegroup'}
obj = urllib.urlencode(params)
self.token_id()
content = self.postRequest(obj)
jid = content['return'][0]['jid']
return jid
def deploy(self,tgt,arg):
''' Module deployment '''
params = {'client': 'local', 'tgt': tgt, 'fun': 'state.sls', 'arg': arg}
obj = urllib.urlencode(params)
self.token_id()
content = self.postRequest(obj)
return content
def async_deploy(self,tgt,arg):
''' Asynchronously send a command to connected minions '''
params = {'client': 'local_async', 'tgt': tgt, 'fun': 'state.sls', 'arg': arg}
obj = urllib.urlencode(params)
self.token_id()
content = self.postRequest(obj)
jid = content['return'][0]['jid']
return jid
def target_deploy(self,tgt,arg):
''' Based on the node group forms deployment '''
params = {'client': 'local_async', 'tgt': tgt, 'fun': 'state.sls', 'arg': arg, 'expr_form': 'nodegroup'}
obj = urllib.urlencode(params)
self.token_id()
content = self.postRequest(obj)
jid = content['return'][0]['jid']
return jid
def main():
sapi = SaltAPI(url='https://172.25.0.3:8000',username='saltapi',password='westos')
sapi.token_id()
print sapi.list_all_key()
#sapi.delete_key('test-01')
#sapi.accept_key('test-01')
sapi.deploy('*','httpd.apache')
#print sapi.remote_noarg_execution('test-01','grains.items')
if __name__ == '__main__':
main()
测试:
[root@server1 ~]# python saltapi.py
([u'server1', u'server2', u'server3'], [])
[root@server3 ~]# /etc/init.d/nginx stop
Stopping nginx: [ OK ]
##更改文件
[root@server1 ~]# vim saltapi.py
################
118 #print sapi.list_all_key()
121 sapi.deploy('server3','nginx.service')
[root@server1 ~]# python saltapi.py
##测试:
[root@server3 ~]# ps ax
PID TTY STAT TIME COMMAND
6025 ? Ss 0:00 nginx: master process /usr/local/nginx/sbin/nginx -c /usr/l
6028 ? S 0:00 nginx: worker process
6029 ? S 0:00 nginx: worker process
6043 pts/0 R+ 0:00 ps ax
补充:
网络出现问题该怎么解决?
##ping不通通网段的ip该怎么办?
[root@foundation52 Desktop]# ping 172.25.254.251
PING 172.25.254.251 (172.25.254.251) 56(84) bytes of data.
From 172.25.254.52 icmp_seq=1 Destination Host Unreachable
From 172.25.254.52 icmp_seq=2 Destination Host Unreachable
From 172.25.254.52 icmp_seq=3 Destination Host Unreachable
From 172.25.254.52 icmp_seq=4 Destination Host Unreachable
^Z
[1]+ Stopped ping 172.25.254.251
##发现网桥自动断开了
[root@foundation52 Desktop]# brctl show
bridge name bridge id STP enabled interfaces
br0 8000.000000000000 no
docker0 8000.0242a9235b74 no
virbr0 8000.52540066ca08 yes virbr0-nic
virbr1 8000.52540084f928 yes virbr1-nic
[root@foundation52 Desktop]# cd /etc/
##查看到enp0s25存在
[root@foundation52 etc]# cd sysconfig/network-scripts/
[root@foundation52 network-scripts]# ls
ifcfg-br0 ifdown-ib ifup-aliases ifup-sit
ifcfg-enp0s25 ifdown-ippp ifup-bnep ifup-Team
ifcfg-lo ifdown-ipv6 ifup-eth ifup-TeamPort
ifcfg-OPPO_R11 ifdown-isdn ifup-ib ifup-tunnel
ifcfg-Wired_connection_1 ifdown-post ifup-ippp ifup-wireless
ifcfg-Wired_connection_2 ifdown-ppp ifup-ipv6 init.ipv6-global
ifcfg-Wired_connection_3 ifdown-routes ifup-isdn keys-OPPO_R11
ifcfg-Wired_connection_4 ifdown-sit ifup-plip keys-婷
ifcfg-婷 ifdown-Team ifup-plusb network-functions
ifdown ifdown-TeamPort ifup-post network-functions-ipv6
ifdown-bnep ifdown-tunnel ifup-ppp
ifdown-eth ifup ifup-routes
##手动将enp0s25网桥桥接上去
[root@foundation52 network-scripts]# brctl addif br0 enp0s25
##查看到桥接成功
[root@foundation52 network-scripts]# brctl show
bridge name bridge id STP enabled interfaces
br0 8000.0021cc6f6201 no enp0s25
docker0 8000.0242a9235b74 no
virbr0 8000.52540066ca08 yes virbr0-nic
virbr1 8000.52540084f928 yes virbr1-nic
[root@foundation52 network-scripts]# ping 172.25.254.251
PING 172.25.254.251 (172.25.254.251) 56(84) bytes of data.
64 bytes from 172.25.254.251: icmp_seq=1 ttl=64 time=12.7 ms
64 bytes from 172.25.254.251: icmp_seq=2 ttl=64 time=6.37 ms
^Z
[3]+ Stopped ping 172.25.254.251
版权声明:本文为love_sunshine_999原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。