CentOS7 SAMBA服务器搭建

samba有三个模式: share|user|domain,平常使用也就是用user模式,也就是使用samba服务器本身的密码资料库,跟passsdb backend有关。

安装软件:

# yum install samba -y

配置SMABA:

# vim /etc/samba/smb.conf
Bash
[global]
workgroup = SAMAB
netbios name = CentOS
server string = This is  samba server
unix charset = utf8
display charset = utf8
dos charset = cp950
log file = /var/log/samba/log.%m
max log size = 50
load printers = no
#与密码有关的设定项目
security = user <==这行就是重点啦!改成user层级
passdb backend = tdbsam <==使用的是TDB资料库格式!
# 分享的资源设定方面:删除temp加入homes与project
[homes] <==分享的资源名称,登入samba的账户的家目录,这个可以不考虑配置
comment = Home Directories
browseable = no <==除了使用者自己外,不可被其他人浏览
writable = yes <==挂载后可读写此分享
create mode = 0664 <==建立档案的权限为664
directory mode = 0775 <= =建立目录的权限为775
[project] <==共享资源
comment = smbuser's project
path = /home/project <==实际的Linux上面的目录位置
browseable = yes <==可被其他人所浏览到资源名称(非内容)
writable = yes <==可以被写入
write list = @users <==写入者有哪些人的意思

每次改完smb.conf都重新检查一下语法正确:

# testparm

创建相应的目录:

# mkdir /home/project
# chgrp users /home/project
# chmod 2770 /home/project

创建系统账号,并设置密码

# useradd -G users smb1
#echo 1234 | passwd --stdin smb1

新增samba账号,使用刚刚创建好的系统账号:

# pdbedit -a -u smb1

输入两次密码即可

# pdbedit -L 可以列出已存在的账号
# smbpasswd smab1可以修改账号密码
# pdbedit -x -u smb1可以删除账户

设置开机自启服务

# systemctl enable smb.service
# systemctl enable nmb.service
# systemctl start smb.service
# systemctl start nmb.service

匿名登录smb服务器测试:

# smbclient -L //smbserverip

使用账号登录smb服务器测试:

# smbclient -L //serverip -U smb1

挂载测试:

# mount -t cifs //serverip/smb1 /mnt -o username=smb1

防火墙设置:

# firewall-cmd --zone=public --add-service=samba --permanent
# firewall-cmd --reload

Selinux设置:

这一步很重要,不然没法正常用的

# getsebool -a | grep samba查看samba的selinux规则
# setsebool -P samba_enable_home_dirs=1
# chcon -t samba_share_t /home/project也可以用# restorecon -Rv '/home/project'

完事在windows上挂载试试就没问题了。

CentOS7 Samba简单配置

1. 安装

yum -y install samba

# 备份配置文件
cp  /etc/samba/smb.conf  /etc/samba/smb.conf.bak

# 创建samba用户
# 首先 添加系统用户
useradd officecoop
rm -rf /home/officecoop/.*
# 然后添加smb用户,按提示输入密码
smbpasswd -a officecoop

其他注意 iptables(或防火墙配置) 和 selinux 配置

2. 设置共享目录

2.1 目标

windows 访问 10.0.209.140 (假设samba服务器假设在140) 时显示 officecoop 目录

2.2 步骤

# 追加如下内容到配置文件
cat >> /etc/samba/smb.conf << EOF
[officecoop]
comment = officecoop
path = /home/officecoop/officecoop
writable = yes
EOF

# 创建文件夹
mkdir /home/officecoop/officecoop

# 设置属主
chmod officecoop /home/officecoop/officecoop

# 重启服务
systemctl restart smb

saltstack/salt的state.sls和pillar定义以及使用

SLS(代表SaLt State文件)是Salt State系统的核心。SLS描述了系统的目标状态,由格式简单的数据构成。这经常被称作配置管理 首先,在master上面定义salt的主目录,默认是在/srv/salt/下面,vim /etc/salt/master:

file_roots:
   base:
     - /srv/salt
   dev:
    - /srv/salt-dev

然后,在/srv/salt下面创建top.sls文件(如果有的话,就不用创建了,直接编辑好了) vim top.sls

base:
  '*':

top.sls 默认从 base 标签开始解析执行,下一级是操作的目标,可以通过正则,grain模块,或分组名,来进行匹配,再下一级是要执行的state文件

base:
  '*':               #通过正则去匹配所有minion
    - nginx          #这里都是我自己写的state.sls模块名 这里可以无视 后面会提到

  my_app:             #通过分组名去进行匹配 必须要定义match:nodegroup
    - match: nodegroup
    - nginx

  'os:Redhat':        #通过grains模块去匹配,必须要定义match:grain
    - match: grain
    - nginx

整个top.sls大概的格式就是这个样子,编写完top.sls后,编写state.sls文件;

cd /srv/salt 
vim nginx.sls

nginx.sls内容:

nginx:
  pkg:               #定义使用(pkg state module)
    - installed      #安装nginx(yum安装)
  service.running:   #保持服务是启动状态
    - enable: True
    - reload: True
    - require:
      - file: /etc/init.d/nginx
    - watch:                 #检测下面两个配置文件,有变动,立马执行上述/etc/init.d/nginx 命令reload操作
      - file: /etc/nginx/nginx.conf
      - file: /etc/nginx/fastcgi.conf
      - pkg: nginx
/etc/nginx/nginx.conf:       #绝对路径
  file.managed:
    - source: salt://files/nginx/nginx.conf  #nginx.conf配置文件在salt上面的位置
    - user: root
    - mode: 644
    - template: jinja   #salt使用jinja模块
    - require:
      - pkg: nginx

/etc/nginx/fastcgi.conf:
  file.managed:
    - source: salt://files/nginx/fastcgi.conf 
    - user: root
    - mode: 644
    - require:
      - pkg: nginx

在当前目录下面(salt的主目录)创建files/nginx/nginx.conf、files/nginx/fastcgi.conf文件,里面肯定是你自己项配置的nginx配置文件的内容啦;使用salt做自动化,一般nginx都是挺熟悉的,这里不做详细解释了

测试安装:

root@salt salt # salt 'sa10-003' state.sls nginx test=True
··········这里省略输出信息
Summary
------------
Succeeded: 8
Failed:    0
------------
Total:     8

往minion上面进行推送的时候,一般salt ‘sa10-003’ state.sls nginx 这种命令;当然,也可以执行 salt sa10-003 state.highstate 这种命令会默认匹配所有的state.sls模块。其中test=True 是指测试安装 ,也就是不进行实际操作,只是查看测试效果。

state的逻辑关系列表:
include: 包含某个文件 比如我新建的一个my_webserver.sls文件内,就可以继承nginx和php相关模块配置,而不必重新编写

root@salt salt # cat my_webserver.sls 
include:
  - nginx
  - php

match: 配模某个模块,比如 之前定义top.sls时候的 match: grain match: nodegroup require: 依赖某个state,在运行此state前,先运行依赖的state,依赖可以有多个 比如文中的nginx模块内,相关的配置必须要先依赖nginx的安装

- require:
  - pkg: nginx

watch: 在某个state变化时运行此模块,文中的配置,相关文件变化后,立即执行相应操作

- watch:
  - file: /etc/nginx/nginx.conf
  - file: /etc/nginx/fastcgi.conf
  - pkg: nginx

order: 优先级比require和watch低,有order指定的state比没有order指定的优先级高,假如一个state模块内安装多个服务,或者其他依赖关系,可以使用

nginx:
  pkg.installed:
    - order:1

想让某个state最后一个运行,可以用last

Pillar是Salt非常重要的一个组件,它用于给特定的minion定义任何你需要的数据,这些数据可以被Salt的其他组件使用。这里可以看出Pillar的一个特点,Pillar数据是与特定minion关联的,也就是说每一个minion都只能看到自己的数据,所以Pillar可以用来传递敏感数据(在Salt的设计中,Pillar使用独立的加密session,也是为了保证敏感数据的安全性)。 另外还可以在Pillar中处理平台差异性,比如针对不同的操作系统设置软件包的名字,然后在State中引用等。

定义pillar数据

默认情况下,master配置文件中的所有数据都添加到Pillar中,且对所有minion可用。默认如下:

#pillar_opts: True

master上配置文件中定义pillar_roots,用来指定pillar的数据存储在哪个目录

pillar_roots:
   base:
    - /srv/salt/pillar

首先,和state系统一样,pillar也是需要一个top.sls文件作为一个入口,用来指定对象。

base:
  '*':
    - pillar #这里指定了一个pillar模块

pillar.sls文件:

############IDC################
{% if grains['ip_interfaces'].get('eth0')[0].startswith('10.10') %}
nameservers: ['10.10.9.31','10.10.9.135']
zabbixserver: ['10.10.9.234']
{% else %}
nameservers: ['10.20.9.75']
zabbixserver: ['10.20.9.234']
{% endif %}

######## nginx ########
ngx_home_dir: /var/cache/nginx

上文的IDC这块是我自己整理的通过ip来划分不同的nameserver等,这里只是放出来参考,在State文件中将可以引用Pillar数据,比如引用
ngx_home_dir:

nginx:
  pkg:
    - installed
  user.present:
    - home: {{ pillar['ngx_home_dir'] }}
    - shell: /sbin/nologin
    - require:
      - group: nginx
  group.present:
    - require:
      - pkg: nginx
  service.running:
    - enable: True
    - reload: True
    - require:
      - file: /etc/init.d/nginx
      - file: /data1/logs/nginx
    - watch:
      - file: {{ pillar['ngx_conf_dir'] }}/nginx.conf
      - file: {{ pillar['ngx_conf_dir'] }}/fastcgi.conf
      - pkg: nginx

······ 后面关于配置就省略了

在pillar内可以提前将不同的部分根据在pillar内定义好,这样统一配置的时候就可以实现根据机器实际情况配置;比如根据机器的硬件情况配置nginx的worker_processes:

user nginx;
{% if grains['num_cpus'] < 8 %}
worker_processes {{ grains['num_cpus'] }};
{% else %}
worker_processes 8;
{% endif %}
worker_rlimit_nofile 65535;
``````````具体配置省略

很多定义的时候,都可以使用到pillar来进行自定义相关数据,具体情况可以自行摸索,这里只是个举例。

SaltStack配置管理–状态间的关系

1、include的引用

需求场景:用于含有多个SLS的状态,使用include可以进行多个状态的组合

[root@linux-node1 prod]# pwd
/srv/salt/prod
[root@linux-node1 prod]# vim lamp.sls
include:
  - apache.init
  - php.init
  - mysql.init
[root@linux-node1 prod]# vim ../base/top.sls 
prod:
  'linux-node1.example.com':
    - lamp
[root@linux-node1 prod]# salt -S "192.168.56.11" state.highstate
linux-node1.example.com:
----------
          ID: apache-install
    Function: pkg.installed
        Name: httpd
      Result: True
     Comment: All specified packages are already installed
     Started: 09:29:20.324067
    Duration: 984.864 ms
     Changes:   
----------
          ID: apache-config
    Function: file.managed
        Name: /etc/httpd/conf/httpd.conf
      Result: True
     Comment: File /etc/httpd/conf/httpd.conf is in the correct state
     Started: 09:29:21.311111
    Duration: 50.95 ms
     Changes:   
----------
          ID: apache-service
    Function: service.running
        Name: httpd
      Result: True
     Comment: The service httpd is already running
     Started: 09:29:21.362769
    Duration: 52.404 ms
     Changes:   
----------
          ID: php-install
    Function: pkg.installed
      Result: True
     Comment: All specified packages are already installed
     Started: 09:29:21.415555
    Duration: 0.693 ms
     Changes:   
----------
          ID: php-config
    Function: file.managed
        Name: /etc/php.ini
      Result: True
     Comment: File /etc/php.ini is in the correct state
     Started: 09:29:21.416438
    Duration: 15.578 ms
     Changes:   
----------
          ID: mysql-install
    Function: pkg.installed
      Result: True
     Comment: All specified packages are already installed
     Started: 09:29:21.432162
    Duration: 0.542 ms
     Changes:   
----------
          ID: mysql-config
    Function: file.managed
        Name: /etc/my.cnf
      Result: True
     Comment: File /etc/my.cnf is in the correct state
     Started: 09:29:21.432807
    Duration: 38.858 ms
     Changes:   
----------
          ID: mysql-service
    Function: service.running
        Name: mariadb
      Result: True
     Comment: The service mariadb is already running
     Started: 09:29:21.471799
    Duration: 38.431 ms
     Changes:   

Summary for linux-node1.example.com
------------
Succeeded: 8
Failed:    0
------------
Total states run:     8
Total run time:   1.182 s

2、extend的使用

需求场景:软件包安装的时候,需求假设:只在node1上按装php-mbstring包,其他的机器不安装。

[root@linux-node1 prod]# pwd
/srv/salt/prod
[root@linux-node1 prod]# vim lamp.sls 
include:
  - apache.init
  - php.init
  - mysql.init

extend:
  php-install:
    pkg.installed:
      - name: php-mbstring
[root@linux-node1 prod]# salt -S "192.168.56.11" state.highstate

3、require和require_in的使用

require:我依赖谁
require_in:我被谁依赖
需求场景:如果安装不成功或者配置httpd不成功,不启动httpd

(1)require使用
[root@linux-node1 apache]# pwd
/srv/salt/prod/apache
[root@linux-node1 apache]# systemctl stop httpd
[root@linux-node1 apache]# vim init_require.sls 
apache-install:
  pkg.installed:
    - name: httpd

apache-config:
  file.managed:
    - name: /etc/httpd/conf/httpd.conf
    - source: salt://apache/files/httpd1.conf----->将此处的文件改错,模拟配置错误
    - user: root
    - group: root
    - mode: 644

apache-service:
  service.running:
    - name: httpd
    - enable: True
    - require:---------------------------->使用require,表示依赖
      - pkg: apache-install--------------->依赖的状态模块为pkg模块,id为apache-install
      - file: apache-config--------------->依赖的状态模块为file模块,id为apache-config
[root@linux-node1 apache]# salt -S "192.168.56.11" state.highstate   #执行模块提示会有报错,此时httpd不会正常启动
......
----------
          ID: apache-config
    Function: file.managed
        Name: /etc/httpd/conf/httpd.conf
      Result: False
     Comment: Source file salt://apache/files/httpd1.conf not found
     Started: 09:48:33.459243
    Duration: 40.414 ms
     Changes:   
----------
          ID: apache-service
    Function: service.running
        Name: httpd
      Result: False
     Comment: One or more requisite failed: apache.init.apache-config
     Changes:   
----------
......
Summary for linux-node1.example.com
------------
Succeeded: 6
Failed:    2
------------
Total states run:     8
Total run time:   1.110 s
[root@linux-node1 apache]# systemctl status httpd
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)
   Active: inactive (dead) since Sat 2018-01-20 09:44:04 CST; 4min 59s ago
     Docs: man:httpd(8)
           man:apachectl(8)
  Process: 65439 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=0/SUCCESS)
 Main PID: 1025 (code=exited, status=0/SUCCESS)
   Status: "Total requests: 0; Current requests/sec: 0; Current traffic:   0 B/sec"

Jan 17 10:41:59 linux-node1 systemd[1]: Starting The Apache HTTP Server...
Jan 17 10:42:02 linux-node1 systemd[1]: Started The Apache HTTP Server.
Jan 18 03:49:02 linux-node1 systemd[1]: Reloaded The Apache HTTP Server.
Jan 20 09:43:53 linux-node1 systemd[1]: Stopping The Apache HTTP Server...
Jan 20 09:44:04 linux-node1 systemd[1]: Stopped The Apache HTTP Server.


(2)require_in使用
[root@linux-node1 apache]# vim init_require_in.sls 
apache-install:
  pkg.installed:
    - name: httpd
    - require_in:------------------>被依赖
      - service: apache-service---->被依赖的模块是service,id为apache-service

apache-config:
  file.managed:
    - name: /etc/httpd/conf/httpd.conf
    - source: salt://apache/files/httpd.conf
    - user: root
    - group: root
    - mode: 644
    - require_in:
      - service: apache-service

apache-service:
  service.running:
    - name: httpd
    - enable: True

解释说明:require和require_in都能实现依赖的功能,主动和被动的关系不同

4、watch和watch_in的使用

需求场景:监控配置文件变动,重启服务或重载服务

[root@linux-node1 apache]# pwd
/srv/salt/prod/apache
[root@linux-node1 apache]# vim init_watch.sls 
apache-install:
  pkg.installed:
    - name: httpd

apache-config:
  file.managed:
    - name: /etc/httpd/conf/httpd.conf
    - source: salt://apache/files/httpd.conf
    - user: root
    - group: root
    - mode: 644

apache-service:
  service.running:
    - name: httpd
    - enable: True
    - watch:---------------------->使用watch
      - file: apache-config------->监控的模块为file,id为apache-config
[root@linux-node1 apache]# vim files/httpd.conf   #随意修改配置文件
[root@linux-node1 apache]# salt -S "192.168.56.11" state.highstate
......
----------
          ID: apache-config
    Function: file.managed
        Name: /etc/httpd/conf/httpd.conf
      Result: True
     Comment: File /etc/httpd/conf/httpd.conf updated
     Started: 10:07:14.430189
    Duration: 55.133 ms
     Changes:   
              ----------
              diff:
                  --- 
                  +++ 
                  @@ -1,4 +1,5 @@
                   #
                  +#hahahaaha--------------->检测到配置文件增加的内容
                   #hahahaaha
                   # This is the main Apache HTTP server configuration file.  It contains the
                   # configuration directives that give the server its instructions.
----------
          ID: apache-service
    Function: service.running
        Name: httpd
      Result: True
     Comment: Service restarted---------------------->将服务重启
     Started: 10:07:14.533852
    Duration: 1219.798 ms
     Changes:   
              ----------
              httpd:
                  True
......

#增加reload参数,让服务重载
[root@linux-node1 apache]# vim init_watch.sls 
apache-install:
  pkg.installed:
    - name: httpd

apache-config:
  file.managed:
    - name: /etc/httpd/conf/httpd.conf
    - source: salt://apache/files/httpd.conf
    - user: root
    - group: root
    - mode: 644

apache-service:
  service.running:
    - name: httpd
    - enable: True
    - reload: True----------------------------------->增加参数重载
    - watch:
      - file: apache-config

[root@linux-node1 apache]# salt -S "192.168.56.11" state.highstate
----------
          ID: apache-config
    Function: file.managed
        Name: /etc/httpd/conf/httpd.conf
      Result: True
     Comment: File /etc/httpd/conf/httpd.conf updated------>检测文件有变化
     Started: 10:10:08.493557
    Duration: 53.016 ms
     Changes:   
              ----------
              diff:
                  --- 
                  +++ 
                  @@ -1,4 +1,5 @@
                   #
                  +#hahahaaha
                   #hahahaaha
                   #hahahaaha
                   # This is the main Apache HTTP server configuration file.  It contains the
----------
          ID: apache-service
    Function: service.running
        Name: httpd
      Result: True
     Comment: Service reloaded---------------->服务重载
     Started: 10:10:08.596434
    Duration: 158.753 ms
     Changes:   
              ----------
              httpd:
                  True
----------
#watch_in的使用和require_in是一样的

5、unless:状态间的条件判断

需求场景:给apache的admin目录进行加密登陆查看

(1)修改配置文件,添加认证功能
[root@linux-node1 apache]# vim files/httpd.conf 
<Directory "/var/www/html/admin">
        AllowOverride All
        Order allow,deny
        Allow from all
        AuthType Basic
        AuthName "haha"
        AuthUserFile /etc/httpd/conf/htpasswd_file
        Require user admin
</Directory>


(2)修改状态文件init.sls
[root@linux-node1 apache]# vim init.sls 
apache-install:
  pkg.installed:
    - name: httpd

apache-config:
  file.managed:
    - name: /etc/httpd/conf/httpd.conf
    - source: salt://apache/files/httpd.conf
    - user: root
    - group: root
    - mode: 644

apache-auth:
  pkg.installed:
    - name: httpd-tools
  cmd.run:------>使用cmd模块的run方法
    - name: htpasswd -bc /etc/httpd/conf/htpasswd_file admin admin---->生成密码文件
    - unless: test -f /etc/httpd/conf/htpasswd_file---->unless判断条件,test -f判断为假则执行。即htpasswd文件如果不存在就执行生成密码

apache-service:
  service.running:
    - name: httpd
    - enable: True
    - reload: True
    - watch:
      - file: apache-config

[root@linux-node1 apache]# salt -S "192.168.56.11" state.highstate
......
----------
          ID: apache-auth
    Function: cmd.run
        Name: htpasswd -bc /etc/httpd/conf/htpasswd_file admin admin
      Result: True
     Comment: Command "htpasswd -bc /etc/httpd/conf/htpasswd_file admin admin" run
     Started: 10:34:54.930867
    Duration: 48.152 ms
     Changes:   
              ----------
              pid:
                  4166
              retcode:
                  0
              stderr:
                  Adding password for user admin
              stdout:
----------
          ID: apache-service
    Function: service.running
        Name: httpd
      Result: True
     Comment: Service reloaded
     Started: 10:34:55.014468
    Duration: 162.844 ms
     Changes:   
              ----------
              httpd:
                  True
......

浏览器访问192.168.56.11/admin/index.html会出现密码验证

SaltStack配置管理-3、之安装tomcat状态

1、本次使用salt简单安装tomcat环境,下面是salt的安装tomcat状态实现。

# cd /srv/salt/base/
# mkdir web     #创建一个web目录
# cd web/
# cat tomcat.sls        #安装java环境及tomcat的salt状态
jdk-install:       #状态ID
  pkg.installed:       #需要有java-1.8.0的包,没有则安装,有则什么也不做
    - name: java-1.8.0-openjdk

tomcat-install:       #状态ID
  file.managed:       #file模块的方法
    - name: /usr/local/src/apache-tomcat-8.0.46.tar.gz       #放到执行的salt-minion端的这个路径下
    - source: salt://web/files/apache-tomcat-8.0.46.tar.gz     #将salt-master端的这个文件,这里的路径可以是http的路径或者是ftp的路径。
    - user: root      #文件权限设置
    - group: root
    - mode: 755
  cmd.run:    #状态里的执行命令的模块
    - name: cd /usr/local/src && tar zxf apache-tomcat-8.0.46.tar.gz && mv apache-tomcat-8.0.46 /usr/local/ && ln -s /usr/local/apache-tomcat-8.0.46 /usr/local/tomcat
    - unless: test -L /usr/local/tomcat && test -d /usr/local/apache-tomcat-8.0.46

# mkdir -p /srv/salt/base/web/files          #创建存放文件目录并长传文件bao包
# cd /srv/salt/base/web/files && ls
apache-tomcat-8.0.46.tar.gz

2、执行状态

# salt '*' state.sls web.tomcat           #多级目录通过.来调用,和python调用模块类似

由于时间关系,更新速度不是很快,后续会做更多更新,请持续关注。

自动化运维工具之SaltStack-2、SaltStack配置管理

1、salt-master的配置文件编写格式之YAML语法说明

YAML语法数据的结构通过缩进来表示,每一级用两个空格来表示缩进,如果有下一
级结构需要以冒号结尾,连续的列表通过减号“-”来表示,减号后面需要有空格,不
是以冒号结尾的冒号后面需要有空格。

2、修改salt-master配置文件

# vim /etc/salt/master +416
416 file_roots:        #告诉salt状态文件的位置
417   base:    #base为必须存在的,
418     - /srv/salt/base      #base状态对应的文件位置
说明:/etc/salt/master 配置文件的格式是采用YAML的格式写的,所以修改需要注意
每个缩进级别由两个空格组成,不支持tabs键,有下一个级别需要以冒号结尾,列表
用“-”减号开头,注意减号后面需要有一个空格。

创建/etc/salt/master配置文件里状态文件目录:

# mkdir /srv/salt/base

修改配置后重启salt-master:

# systemctl restart salt-master

重启后测试salt-master与salt-minion端的通讯

# salt 'linux-node1' test.ping
linux-node1:
    True     #确定能成功通讯

3、使用salt写一个自动化安装apache的状态并执行

# cd /srv/salt/base
# vim apache.sls      #状态文件的名字
apache-install:    #安装状态的ID声明
  pkg.installed:    #pkg为状态模块,installed是pkg模块下的方法(即安装)
    - name: httpd    #installed方法的参数,name是一个特殊的参数(安装的东西)
注:以上整个状态的意思为:{应该有一个httpd服务,如果有则啥也不干,如果没有则下载一个}

apache-service:    #服务状态的ID
  service.running:   #service是状态模块,running是service模块下的方法(running即启动)
    - name: httpd    #方法的目标参数(启动的目标)
    - enable: True   #目标参数的动作(是否启动True则表示启动)
注:以上状态意思为{如果有httpd这个服务则启动httpd,如果没有httpd这个服务,就下载一个httpd并启动httpd}

执行这个apache状态:

[root@linux-node1 base]# salt 'linux-node1*' state.sls apache
linux-node1:      #minion端ID
----------
          ID: apache-install    #状态的ID
    Function: pkg.installed     #模块.模块的方法
        Name: httpd    #参数
      Result: True     #True为成功
     Comment: Package httpd is already installed.     #描述信息
     Started: 22:25:05.529566     #启动时间
    Duration: 1274.843 ms    #用了多少秒
     Changes:      #如果下东西了会有输出
----------
          ID: apache-service
    Function: service.running
        Name: httpd
      Result: True
     Comment: Service httpd is already enabled, and is in the desired state
     Started: 22:25:06.805143
    Duration: 268.049 ms
     Changes:   #都做了啥
              ----------
              httpd:
                  True     #启动了httpd

Summary
------------
Succeeded: 2    #成功了两个
Failed:    0
------------
Total states run:     2

执行之后即可到目标服务器去查看apache的启动装了,或者使用salt查看目标服务器的apache状态

# salt "linux-node1" cmd.run "systemctl status httpd"     #在salt-master端用此命令查看apache启动状态

本次就更新到这里,请关注后续更新,如有问题欢迎指出与交流。

自动化运维工具之SaltStack-1、SaltStack介绍及安装

1、SaltStack简介

官方网址:http://www.saltstack.com
官方文档:http://docs.saltstack.com
GitHub:https:github.com/saltstack

SaltStack是一个服务器基础架构集中化管理平台,具备配置管理、远程执行、
监控等功能,一般可以理解为简化版的puppet和加强版的func。SaltStack基于
Python语言实现,结合轻量级消息队列(ZeroMQ)与Python第三方模块
(Pyzmq、PyCrypto、Pyjinjia2、python-msgpack和PyYAML等)构建。
通过部署SaltStack环境,我们可以在成千上万台服务器上做到批量执行命令,
根据不同业务特性进行配置集中化管理、分发文件、采集服务器数据、操作系统基
础及软件包管理等,SaltStack是运维人员提高工作效率、规范业务配置与操作的利
器。

2、SaltStack特性

(1)、部署简单、方便;
(2)、支持大部分UNIX/Linux及Windows环境;
(3)、主从集中化管理;
(4)、配置简单、功能强大、扩展性强;
(5)、主控端(master)和被控端(minion)基于证书认证,安全可靠;

(6)、支持API及自定义模块,可通过Python轻松扩展。

3、SaltStack的结构

saltstack采用C/S(客户端和server端)架构,salt-master为server端,salt-minion为客户端

a)Master与Minion认证

(1)、minion在第一次启动时,会在/etc/salt/pki/minion/(该路径在/etc/salt/minion里面设置)下自动生成minion.pem(private key)和 minion.pub(public key),然后将 minion.pub发送给master。

(2)、master在接收到minion的public key后,通过salt-key命令accept minion public key,这样在master的/etc/salt/pki/master/minions下的将会存放以minion id命名的 public key,然后master就能对minion发送指令了。

b)Master与minion链接

(1)、SaltStack master启动后默认监听4505和4506两个端口。4505(publish_port)为saltstack的消息发布系统,4506(ret_port)为saltstack客户端与服务端通信的端口。如果使用lsof 查看4505端口,会发现所有的minion在4505端口持续保持在ESTABLISHED状态。

4、SaltStack基础安装与操作

(1)环境说明

192.168.1.12 安装salt-master salt-minion
192.168.1.100 安装salt-minion

1、本次操作采用CentOS 7.2系统

# cat /etc/redhat-release 
CentOS Linux release 7.2.1511 (Core) 

# uname -r
3.10.0-327.el7.x86_64

# hostname -I
192.168.1.12

# hostname -I
192.168.1.100

2、操作系统基础优化

参考博客:http://blog.51cto.com/12217917/2060136

5、yum安装SaltStack

# rpm -ivh https://repo.saltstack.com/yum/redhat/salt-repo-latest-2.el7.noarch.rpm    #两台服务器都安装rpm包

1、salt管理节点安装

# yum install -y salt-master salt-minion

2、salt所有客户端安装(被管理的机器)

# yum install -y salt-minion

6、启动Salt

1、管理端启动命令

# systemctl start salt-master      #master端启动命令
# tree /etc/salt/pki        #启动后查看目录结构
pki
└── master
    ├── master.pem     #salt-master的公钥
    ├── master.pub     #salt-master的私钥
    ├── minions
    ├── minions_autosign
    ├── minions_denied
    ├── minions_pre
    └── minions_rejected

2、配置客户端并启动客户端

# sed -n '16p' /etc/salt/minion         #修改所有客户端的配置文件
master: 192.168.56.11      #告诉客户端   salt-master是谁,:冒号后面需要有空格
注:minion配置文件的关于ID配置,{如果配置ID则使用配置里的ID作为主机通讯标记,如果不配置ID则默认以主机名作为ID为主机通讯标记(本人生产上的主机名都做修改所以这里没有配置ID),ID如果修改,需要删除之前认证的KEY,然后重新添加KEY。}
# systemctl start salt-minion        #启动客户端
注:修改客户端通讯ID的步骤{1.停止需要修改ID的salt-minion  2.salt-key 删除老的id   3.删除minion端的/etc/salt/minion_id   4.删除minion端/etc/salt/pki  5.修改minion配置文件的id   6.启动minion   7.master端重新salt-key加入}

# tree      #启动后查看客户端的结构
.
├── minion
├── minion.d
├── minion_id
└── pki
    └── minion
        ├── minion.pem    #minion的公钥
        └── minion.pub    #minion的私钥

7、在master端添加客户端

说明:这一步操作就相当与签劳动合同,表示客户端(salt-minion)接受server端(salt-master)管理。

# salt-key          #查看客户端的命令
Accepted Keys:    #已经同意的key有哪些
Denied Keys:      #拒绝的key有哪些
Unaccepted Keys:    #未同意的key有哪些
linux-node1     #客户端的通讯ID(由于前面没有配置,这里以主机名的形式出现)
linux-node2     #客户端的通讯ID(由于前面没有配置,这里以主机名的形式出现)

# salt-key -A        #-A表示同意所有的客户端通讯ID
The following keys are going to be accepted:
Unaccepted Keys:
db02-36
saltstack-41
Proceed? [n/Y] y    #确认信息,是否同意这两个key
Key for minion linux-node1
Key for minion linux-node2

关于salt-key的参数
-d 删除单个key,也支持*号模糊匹配删除   (针对key的操作)
-D 删除所有key,慎用                    (针对key的操作)
-L 列表                                 (远程执行、列表key等)
-A 同意所有key                          (针对key的操作)
-a 同意单个,可以用*号迷糊匹配添加      (针对key的操作)
-G 匹配Grains                           (远程执行)
-I 匹配Pillar                             (远程执行)
-E 支持正则表达式                       (远程执行)
-S 指定客户端的ip地址                   (远程执行)
-C 一条远程执行的命令同时支持多个参数   (远程执行)
-N 支持节点组                           (远程执行)
更多操作请通过salt-key --help来查看

8、master端确认是否能连接到客户端(salt-minion端)

1、测试所有客户端是否能通讯

# salt '*' test.ping        #{*为通配符,表示所有。test为模块,ping为test模块下的一个方法(测试是否能通讯)}
linux-node2
    True      #True为通,False为失败
linux-node1
    True

2、远程执行shell命令

# salt ' linux-node2 ' cmd.run "w"       #单独指定某个客户端的通讯ID表示在这台客户端执行(cmd.cun表示执行shell命令,支持linux下所有的shell命令)
linux-node2:
     20:26:56 up  2:10,  1 user,  load average: 0.00, 0.01, 0.05

本次就介绍到这里,如有问题欢迎指出与交流。

rsync备份同步文件

一、介绍

Rsync具有可使本地和远程两台主机之间的数据快速复制同步镜像、远程备份的功能。
cp,scp等工具拷贝均为完整的拷贝,而rsync除了可以完整拷贝外,还具有增量拷贝的功能。

官方文档:https://www.samba.org/ftp/rsync/rsync.html

二、常见应用场景

1) rsync+crontab 数据同步
2)实时数据同步rsync+inotify

三、工作模式(三种)

1)单个主机本地直接的数据传输

rsync -avz   /etc/hosts    /tmp        相当于cp
rsync -avz  --delete  /null/  /tmp/   相当于rm

2)remote shell

push:   rsync -avzP -e ' ssh -p 22'   /tmp/  [email protected] :/tmp/
pull :      rsync -avzP -e ' ssh -p  22'  [email protected] :/tmp/   /tmp/

3)rsync daemon

四、rsync 服务端配置

1)vi /etc/rsyncd.conf(需要手动生成)

uid = root  
gid = root   
user chroot = no   
max connections = 20   
timeout = 60  
pid file = /var/run/rsyncd.pid   
lock file = /var/run/rsyncd.lock  
motd file = /etc/rsyncd.motd     
log file = /var/log/rsyncd.log   
[backup]   
path = /backup   
ignore errors   
read only = no   
list = no   
hosts allow = 192.168.1.101  
auth users = rsync   
secrets file =/etc/rsyncd.pwd  

2)创建rsync用户及共享目录/backup

useradd rsync -s   /sbin/nologin -M
id  rsync
mkdir /backup
chown -R  rsync  /backup

3)创建密码文件

echo "rsync:123456">/etc/rsyncd.pwd
chmod 600  /etc/rsync.password

4)启动服务

/usr/bin/rsync  --deamon
netstat   -lntup |grep  rsync
ps  -ef |grep rsync |grep -v grep

5)加入开机自启动

echo "/usr/bin/rsync --deamon">>/etc/rc.local
cat  /etc/rc.local

五、rsync客户端配置

1、客户端不用配置,直接使用rsync命令就可以,

rsync -vzrtopg --progress --delete [email protected]::backup  /data/
rsync -vzrtopg --progress --delete /data/  [email protected]::backup

2、rsync无密码登陆,客户端需配置密码文件,只包含服务器端auth user的密码,不需要配置用户名 。

vim /etc/rsyncd.pwd 
123456
chmod 600  /etc/rsyncd.pwd

注:此处密码一定要与rsync服务器端密码文件中密码保持一致。

rsync -vzrtopg --progress --delete --password-file=/etc/rsyncd.pwd [email protected]::backup /data/
rsync -vzrtopg --progress --delete --password-file=/etc/rsyncd.pwd /data/ [email protected]::backup

3、rsync定时任务(备份本地目录/data/到服务端192.168.1.100)

crontab -e
0 1  * * *  rsync -vzrtopg --progress --delete --password-file=/etc/rsyncd.pwd /data/ [email protected]::backup

4、Rsync 同步参数说明

-vzrtopg里的v是verbose,z是压缩,r是recursive,topg都是保持文件原有属性如属主、时间的参数。
–progress是指显示出详细的进度情况
–delete是指如果服务器端删除了这一文件,那么客户端也相应把文件删除

5、rsync常用参数:

#rsync [option] 源路径 目标路径
其中[option]为:

a:使用archive模式,等于-rlptgoD,即保持原有的文件权限
z:表示传输时压缩数据
v:显示到屏幕中
e:使用远程shell程序(可以使用rsh或ssh)

–delete:精确保存副本,源主机删除的文件,目标主机也会同步删除
–include=PATTERN:不排除符合PATTERN的文件或目录
–exclude=PATTERN:排除所有符合PATTERN的文件或目录
–password-file:指定用于rsync服务器的用户验证密码

六、rsync常见错误排错

1、

rsync: failed to connect to 118.244.216.177: No route to host (113)

rsync error: error in socket IO (code 10) at clientserver.c(124) [receiver=3.0.6]

原因:防火墙屏蔽了端口

解决:打开873段考

iptables -i INPUT -p tcp --dport 873 -j ACCEPT
iptables -L

如果以上指令不行,可以直接停掉防火墙

/etc/init.d/iptables stop

2、

@ERROR: auth failed on module backup

rsync error: error starting client-server protocol (code 5) at main.c(1506) [Receiver=3.0.7]

检查密码文件设置权限 chmod 600 /etc/rsyncd.pwd

3、

@ERROR: auth failed on module xxxxx

rsync: connection unexpectedly closed (90 bytes read so far)

rsync error: error in rsync protocol data stream (code 12) at io.c(150)

这是因为密码设错了, 无法登入成功, 请检查一下 rsyncd.scrt 中的密码, 二端是否一致?

4、

password file must not be other-accessible

continuing without password file

Password:

这表示 rsyncd.pwd 的档案权限属性不对, 应设为 600。

5、

@ERROR: chroot failed

rsync: connection unexpectedly closed (75 bytes read so far) 

rsync error: error in rsync protocol data stream (code 12) at io.c(150)

这通常是您的 rsyncd.conf 中的 path 路径所设的那个目录并不存在所致.请先用 mkdir开设好要备份目录

6、

@ERROR: access denied to www from unknown (192.168.1.123)

rsync: connection unexpectedly closed (0 bytes received so far) [receiver]

rsync error: error in rsync protocol data stream (code 12) at io.c(359)

最后原因终于找到了。因为有两个网段都需要同步该文件夹内容,但没有在hosts allow 后面添加另一个IP段

hosts allow = 192.168.1.0/24

改为

hosts allow = 192.168.1.0/24 192.168.2.0/24

重新启动rsync服务,问题解决

7、

@ERROR: auth failed on module backup

rsync error: error starting client-server protocol (code 5) at 
main.c(1506) [Receiver=3.0.7]

client端没有设置/etc/rsyncd.pwd这个文件,而在使用rsync命令的时候,加了这个参数–password-file=/etc/rsyncd.pwd

8、

rsync: recv_generator: mkdir "/teacherclubBackup/rsync……" failed: No space left on device (28)

*** Skipping any contents from this failed directory ***

磁盘空间满了

9、

rsync: opendir "/backup" (in dtsChannel) failed: Permission denied (13)

同步目录的权限设置不对,改为755

10、

rsync: read error: Connection reset by peer (104)

rsync error: error in rsync protocol data stream (code 12) at io.c(759) [receiver=3.0.5]

未启动xinetd守护进程

[root@CC02 /]# service xinetd start

11、

rsync: unable to open configuration file "/etc/rsyncd.conf": No such file or directory

xnetid查找的配置文件位置默认是/etc下,在/etc下找不到rsyncd.conf文件

12、

rsync: failed to connect to 203.100.192.66: Connection timed out (110)

rsync error: error in socket IO (code 10) at clientserver.c(124) [receiver=3.0.5]

连接服务器超时,检查服务器的端口netstat –tunlp,远程telnet测试

13、我需要在防火墙上开放哪些端口以适应rsync?

视情况而定。rsync可以直接通过873端口的tcp连接传文件,也可以通过22端口的ssh来进行文件传递,但你也可以通过下列命令改变它的端口:

rsync --port 8730 otherhost::

或者

rsync -e 'ssh -p 2002' otherhost:

14、我如何通过rsync只复制目录结构,忽略掉文件呢?

rsync -av --include '*/' --exclude '*' source-dir dest-dir

15、为什么我总会出现”Read-only file system”的错误呢?

看看是否忘了设”read only = no”了

16、

@ERROR: chroot failed

rsync error: error starting client-server protocol (code 5) at 
main.c(1522) [receiver=3.0.3]

原因:

服务器端的目录不存在或无权限。创建目录并修正权限可解决问题。

17、

@ERROR: auth failed on module backup

rsync error: error starting client-server protocol (code 5) at main.c(1522) [receiver=3.0.3]

原因:
服务器端该模块(tee)需要验证用户名密码,但客户端没有提供正确的用户名密码,认证失败。提供正确的用户名密码解决此问题。

18、

@ERROR: Unknown module ‘bcakup’

rsync error: error starting client-server protocol (code 5) at main.c(1522) [receiver=3.0.3]

原因:
服务器不存在指定模块。提供正确的模块名或在服务器端修改成你要的模块以解决问题。

19、权限无法复制。去掉同步权限的参数即可。(这种情况多见于Linux向Windows的时候)
(备份本地目录/data/到服务端192.168.1.100)

Linux VPS采用Rsync实现网站文件/服务器数据同步增量备份

无论我们选择虚拟主机,还是选择VPS、服务器,最为关键的就是服务器中的数据。相对而言,选择优质服务商和服务器的意外几率会小一些,但也不是没有。因为服务器的意外不是商家和我们用户控制的,包括服务器中程序的问题,也可能是我们人为的操作问题。

如果网站数据量不大,我们可以采用定期人工备份或者利用定时备份脚本。一键包环境或者是WEB面板都带有自动备份到本地和远程服务器的功能。如果数据量较大,我们其实可以采用Rsync实现同步增量备份。下面的记录是通过Rsync实现文件同步增量备份的。
设置过程却是比较繁琐,如果我们普通项目用户可以使用商家自带的快照定时或者脚本环境带的自动备份功能,以及我们自己的定期备份。(本文来自:https://www.laobuluo.com/1070.html)

第一、准备工作

1、数据备份

如果我们没有把握一次性搞定,我们可以准备两台测试环境服务器实现Rsync同步备份功能之后再用到生产环境。如果用到生产环境,我们可以将服务器快照备份,或者将网站、项目数据备份。

2、服务器准备

这里我们采用的是Rsync同步增量备份,所以我们需要准备主服务器、以及一台备份服务器。鉴于数据备份后的功能,我们可以直接备份到备份服务器某一个目录,或者将备份服务器安装主服务器环境,将需要备份的网站项目备份到对应的同目录中。

3、端口开放

如果我们服务器没有设定iptables防火墙规则,那就不要设置端口。如果我们有设置iptables防火墙,那就需要将873端口添加放行。

vi /etc/sysconfig/iptables

打开iptables规则文档,添加:

-A INPUT -p tcp -m state --state NEW -m tcp --dport 873 -j ACCEPT

未分类

编辑保存之后,然后/etc/init.d/iptables restart重启才能生效。同样的方法,我们需要在主服务器和备份服务器同时设置。

第二、配置备份服务器

1、安装rsync

未分类

2、配置文件

vi /etc/xinetd.d/rsync

将配置文件disable参数从”yes”换成”no”。

3、创建配置文件

vi /etc/rsyncd.conf

创建文件,然后将下面脚本添加:

log file = /var/log/rsyncd.log
pidfile = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
secrets file = /etc/rsync.pass
motd file = /etc/rsyncd.Motd
#创建一个模块名称,后面需要一致
[www.laobuluo.com]
#备份服务器目录地址
path = /home/wwwroot/www.laobuluo.com
#对应上面模块名称
comment = www.laobuluo.com
uid = root
gid = root
port = 873
use chroot = no
read only = no
list = no
max connections = 200
timeout = 600
#创建一个同步用户名,随便取,反正后面出现的时候要一致
auth users = www.laobuluo.com_user
#主服务器IP地址
hosts allow = xxx.xxx.xxx.xxx

根据我们网站项目以及服务器实际信息创建文件贴到配置文件中保存退出。

4、创建密码配对文件

vi /etc/rsync.pass

创建密码配对文件:

www.laobuluo.com_user:1234567890passwd

红色字段需要对应上面的auth users,蓝色部分是我们创建配对的密码。后面主服务器配置的时候也需要用到密码,所以必须一致。

5、开放权限和启动

chmod 600 /etc/rsyncd.conf
chmod 600 /etc/rsync.pass
service xinetd restart

未分类

第三、配置主服务器

1、安装rsync

yum install rsync xinetd -y

未分类

2、配置文件

vi /etc/xinetd.d/rsync

未分类

将配置文件disable参数从”yes”换成”no”。

3、创建密码配对文件

未分类

将我们上面在备份服务器中蓝色的密码丢进来,必须一致。

4、授权和启动

未分类

第四、配置主服务器

这一步我们继续配置主服务器,需要安装和配置inotify-tools来实现同步增量备份。

1、安装环境包

yum install make gcc gcc-c++ -y

未分类

2、下载和安装inotify-tools

cd /usr/local/src
wget https://download.laobuluo.com/tools/inotify-tools-3.14.tar.gz
tar -zxvf inotify-tools-3.14.tar.gz
cd inotify-tools-3.14
./configure --prefix=/usr/local/inotify
make
make install

未分类

3、配置环境变量

echo "PATH=/usr/local/inotify/bin:$PATH" >>/etc/profile.d/inotify.sh
source /etc/profile.d/inotify.sh
echo "/usr/local/inotify/lib" >/etc/ld.so.conf.d/inotify.conf
ln -s /usr/local/inotify/include /usr/include/inotify

4、配置参数

未分类

参考就脚本 – http://soft.laozuo.org/scripts/rsync.sh

修改自行的文件和目录,然后保存退出。

5、创建排除目录列表

vi /usr/local/inotify/exclude.list

创建一个排除目录,这里可以添加不同步的目录,一行一个目录。如果暂时没有可以留空,以后需要用到在添加。

6、授权和设置开机启动

chmod +x /usr/local/inotify/rsync.sh

这里我们授权。

vi /etc/rc.d/rc.local

最后一行添加:

sh /usr/local/inotify/rsync.sh &

未分类

第五、检测以及生效小结

1、检查生效

设置完毕之后,我们可以通过手工检查

sh /usr/local/inotify/rsync.sh &

在主服务器执行脚本,如果看到有目录在进度,说明完美,然后去备份服务器中可以看到已经备份到的文件目录。

未分类

2、自动生效

重启主服务器,然后就会自动生效。如果不放心我们可以在主服务器对应目录丢一个文件看看备份服务器是否有增加。

总结,这篇文章较为详细的将Linux VPS、服务器使用Rsync进行同步增量备份文件。

使用Python和Flask编写Prometheus监控

Installation

pip install flask
pip install prometheus_client

Metrics

Prometheus提供4种类型Metrics:Counter, Gauge, Summary和Histogram

Counter

Counter可以增长,并且在程序重启的时候会被重设为0,常被用于任务个数,总处理时间,错误个数等只增不减的指标。

import prometheus_client
from prometheus_client import Counter
from prometheus_client.core import CollectorRegistry
from flask import Response, Flask
app = Flask(__name__)
requests_total = Counter("request_count", "Total request cout of the host")
@app.route("/metrics")
def requests_count():
    requests_total.inc()
    # requests_total.inc(2)
    return Response(prometheus_client.generate_latest(requests_total),
                    mimetype="text/plain")
@app.route('/')
def index():
    requests_total.inc()
    return "Hello World"
if __name__ == "__main__":
    app.run(host="0.0.0.0")

运行改脚本,访问youhost:5000/metrics

# HELP request_count Total request cout of the host
# TYPE request_count counter
request_count 3.0

Gauge

Gauge与Counter类似,唯一不同的是Gauge数值可以减少,常被用于温度、利用率等指标。

import random
import prometheus_client
from prometheus_client import Gauge
from flask import Response, Flask
app = Flask(__name__)
random_value = Gauge("random_value", "Random value of the request")
@app.route("/metrics")
def r_value():
    random_value.set(random.randint(0, 10))
    return Response(prometheus_client.generate_latest(random_value),
                    mimetype="text/plain")
if __name__ == "__main__":
    app.run(host="0.0.0.0")

运行改脚本,访问youhost:5000/metrics

# HELP random_value Random value of the request
# TYPE random_value gauge
random_value 3.0

Summary/Histogram

Summary/Histogram概念比较复杂,一般exporter很难用到,暂且不说。

PLUS

LABELS

使用labels来区分metric的特征

from prometheus_client import Counter
c = Counter('requests_total', 'HTTP requests total', ['method', 'clientip'])
c.labels('get', '127.0.0.1').inc()
c.labels('post', '192.168.0.1').inc(3)
c.labels(method="get", clientip="192.168.0.1").inc()

REGISTRY

from prometheus_client import Counter, Gauge
from prometheus_client.core import CollectorRegistry
REGISTRY = CollectorRegistry(auto_describe=False)
requests_total = Counter("request_count", "Total request cout of the host", registry=REGISTRY)
random_value = Gauge("random_value", "Random value of the request", registry=REGISTRY)