RHCE---服务+ansible

一、命令提示符颜色

也可以写入配置文件/etc/profile
[root@master ~]# vim .bashrc 
绿色:
PS1='\[\033[01;32m\]\u@\H:\[\033[01;34m\]\w\$\[\033[00m\] '
粉红色:
PS1='\[\e[1;35m\]\u@\h:\[\e[0m\]\[\e[1;33m\]\w\[\e[1;35m\]\[\e[0m\]\[\e[1;34m\]\$ \[\e[0m\]'
[root@master ~]# source .bashrc

详解:

[root@master ~]# echo $PS1
[\u@\h \W]\$
那么里面的 [\u@\h \W]$分别代表什么呢?
PS1(是数字1而不是字母l),每个版本bash的PS1变量内的特殊符号可能有些小的差异,
你可以先man bash 一下。
  下面是RedHat7环境下默认的特殊符号所代表的意义:
  \d :代表日期,格式为weekday month date,例如:"Mon Aug 1"
  \H :完整的主机名称。例如:我的机器名称为:RedHat7.linux,则这个名称就是RedHat7.linux
  \h :仅取主机的第一个名字,如上例,则为RedHat7,而.linux则被省略
  \t :显示时间为24小时格式,如:HH:MM:SS
  \T :显示时间为12小时格式
  \A :显示时间为24小时格式:HH:MM
  \u :当前用户的账号名称
  \v :BASH的版本信息
  \w :完整的工作目录名称。家目录会以 ~代替
  \W :利用basename取得工作目录名称,所以只会列出最后一个目录
  \# :下达的第几个命令
  \$ :提示字符,如果是root时,提示符为:# ,普通用户则为:$
  默认的PS1内容为: PS1='[\u@\h \W]\$ ' ,
  所以默认的提示符就是: [root@linux ~]#

当我们了解上述参数之后,在实际操作过程中,我们如果想显示主机全名以及完整的工作目录,我们就需要修改PS1的相应参数,并写入/etc/profile文件中 例如:修改前,我们默认的PS1对于主机名、目录都只是显示一部分,
[root@RedHat7 ~]# hostname
RedHat7.linux
[root@RedHat7 ~]# 
[root@RedHat7 ~]# cd /etc/sysconfig/network-scripts/
[root@RedHat7 network-scripts]#
现在我们想让主机名和工作路径全部显示出来,根据上面参数,我们需要用到大写的H和小写的w,我们用echo命令将修改后的PS1追加到 /etc/profile文件中(不建议这样操作,最好还是vim 进到文件去编辑好些),并更新该文件
[root@RedHat7 ~]# echo "PS1='[\u@\H \w]\$' " >> /etc/profile
[root@RedHat7 ~]# source /etc/profile
如果是在虚拟机里面或者是Xshell中,我们可能还要重启或断开连接再次连接才能看到结果。
[[email protected] ~]$ cd /etc/sysconfig/network-scripts/
[[email protected] /etc/sysconfig/network-scripts]$ 
此时,我们可以看到主机全名和工作路径的全部

 颜色值设置
 PS1中设置字符颜色的格式为:\[\e[F;Bm\],\[\e[0m\] 其中
 “F“为字体颜色,编号为30-37,
 “B”为背景颜色,编号为40-47。用 \[\e[0m\]结束颜色设置,颜色表如下:
  F    B
  30    40    黑色
  31    41    红色
  32    42    绿色
  33    43    黄色
  34    44    蓝色
  35    45    紫红色
  36    46    青蓝色
  37    47    白色
  根据颜色表,套用入字符颜色设置格式中,就可以对linux终端命令行颜色进行个性化设置。
  比如要设置命令行的格式为绿字黑底,显示当前用户的账号名称、
  主机的第一个名字、完整的当前工作目录名称、24小时格式时间,就可以使用如下的命令:
 
  export PS1='\[\e[30;1m\][\u@\h \w]\$ \[\e[0m\]  -----黑色提示符
  export PS1='\[\e[31;1m\][\u@\h \w]\$ \[\e[0m\]  -----红色提示符
  export PS1='\[\e[32;1m\][\u@\h \w]\$ \[\e[0m\]  -----绿色提示符
  export PS1='\[\e[33;1m\][\u@\h \w]\$ \[\e[0m\]  -----黄色提示符
  export PS1='\[\e[34;1m\][\u@\h \w]\$ \[\e[0m\]  -----蓝色提示符(天蓝)
  export PS1='\[\e[35;1m\][\u@\h \w]\$ \[\e[0m\]  -----粉色提示符
  export PS1='\[\e[36;1m\][\u@\h \w]\$ \[\e[0m\]  -----蓝色提示符(海蓝)
  export PS1='\[\e[37;1m\][\u@\h \w]\$ \[\e[0m\]  -----白色提示符

环境准备:

1.至少俩台linux主机,一台是控制节点,一台是受控节点
2.控制节点和受控节点都需要安装Python36
3.控制节点需要安装ansible
4.控制节点需要获得受控节点的普通用户或root用户的权限,控制节点需要ssh客户端,受控节点需要ssh服务端
5.控制节点和受控节点之间网络联通,配置静态ip

二、环境安装:

主机名 IP地址 角色
master 172.25.250.132 控制节点
node01 172.25.250.128 受控节点
node02 172.25.250.129 受控节点

1、替换yum源,方便安装软件:----阿里

sed -e 's|^mirrorlist=|#mirrorlist=|g' \
    -e 's|^#baseurl=http://dl.rockylinux.org/$contentdir|baseurl=https://mirrors.aliyun.com/rockylinux|g' \
    -i.bak \
    /etc/yum.repos.d/Rocky-*.repo

dnf makecache

2、安装常用工具:

yum install -y bash-completion tree lrzsz  vim  net-tools.x86_64  unzip   lsof  wget

3、修改主机名:

master: hostnamectl set-hostname master
node01:hostnamectl set-hostname node01
node02:hostnamectl set-hostname node02

4、配置ip地址:

master:俩张网卡NAT和桥接模式

node01 node02:桥接模式

master主机上的配置:
1.查看状态:

[root@master ~]# nmcli device
DEVICE  TYPE      STATE                                  CONNECTION
ens160  ethernet  connected                              ens160
ens224  ethernet  connecting (getting IP configuration)  Wired connection 1
lo      loopback  unmanaged                              --
[root@master ~]# nmcli connection
NAME                UUID                                  TYPE      DEVICE
Wired connection 1  408f15fc-eaa9-3a51-ae18-d9673dcbabab  ethernet  ens224
ens160              b4725590-2691-43b0-b2a8-7eae81ee470a  ethernet  ens160


2、添加ip,网关,dns,改为手动,开机自启
[root@master ~]# cd /etc/sysconfig/network-scripts/
[root@master network-scripts]# ll
total 4
-rw-r--r--. 1 root root 247 Dec 13 09:34 ifcfg-ens160
[root@master network-scripts]# cat ifcfg-ens160
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=dhcp
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
NAME=ens160
UUID=b4725590-2691-43b0-b2a8-7eae81ee470a
DEVICE=ens160
ONBOOT=yes ---改为yes

3、修改master主机桥接网卡的ip地址:
[root@master ~]# nmcli device
DEVICE  TYPE      STATE                                  CONNECTION
ens160  ethernet  connected                              ens160
ens224  ethernet  connecting (getting IP configuration)  Wired connection 1
lo      loopback  unmanaged       
[root@master network-scripts]# nmcli device  connect ens224 ---自动创建connection,如果有俩个网段就可以实现
但是我在家在学校只有一个192.168.x.x的地址,包括后面俩台node也配不上
[root@master network-scripts]# nmcli device connect ens224
Error: Connection activation failed: (5) IP configuration could not be reserved (no available address, timeout, etc.).

5、网卡改为仅主机模式:

仅主机:172.25.250.x 255.255.255.0

master:192.168.11.154---NAT模式,都可以连接

master:172.25.250.132
node01:172.25.250.128
node02:172.25.250.129

6、配置hosts文件:

172.25.250.132 master
172.25.250.128 node01
172.25.250.129 node02

7、xshell配置会话:

172.25.250.132 master
172.25.250.128 node01
172.25.250.129 node02

8、时间同步:

这里我使用的是仅主机模式,所以受控节点的主机没有互联网,但是三台主机的时间一样的,我就不做配置

1、安装时间同步软件包:
[root@master ~]# yum install chrony

2、修改配置文件:
[root@master ~]# vim /etc/chrony.conf
pool 2.rocky.pool.ntp.org iburst
pool ntp1.aliyun.com iburst
pool ntp2.aliyun.com iburst

3、设置为开机自启:
[root@master ~]# systemctl enable --now chronyd

4、写计划任务同步:

[root@master ~]# vim /etc/crontab
0 10  * * * root  chronyc sources &>/dev/null

9、装Python36:

1、每台机器都装:接下来的操作都在master上
yum install python36 -y

2、不用root权限,权限太高了;在master主机上创建student 密码redhat;在node节点上用的redhat用户,密码redhat
[root@node01 ~]# vim /etc/sudoers
root    ALL=(ALL)       ALL
redhat ALL=(ALL)       NOPASSWD: ALL
强制保存退出
如果用的visudo打开就不用,正常退出就行


3、测试:
[root@master ~]# visudo
[root@master ~]#
[root@master ~]#
[root@master ~]# su - student
Last login: Tue Dec 13 12:17:40 CST 2022 on pts/0
[student@master ~]$ sudo ls /root
anaconda-ks.cfg

10、安装ansible:

1、阿里云下载扩展源:epel
[student@master ~]$ sudo yum install -y https://mirrors.aliyun.com/epel/epel-release-latest-8.noarch.rpm

也可以自己写源:
[epel]
name=epel
baseurl=https://mirrors.aliyun.com/epel/8/Everything/x86_64/
gpgcheck=0

2、安装ansible:
[student@master ~]$ yum install ansible -y

3、查看ansible版本信息:
[student@master ~]$ ansible --version
ansible [core 2.13.3]
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/home/student/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.9/site-packages/ansible
  ansible collection location = /home/student/.ansible/collections:/usr/share/ansible/collections
  executable location = /usr/bin/ansible
  python version = 3.9.13 (main, Nov 16 2022, 15:31:39) [GCC 8.5.0 20210514 (Red Hat 8.5.0-15)]
  jinja version = 3.1.2
  libyaml = True

11、配置免密登录:

1、在master主机上创建密钥对:
[student@master ~]$ ssh-copy-id redhat@node02
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/student/.ssh/id_rsa.pub"
The authenticity of host 'node02 (172.25.250.129)' can't be established.
ECDSA key fingerprint is SHA256:723ytDI+oeyH5SeBHONt70U2NspX11SZ5lwzBASGLy4.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
redhat@node02's password:输入密码

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'redhat@node02'"
and check to make sure that only the key(s) you wanted were added.

2、测试:
在master连接node节点:
[student@master ~]$ ssh redhat@node01
Last login: Tue Dec 13 12:12:43 2022
[redhat@node01 ~]$

12、环境搭好了,做好快照

所有的密码都是redhat

三、简单操作:

ansible清单和配置文件

1、定义清单文件:

1、创建一个文件夹存放::
[student@master ~]$ mkdir ansibleTest
[student@master ~]$ cd ansibleTest/
[student@master ansibleTest]$

2、编写文件,注意优先级
[student@master ~]$ sudo vim /etc/ansible/hosts
这是在默认配置文件中的主机清单文件:
[student@master ~]$ tail -2 /etc/ansible/hosts
node01
node02

这是在自定义的主机清单文件,-i指定清单文件文件名:
[student@master ansibleTest]$ ansible all --list-hosts -i ./inventory
  hosts (3):
    node01
    node02
    master
这是查看主机组里面的主机文件:
[student@master ansibleTest]$ ansible webserver --list-hosts -i ./inventory
  hosts (2):
    node01
    node02

2、执行清单文件:

[student@master ~]$ ansible all --list-hosts
  hosts (2):
    node01
    node02

3、修改配置文件

1、自定义ansible.cfg,这几条信息都需要写
[student@master ansibleTest]$ cat ./ansible.cfg
[defaults]
inventory= ./inventory
remote_user = redhat
ask_pass = false
[privilege_escalation]
become = True
become_method = sudo
become_user = root
become_ask_pass = False

4、简单测试:

1.masterping不通。因为没有免密做student免密登录redhat:
[student@master ansibleTest]$ ansible all -m ping
The authenticity of host 'master (172.25.250.132)' can't be established.
ECDSA key fingerprint is SHA256:NeqtJaCF7cvzBynyHDzGp4j1w6qIRrF2du45YRldvB8.
Are you sure you want to continue connecting (yes/no/[fingerprint])? node01 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}
node02 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}
这里master上面的redhat需要密码,但是在清单文件中是ask_pass = false,所以ping不通master
root    ALL=(ALL)       ALL
student ALL=(ALL) NOPASSWD: ALL
redhat ALL=(ALL) NOPASSWD:ALL
添加redhat进去


2、把公钥私钥用student用户传给redhat
[student@master ansibleTest]$ ssh-copy-id redhat@master
测试:
[student@master ansibleTest]$ ansible all -m ping
node02 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}
node01 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}
master | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}
学会看日志

5、几个清单文件的优先级:

[student@master ansibleTest]$ ll /etc/ansible/ansible.cfg  ~/ansible.cfg   ./ansible.cfg

运行临时命令

1、创建文件:

1、file模块:
[student@master ansibleTest]$ ansible-doc -l ---查看所有模块
[student@master ansibleTest]$ ansible-doc file ---查看file模块的用法
[student@master ansibleTest]$ ansible all -m ping -v ---ping模块
Using /home/student/ansibleTest/ansible.cfg as config file  ---使用的配制文件
node01 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}
node02 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}
master | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "ping": "pong"
}

作业:

使用yum和service模块安装和启动httpd服务,但是我node没有网,所以下载不了
[student@master ansibleTest]$ ansible all -m yum -a 'name=httpd state=present'
[student@master ansibleTest]$ ansible all -m service -a 'name=httpd state=started'

这里我把受控节点也添加了俩张网卡,一个仅主机一个NAT
[student@master ansibleTest]$ ansible all -m yum -a 'name=httpd state=present'
node01 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "msg": "Nothing to do",
    "rc": 0,
    "results": []
}
node02 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "msg": "Nothing to do",
    "rc": 0,
    "results": []
}
master | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "msg": "Nothing to do",
    "rc": 0,
    "results": []
}

测试:
[student@master ansibleTest]$ ansible all -m shell -a 'systemctl is-active httpd'
node02 | CHANGED | rc=0 >>
active
node01 | CHANGED | rc=0 >>
active
master | CHANGED | rc=0 >>
active

playbook

1、编写一个确保chrond服务开机自启:

1、安装chrony服务:---注意服务名称呀!!!!
[student@master ansibleTest]$  ansible all -m yum -a 'name=chrony state=present'
node01 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "msg": "Nothing to do",
    "rc": 0,
    "results": []
}
master | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": false,
    "msg": "Nothing to do",
    "rc": 0,
    "results": []
}
node02 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/libexec/platform-python"
    },
    "changed": true,
    "msg": "",
    "rc": 0,
    "results": [
        "Installed: timedatex-0.5-3.el8.x86_64",
        "Installed: chrony-4.2-1.el8.rocky.1.0.x86_64"
    ]
}


2、编写playbook:

---
- name: enable chronyd
  hosts: all
  tasks:
    - name: enable chrony service
      service:
        name: chronyd
        enabled: yes

3、运行playbook:
[student@master ansibleTest]$ ansible-playbook chrony_service.yaml

PLAY [enable chronyd] ************************************************************************************************************************

TASK [Gathering Facts] ***********************************************************************************************************************
ok: [node01]
ok: [node02]
ok: [master]

TASK [enable chrony service] *****************************************************************************************************************
ok: [node01]
ok: [node02]
ok: [master]

PLAY RECAP ***********************************************************************************************************************************
master                     : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
node01                     : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
node02                     : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
执行成功结果!!!

2、语法检测:

[student@master ansibleTest]$ ansible-playbook  --syntax-check chrony_service.yaml
playbook: chrony_service.yaml

实验:

案例一:安装http 启动防火墙,写入测试页index.html

1、编写playbook:

---
- name: configer web server
  hosts: webs
  tasks:
    - name: install httpd
      yum:
        name: httpd
        state: present
    - name: start firwalld
      service:
        name: firewalld
        state: started

    - name: firewalld allow httpd
      firewalld:
        service: http
        state: enabled
    - name: copy index.html
      copy:
        content: "this is web test"
        dest: /var/www/html/idnex.html
    - name: test web page
      uri:
        url: http://localhost
        return_content: yes
        status_code: 200

2、语法检测:
[student@master ansibleTest]$ ansible-playbook --syntax-check configer_server.yaml
playbook: configer_server.yaml

3、运行playbook:

[student@master ansibleTest]$ ansible-playbook configer_server.yaml

PLAY [configer web server] *******************************************************************************************************************

TASK [Gathering Facts] ***********************************************************************************************************************
ok: [node02]
ok: [node01]

TASK [install httpd] *************************************************************************************************************************
ok: [node01]
ok: [node02]

TASK [start firwalld] ************************************************************************************************************************
ok: [node02]
ok: [node01]

TASK [firewalld allow httpd] *****************************************************************************************************************
ok: [node02]
ok: [node01]

TASK [copy index.html] ***********************************************************************************************************************
changed: [node01]
changed: [node02]

TASK [test web page] *************************************************************************************************************************
ok: [node02]
ok: [node01]

PLAY RECAP ***********************************************************************************************************************************
node01                     : ok=6    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
node02                     : ok=6    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

案列二:在上一实验基础上写多个play

1、编写playbook:
[student@master ansibleTest]$ cat configer_server.yaml
---
- name: configer web server
  hosts: webs
  tasks:
    - name: install httpd
      yum:
        name: httpd
        state: present
    - name: start firwalld
      service:
        name: firewalld
        state: started

    - name: firewalld allow httpd
      firewalld:
        service: http
        state: enabled
    - name: copy index.html
      copy:
        content: "this is web test"
        dest: /var/www/html/index.html
    - name: test web page
      uri:
        url: http://localhost
        return_content: yes
        status_code: 200


- name: test web pages
  hosts: master
  tasks:
    - name: test node01 web
      uri:
        url: http://node01
        status_code: 200
    - name: test node02 web
      uri:
        url: http://node02
        status_code: 200

2、测试:

[student@master ansibleTest]$ ansible-playbook configer_server.yaml

PLAY [configer web server] *******************************************************************************************************************

TASK [Gathering Facts] ***********************************************************************************************************************
ok: [node02]
ok: [node01]

TASK [install httpd] *************************************************************************************************************************
ok: [node01]
ok: [node02]

TASK [start firwalld] ************************************************************************************************************************
ok: [node02]
ok: [node01]

TASK [firewalld allow httpd] *****************************************************************************************************************
ok: [node02]
ok: [node01]

TASK [copy index.html] ***********************************************************************************************************************
changed: [node01]
changed: [node02]

TASK [test web page] *************************************************************************************************************************
ok: [node02]
ok: [node01]

PLAY RECAP ***********************************************************************************************************************************
node01                     : ok=6    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
node02                     : ok=6    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

案例三:webserver

1、编写playbook:
---
- name: first play
  hosts: webs
  tasks:
    - name: install packages
      yum:
        name:
          - httpd
          - php
          - firewalld
          - mariadb-server
          - php-mysqlnd
        state: latest


    - name: start firewalld
      service:
        name: firewalld
        state: started
        enabled: yes

    - name: configer firewalld allow http
      firewalld:
        service: http
        permanent: yes
        state: enabled
        immediate: yes

    - name: copy index.php
      copy:
        src: index.php
        dest: /var/www/html/index.php


    - name: start httpd
      service:
        name: httpd
        state: restarted
        enabled: yes

- name: second play
  hosts: master
  become: no
  tasks:
    - name: test web1 page
      uri:
        url: http://node01
        return_content: yes
        status_code: 200

    - name: test web2 page
      uri:
        url: http://node02
        return_content: yes
        status_code: 200
 
2、编写php文件:
[student@master ansibleTest]$ cat index.php

作业:在受控节点上添加一个普通用户xiaohong,配置控制节点的student可以免密登录xiaohong用户,并且xiaohong可以sudo。

1、编写yaml:
[student@master ansibleTest]$ cat user.yaml
---
- name: generate public/private key pair
  hosts: master
  become: no
  remote_user: student
  tasks:
    - openssh_keypair:
        path: /home/student/.ssh/id_rsa

- name: create user
  hosts: node01
  tasks:
    - name: create user xiaohong
      user:
        name: xiaohong
        state: present

    - name: setting passwd
      shell: echo redhat | passwd --stdin xiaohong

    - name: setting sudoers
      lineinfile:
        line: "xiaohong ALL=(ALL) NOPASSWD: ALL"
        path: /etc/sudoers

- name: set authorized key
  hosts: node01
  remote_user: xiaohong
  become: no
  tasks:
    - name: set authorized key
      authorized_key:
        state: present
        user: xiaohong
        key: "{{ lookup( 'file', '/home/student/.ssh/id_rsa.pub' ) }}"

2、修改ansible.cfg文件
[student@master ansibleTest]$ cat ansible.cfg
[defaults]
inventory= ./inventory
remote_user = redhat
ask_pass = yes
[privilege_escalation]
become = True
become_method = sudo
become_user = root
become_ask_pass = False

3、语法检测:
[student@master ansibleTest]$ ansible-playbook user.yaml

4、执行:需要输入密码!!!

[student@master ansibleTest]$ ansible-playbook user.yaml
SSH password:

PLAY [generate public/private key pair] ******************************************************************************************************

TASK [Gathering Facts] ***********************************************************************************************************************
ok: [master]

TASK [openssh_keypair] ***********************************************************************************************************************
changed: [master]

PLAY [create user] ***************************************************************************************************************************

TASK [Gathering Facts] ***********************************************************************************************************************
ok: [node01]

TASK [create user xiaohong] ******************************************************************************************************************
changed: [node01]

TASK [setting passwd] ************************************************************************************************************************
changed: [node01]

TASK [setting sudoers] ***********************************************************************************************************************
changed: [node01]

PLAY [set authorized key] ********************************************************************************************************************

TASK [Gathering Facts] ***********************************************************************************************************************
ok: [node01]

TASK [set authorized key] ********************************************************************************************************************
changed: [node01]

PLAY RECAP ***********************************************************************************************************************************
master                     : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
node01                     : ok=6    changed=4    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

作业二:给受控主机部署yum仓库

仓库1:

name:base

description:baseos

base url:http://mirrors.163.com/centos-vault/8.5.2111/BaseOS/x86_64/os/

需要验证软件包gpg签名

gpgcheck在/etc/pki/rpm-gpg/rpm-gpg-key-*

启用此软件仓库

仓库2:

name:app

description:APPstream

base url:http://mirrors.163.com/centos-vault/8.5.2111/AppStream/x86_64/os/

需要验证软件包gpg签名

gpgcheck在/etc/pki/rpm-gpg/rpm-gpg-key-*

注意:检查自己的linux版本,选择对应版本的仓库

部署成功后在受控节点上安装vsftpd软件包

环境前准备:
查看配置文件:
[student@master ansibleTest]$ cat ansible.cfg
[defaults]
inventory= ./inventory
remote_user = redhat
ask_pass = false
[privilege_escalation]
become = True
become_method = sudo
become_user = root
become_ask_pass = False
[student@master ansibleTest]$ ansible --version
ansible [core 2.13.3]
  config file = /home/student/ansibleTest/ansible.cfg
  configured module search path = ['/home/student/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python3.9/site-packages/ansible
  ansible collection location = /home/student/.ansible/collections:/usr/share/ansible/collections
  executable location = /usr/bin/ansible
  python version = 3.9.13 (main, Nov 16 2022, 15:31:39) [GCC 8.5.0 20210514 (Red Hat 8.5.0-15)]
  jinja version = 3.1.2
  libyaml = True

查看inventory:
[student@master ansibleTest]$ cat inventory
[webs]
node01
node02

[web1]
node01

[web2]
node02

[all]
node01
node02
master

做好免密登录,重传
[student@master ansibleTest]$ ssh-copy-id redhat@node01
[student@master ansibleTest]$ ssh-copy-id redhat@node02


1、编写playbook:
[student@master ansibleTest]$ cat yum.yaml
---
- name: create repository
  hosts: webs
  tasks:
    - name: add repository baseos
      yum_repository:
        name: base
        description: baseos
        baseurl: http://mirrors.163.com/rocky/8.6/BaseOS/x86_64/os/
        gpgcheck: yes
        gpgkey: file:///etc/pki/rpm-gpg/RPM-GPG_KEY-rockyofficial
        enabled: yes
    - name: add repository app
      yum_repository:
        name: app
        description: appstream
        baseurl: http://mirrors.163.com/rocky/8.6/AppStream/x86_64/os/
        gpgcheck: yes
        gpgkey: file:///etc/pki/rpm-gpg/RPM-GPG_KEY-rockyofficial
        enabled: yes

2、语法检测:
[student@master ansibleTest]$ ansible-playbook yum.yaml

3、测试:
[student@master ansibleTest]$ ansible-playbook yum.yaml

PLAY [create repository] *********************************************************************************************************************

TASK [Gathering Facts] ***********************************************************************************************************************
ok: [node02]
ok: [node01]

TASK [add repository baseos] *****************************************************************************************************************
changed: [node02]
changed: [node01]

TASK [add repository app] ********************************************************************************************************************
changed: [node01]
changed: [node02]

PLAY RECAP ***********************************************************************************************************************************
node01                     : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
node02                     : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

作业三:给web主机组写一个playbook,该playbook有俩个play,第一个play可以保证在web主机组上安装httpd和php,确保web主机组的/var/www/html/目录下有一个index.php,内容如下:

该playbook里面的第二个play用于测试该web主机组的web服务能否被成功访问index.php内容

管理事实

案例一:向受管主机的/home/file文件里面写入内容如下:

hostname=当前主机的名字
memory=当前主机的内存大小
BIOS version = 当前主机的bios的版本
distribution = 当前linux主机的发行版本信息
size of disk device is 当前主机的磁盘大小
[student@master ansibleTest]$ cat sys.yaml
---
- name: first play
  hosts: master
  tasks:
    - name: print msg
      debug:
        msg: |
                hostname: {{ ansible_facts.hostname }},
                memory: {{ ansible_facts.memory_mb.real.total }}
                bios version: {{ ansible_facts.bios_version }}
                distribution: {{ansible_facts.distribution }}
                device size: {{ ansible_facts.device.sda.size}}

    - name: copy file
      copy:
        content: |
                hostname: {{ ansible_facts.hostname }},
                memory: {{ ansible_facts.memory_mb.real.total }}
                bios version: {{ ansible_facts.bios_version }}
                distribution: {{ansible_facts.distribution }}
                device size: {{ ansible_facts.device.sda.size}}

        dest: /home/file

案例二:将createuser.fact文件传输到受管主机工作为自定义事实

案例三:使用debug模块,显示当前受控主机的dns服务器的ip地址

[student@master ansibleTest]$ ansible-playbook dns.yaml

PLAY [firt play] *****************************************************************************************************************************

TASK [Gathering Facts] ***********************************************************************************************************************
ok: [node01]

TASK [debug] *********************************************************************************************************************************
ok: [node01] => {
    "ansible_facts.dns.nameservers": [
        "192.168.11.2",
        "172.25.250.1"
    ]
}

PLAY RECAP ***********************************************************************************************************************************
node01                     : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

[student@master ansibleTest]$ cat dns.yaml
---
- name: firt play
  hosts: node01
  tasks:
    - debug:
        var: ansible_facts.dns.nameservers

实施任务控制

案列一:重启服务

1、编写playbook:
[student@master ansibleTest]$ cat restart_service.yaml
---
- name: restart service
  hosts: all
  tasks:
    - name: install httpd mariadb-server
      yum:
        name:
          - httpd
          - mariadb-server

        state: present
      register: result

    - debug:
        var: result

    - name: start service
      service:
        name: "{{ item }}"
        state: restarted
      loop:
        - httpd
        - mariadb
      when: result.rc == 0
2、执行:俩次执行不一样,因为幂等性
[student@master ansibleTest]$ ansible-playbook restart_service.yaml

PLAY [restart service] ***********************************************************************************************************************

TASK [Gathering Facts] ***********************************************************************************************************************
ok: [node02]
ok: [node01]
ok: [master]

TASK [install httpd mariadb-server] **********************************************************************************************************
ok: [node01]
ok: [master]
ok: [node02]

TASK [debug] *********************************************************************************************************************************
ok: [node01] => {
    "result": {
        "changed": false,
        "failed": false,
        "msg": "Nothing to do",
        "rc": 0,
        "results": []
    }
}
ok: [node02] => {
    "result": {
        "changed": false,
        "failed": false,
        "msg": "Nothing to do",
        "rc": 0,
        "results": []
    }
}
ok: [master] => {
    "result": {
        "changed": false,
        "failed": false,
        "msg": "Nothing to do",
        "rc": 0,
        "results": []
    }
}

TASK [start service] *************************************************************************************************************************
changed: [node01] => (item=httpd)
changed: [node02] => (item=httpd)
changed: [master] => (item=httpd)
changed: [node01] => (item=mariadb)
changed: [node02] => (item=mariadb)
changed: [master] => (item=mariadb)

PLAY RECAP ***********************************************************************************************************************************
master                     : ok=4    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
node01                     : ok=4    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
node02                     : ok=4    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

四、个人博客搭建

一、主要内容

wordpress依赖于PHP和MySQL,所以在搭建wordpress前需要先把PHP和MySQL的环境搭建好,本文中使用的web服务为apache。

1、安装LAMP服务器系统(Linux、Apache、MySQL、PHP )

2、安装WordPress

二、具体步骤

安装apache

使用yum安装apache

root@rocky:~# yum install httpd -y

启动apache

root@rocky:~# systemctl is-active httpd
active
root@rocky:~# systemctl start httpd

设置开机自启动

systemctl enable httpd

或者:重启加开机自启动
root@rocky:~# systemctl enable --now httpd

安装PHP

root@rocky:~# yum install php php-devel -y

接下来是一些拓展

yum install php-gd php-ldap php-odbc php-pear php-xml php-xmlrpc -y

还有一个不能通过上述方式直接安装的php-mysql

root@rocky:~# yum search php-mysql
Last metadata expiration check: 0:16:40 ago on Sat 17 Dec 2022 07:54:40 PM CST.
===================================================================== Name Matched: php-mysql ======================================================================
php-mysqlnd.x86_64 : A module for PHP applications that use MySQL databases
root@rocky:~# yum install php-mysqlnd.x86_64
Last metadata expiration check: 0:16:55 ago on Sat 17 Dec 2022 07:54:40 PM CST.
Package php-mysqlnd-7.2.24-1.module+el8.4.0+413+c9202dda.x86_64 is already installed.
Dependencies resolved.
Nothing to do.
Complete!

PHP,启动!

root@rocky:~# systemctl start php-fpm

开机启动

root@rocky:~# systemctl enable php-fpm

安装MySQL

很多教程选择安装mysql的客户端来进行以下操作,官网也是这么玩的,但是我懒,就选择了直接摁命令行

root@rocky:~# yum install mysql mysql-server

启动MySQL

root@rocky:~# systemctl start mysqld.service

修改新建好的账户密码

root@rocky:~# mysqladmin -u root password 123456

登入你的MySQL

root@rocky:~# mysql -u root -p123456

输入你刚刚修改的密码,然后新建一个库

mysql> create database wordpress ;
Query OK, 1 row affected (0.00 sec)

新建一个用户(MySQL8.0需要先创建用户,如果不是8.0+可以跳过这步),如果报错把"IDENTIFIED BY '这里是你的密码'"这块去掉

mysql> CREATE USER 'root'@'%' IDENTIFIED BY '123456';
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE USER 'wordpress'@'%' IDENTIFIED BY '123456';
Query OK, 0 rows affected (0.01 sec)

授予访问权限,刷新

mysql> grant all privileges on wordpress .* to 'root'@'%';
Query OK, 0 rows affected (0.00 sec)

mysql> grant all privileges on wordpress to 'wordpress'@'%';
Query OK, 0 rows affected (0.00 sec)


mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

准备工作完成开始安装wordpress

安装wordpress

下载wordpress的包,并解压。如果你愿意冒着一点打不开的风险重新安装的话可以试试下面的最新版,毕竟在装了两次最新版都死亡白屏但是换成了旧版本之前,我也是个一定要装最新版的强迫症

root@rocky:~#  wget http://wordpress.org/latest.tar.gz

 tar -xzf latest.tar.gz

附上我用起来没毛病的包

root@rocky:~# wget https://cn.wordpress.org/wordpress-5.0.3-zh_CN.zip
root@rocky:~#unzip wordpress-5.0.3-zh_CN.zip

将wordpress文件夹拷贝至apache服务器根文件目录下(正常情况下为:/var/www/html )

root@rocky:~#cp -r wordpress /var/www/html/

跳转然后创建并修改wordpress的配置文件

root@rocky:~# cd /var/www/html/wordpress/
root@rocky:/var/www/html/wordpress# cp wp-config-sample.php wp-config.php
root@rocky:/var/www/html/wordpress# vim wp-config.php

修改数据库名字,用户名,密码

测试:

关闭防火墙selinux

root@rocky:/var/www/html/wordpress# systemctl is-active firewalld.service
active
root@rocky:/var/www/html/wordpress# systemctl stop firewalld.service
root@rocky:/var/www/html/wordpress# setenforce 0
root@rocky:/var/www/html/wordpress# getenforce
Permissive

访问

http://192.168.11.142/wordpress/wp-admin/install.php

进行wordpress初始化,一顿操作猛如虎,但是结果进不了数据库

简化步骤直接操作:

1、安装httpd:
[root@rocky ~]#yum update
[root@rocky ~]# yum install httpd -y

2、启动服务;
[root@rocky ~]# systemctl start httpd

3、关闭防火墙,selinux
[root@rocky ~]# systemctl stop firewalld.service
[root@rocky ~]# setenforce 0

4、安装PHP:
[root@rocky ~]# yum install php -y

5、安装组件:
[root@rocky ~]#yum install php-* -y

6、写phpinfo
[root@rocky html]# cat info.php


7、重启服务:
[root@rocky html]# systemctl restart httpd.service
[root@rocky html]# systemctl restart php-fpm.service

8、安装mysql:
[root@rocky html]# yum install mysql-server -y

9、重启并设置为开机自启动:
[root@rocky html]# systemctl enable --now mysqld

10、设置数据库密码:
mysqladmin -uroot -p123456

11、创建数据库:
mysql> create database wordpress;
Query OK, 1 row affected (0.00 sec)

12、下载WordPress:
root@rocky:~# wget https://cn.wordpress.org/wordpress-5.0.3-zh_CN.zip
root@rocky:~#unzip wordpress-5.0.3-zh_CN.zip

13、拷贝一份并命名为 wp-config.php
[root@rocky wordpress]# cp wp-config-sample.php wp-config.php

14、修改三个地方:
第一个是数据库名称,安装mysql时最后面创建的数据库,这里是wordpress
第二个是数据库的名称,这里没创建用户,用默认的root即可
第三个是数据库的密码,即安装第3步数据库时修改的密码,没修改的话默认填写’’,空着,不要删除两个单引号,(实际上我没试过没密码的,习惯性给数据库都添加了密码,这里你可以试试看没密码的,如果不行就按照安装数据库部分第三步修改一下密码,然后设置进来就行)
修改完成后按esc,然后输入:wq退出保存文件即可

15、测试:http://192.168.11.142/wordpress/wp-admin/install.php
数据库密码为空

蒸汽小火车:

下载链接:http://rpmfind.net/linux/rpm2html/search.php?query=sl&submit=Search+...&system=&arch=+x86_64

1、下载:
[root@rocky ~]# wget http://rpmfind.net/linux/epel/8/Everything/x86_64/Packages/s/sl-5.02-1.el8.x86_64.r   pm
2、安装:
[root@rocky ~]# rpm -i sl-5.02-1.el8.x86_64.rpm
warning: sl-5.02-1.el8.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID 2f86d6a1: NOKEY
3、运行:
[root@rocky ~]# sl

五、RHCE---服务篇

环境准备

1、将网卡设置为开机自启动:

[root@master ~]# nmcli connection modify ens160 connection.autoconnect yes
[root@master ~]# nmcli connection up ens160
Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/3)

2、学习环境:8.x

[root@master ~]# cat /etc/os-release
NAME="Rocky Linux"
VERSION="8.6 (Green Obsidian)"
ID="rocky"
ID_LIKE="rhel centos fedora"
VERSION_ID="8.6"
PLATFORM_ID="platform:el8"
PRETTY_NAME="Rocky Linux 8.6 (Green Obsidian)"
ANSI_COLOR="0;32"
CPE_NAME="cpe:/o:rocky:rocky:8:GA"
HOME_URL="https://rockylinux.org/"
BUG_REPORT_URL="https://bugs.rockylinux.org/"
ROCKY_SUPPORT_PRODUCT="Rocky Linux"
ROCKY_SUPPORT_PRODUCT_VERSION="8"
REDHAT_SUPPORT_PRODUCT="Rocky Linux"
REDHAT_SUPPORT_PRODUCT_VERSION="8"

3、系统时间--方便后期查看日志文件更新时间:

[root@master ~]# timedatectl set-timezone   Asia/Shanghai

4、配置好yum/dnf源 rpm

curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-vault-8.5.2111.repo

5、安装常用的软件包:

yum install -y bash-completion tree lrzsz  vim  net-tools.x86_64  unzip net-tools  lsof  wget

6、rpm包软件管理:

rpm包进行管理
rpm   -ivh 安装软件
      -evh 卸载软件
       -qa     rpm -qa | grep httpd 查看信息
       -ql      
       -qf

7、yum/dnf 7的版本用yum更多,在8版本之后用的dnf之多,可以在后期自己尝试用dnf

#vim   /etc/fstab
/dev/sr0   /mnt  iso9660    defaults     0 0 
#mount -a 查看挂载
#vim /etc/yum.repos.d/base.repo 
[BaseOS]
name=RHEL8.5-BaseOS
baseurl=file:///mnt/BaseOS
gpgcheck=0
[AppStream]
name=RHEL8.5-AppStream
baseurl=file:///mnt/AppStream
gpgcheck=0

案例

案例一: 搭建web服务器,提供redhat测试界面

linux主机作为服务器

1、部署web服务程序 apache http server(httpd)

[root@localhost ~]# rpm -qa | grep httpd
httpd-filesystem-2.4.37-41.module+el8.5.0+11772+c8e0c271.noarch
httpd-tools-2.4.37-41.module+el8.5.0+11772+c8e0c271.x86_64
httpd-2.4.37-41.module+el8.5.0+11772+c8e0c271.x86_64
redhat-logos-httpd-84.5-1.el8.noarch
[root@localhost ~]# yum install httpd -y

2、当前主机启动该服务程序

#systemctl    start|stop|restart|status|load|reload|enable|disable|is-active|is-enabled   httpd
[root@localhost ~]# systemctl start httpd
[root@localhost ~]# systemctl is-active httpd

3、提供客户端主机可以访问的资源文件

默认的资源文件

问什么默认访问的是欢迎界面:通过主配置/var/www/html加载网站资源文件(index.html),当文件不存在,匹配子配置文件/etc/httpd/conf.d/welcome.conf

Alias /.noindex.html /usr/share/httpd/noindex/index.html

4、关闭防火墙,selinux

[root@localhost ~]# systemctl stop firewalld      ---建议临时关闭
 [root@localhost ~]# systemctl disable firewalld

关闭selinux:

临时生效
[root@localhost ~]# setenforce 0      ---主机运行状态下临时关闭
[root@localhost ~]# getenforce            --查看selinux状态
Permissive 
永久修改linux状态
[root@localhost ~]# vim /etc/selinux/config 
# This file controls the state of SELinux on the system.
# SELINUX= can take one of these three values:
#     enforcing - SELinux security policy is enforced.     强制状态(开启)
#     permissive - SELinux prints warnings instead of enforcing.   警告(关闭)
#     disabled - No SELinux policy is loaded.                    禁用(不加载selinux)
SELINUX=permissive

5、rpm -ql httpd | more

/etc/httpd/conf 主配置目录(默认提供的参数信息)

/etc/httpd/conf/httpd.conf

/etc/httpd/conf.d 子配置目录(辅助)(自定义的配置文件)

/etc/httpd/conf.d/*.conf

一个完整配置文件先加载主配置文件,在加载子配置文件

/etc/httpd/conf.modules.d 模块配置文件的路径

全局生效
ServerRoot   /etc/httpd      配置文件中加载文件的主路径
Listen  80                   服务程序默认监听端口
User apache                  服务程序运行后的所属用户和所属组
Group apache
Serveradmin  root@localhost
#ServerName  www.example.com:80   定义服务主机访问名称
ServerName 0.0.0.0:80
DocumentRoot "/var/www/html"   定义网站默认的主路径
IncludeOptional conf.d/*.conf   开始加载所有子配置文件

局部生效
            目录起始标签  /
    AllowOverride none
    Require all denied         请求所有拒绝

     目录起始标签  /var/www  
    AllowOverride None
    # Allow open access:
    Require all granted     请求所有允许  

      模块标记  对目录模块定义
    DirectoryIndex index.html     网站主目录索引文件文件名为index.html

案例二:搭建网站创建自定义网页文件

linux主机作为服务器

1、部署web服务程序 apache http server(httpd)

2、当前主机启动该服务程序

3、提供客户端主机可以访问的资源文件

#cd /var/www/html
  #echo helloworld > index.html
  通过主配置/var/www/html加载网站资源文件(index.html)当文件存在,直接加载该文件内容进行相应。

4、关闭防火墙,selinux

window/linux 客户端主机

浏览器:url 网址 http://ip/1/index.html /var/www/html/1/index.html

权限控制

web服务程序资源文件的权限控制可以在配置文件和文件层级。

     目录起始标签  /www  
    AllowOverride None
    #Allow open access:
    Require all granted     请求所有允许  

[root@localhost ~]# chmod o-r /www/index.html
[root@localhost ~]# ll /www/index.html
-rw-r-----. 1 root root 13 Mar 20 09:58 /www/index.html
[root@localhost ~]# chmod o+r /www/index.html

https://httpd.apache.org/docs/2.4/howto/auth.html
require user tom
Require ip address
Require not  ip address
Require host domain_name

        AllowOverride none
        
                Require all granted
                Require not  ip 192.168.153.128
        


多网站访问
http://ip|域名|:80
https://

案例三:多ip匹配多网站

1、当前主机配置多个ip

[root@localhost ~]# nmcli connection modify ens160 ipv4.method manual ipv4.addresses  192.168.153.128/24 ipv4.gateway 192.168.153.2 ipv4.dns 114.114.114.114 +ipv4.a
ddresses 192.168.153.129 +ipv4.addresses  192.168.153.130
[root@localhost ~]# nmcli connection up ens160 
Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/4)
[root@localhost ~]# ip a

2、通过配置基于多个虚拟主机标签配置多个网站站点

虚拟主机示例文件
# rpm -ql httpd | grep vhosts.conf
#  vim /usr/share/doc/httpd/httpd-vhosts.conf
1.自定义子配置文件,配置多主机网站信息
vim /etc/httpd/conf.d/vhosts.conf 

    DocumentRoot "/openlab/128"
    ServerName 192.168.153.128
    ErrorLog "/var/log/httpd/dummy-128.example.com-error_log"
    CustomLog "/var/log/httpd/dummy-128.example.com-access_log" common



    DocumentRoot "/openlab/129"
    ServerName 192.168.153.129



    DocumentRoot "/openlab/130"
    ServerName 192.168.153.130

#资源路径的访问权限

        AllowOverride none
        Require all granted

2.根据配置创建对应资源文件
#mkdir /openlab/{128,129,130} -pv
#echo this is 128 > /openlab/128/index.html
#echo this is 129 > /openlab/129/index.html
#echo this is 130 > /openlab/130/index.html
#systemctl restart httpd

案例四: 基于多端口访问多网站

##130-80

    DocumentRoot "/openlab/130"
    ServerName 192.168.153.130

##130--10000    
Listen 10000   #监听自定义端口

    DocumentRoot "/openlab/10000"
    ServerName 192.168.153.130


        AllowOverride none
        Require all granted
 

[root@localhost ~]# mkdir /openlab/10000
[root@localhost ~]# echo this is 10000 > /openlab/10000/index.html
[root@localhost ~]# systemctl restart httpd     

测试:

案例五:基于域名访问多网站


    DocumentRoot "/openlab/haha"
    ServerName www.haha.com
    ErrorLog "/var/log/httpd/dummy-128.example.com-error_log"
    CustomLog "/var/log/httpd/dummy-128.example.com-access_log" common


    DocumentRoot "/openlab/xixi"
    ServerName www.xixi.com
    ErrorLog "/var/log/httpd/dummy-128.example.com-error_log"
    CustomLog "/var/log/httpd/dummy-128.example.com-access_log" common


        AllowOverride none
        Require all granted
 
[root@localhost ~]# mkdir /openlab/{haha,xixi}
[root@localhost ~]# echo this is xixi > /openlab/xixi/index.html
[root@localhost ~]# echo this is haha > /openlab/haha/index.html
[root@localhost ~]# systemctl restart httpd

客户端测试

1.通过域名访问需要将域名解析为ip
	通过浏览器缓存匹配
	客户端主机的hosts文件匹配  
  		window:C:\Windows\System32\drivers\etc
							192.168.153.128         www.haha.com
							192.168.153.128         www.xixi.com                         
         linux :  /etc/hosts
	路由缓存记录匹配
	本地dns服务

排错方式

(1) 启动不成功(配置文件写的有问题)systemctl restart httpd  
[root@localhost ~]#systemctl status httpd
[root@localhost ~]# journalctl -xe
[root@localhost ~]# httpd -t

(2)访问的内容不是我们定义的内容
逻辑问题:分析主机配置标签是否能匹配或是否冲突
		资源文件是否创建
        匹配对应文件是否有权限
		防火墙,selinux

案例六:虚拟目录

alias 虚拟目录名称 真实目录路径

​ 为了便于对网站资源进行灵活管理,还可以把这些文件存放在本地计算机的其它文件夹中或者其它计算机的共享文件夹中,然后再把这个文件夹映射到网站主目录中的一个目录上,这个文件夹被称为“虚拟目录”。

每个虚拟目录都有一个别名,这样用户就可以通过这个虚拟目录的别名来访问与之对应的真实文件夹中的资源了。虚拟目录的好处是在不需要改变别名的情况下,可以随时改变其对应的文件夹。


    DocumentRoot "/openlab/128"
    #  /网站根目录=/openlab/128
    Alias /file   /openlab/128/1/f/file/newfile/
    ServerName 192.168.153.128
        #  /openlab/128/3w
    Alias /3w     /www


        AllowOverride none
        Require all granted


    AllowOverride None
    # Allow open access:
    Require all granted



[root@localhost ~]# mkdir -pv  /openlab/128/1/f/file/newfile/
mkdir: created directory '/openlab/128/1'
mkdir: created directory '/openlab/128/1/f'
mkdir: created directory '/openlab/128/1/f/file'
mkdir: created directory '/openlab/128/1/f/file/newfile/'
[root@localhost ~]# echo this is zijiemian > /openlab/128/1/f/file/newfile/index.html

[root@localhost ~]# mkdir /www
mkdir: cannot create directory ‘/www’: File exists
[root@localhost ~]# cd /www
[root@localhost www]# ll
total 4
-rw-r--r--. 1 root root 13 Mar 20 09:58 index.html
[root@localhost www]# echo this is 128 test page > index.html

案例七:用户访问控制+虚拟目录


    DocumentRoot "/openlab/128"
       # /网站根目录=/openlab/128
    Alias /file   /openlab/128/1/f/file/newfile/
    ServerName 192.168.153.128
    Alias /3w     /www


        AllowOverride none
        Require all granted


        AuthType Basic
        AuthName "Please login:"
        AuthuserFile /etc/httpd/userfile
        Require user tom zhangsan


[root@localhost www]# htpasswd -c /etc/httpd/userfile tom    
New password: 
Re-type new password: 
Adding password for user tom
[root@localhost www]# htpasswd /etc/httpd/userfile zhangsan
New password: 
Re-type new password: 
Adding password for user zhangsan

curl  http://192.168.153.128/3w/   -u tom

案例八:搭建加密网站

1.加载mod_ssl认证模块

[root@localhost www]# yum install mod_ssl -y

2.生成自签名证书

(第二种) [root@localhost ~]#cd /etc/pki/tls/certs
[root@localhost certs]# openssl req -newkey rsa:4096 -nodes -sha256 -keyout ../private/openlab.key  -x509 -days 365 -out openlab.crt

----------------------------------------------x509 key csr crt---------------------------
[root@www certs]# openssl genrsa -aes128 2048 > openlab.key
 (第三种) #openssl req -utf8 -new -key openlab.key -x509 -days 365 -out openlab.crt 
-------------------------------------------------------------------------------------

3.虚拟主机标签中添加加密验证信息


    DocumentRoot "/ssl"
    ServerName 192.168.153.128
    SSLEngine on
	SSLCertificateFile /etc/pki/tls/certs/openlab.crt
	SSLCertificateKeyFile /etc/pki/tls/private/openlab.key


​        AllowOverride none
​        Require all granted

4.重启服务测试

**案例九:扩展配置 **

1.通过http/https 实现文件共享
目录标签中 options +indexes
indexes 默认加载directoryindex 目录标签后,当目录directoryindex找不到对应网页文件(删除主路径下的index.html,以及欢迎界面)会加载mod_autoindex 会将网站主路径下的文件格式为目录列表提供客户端主机访问。

2.配置用户主界面---静态

1.更改用户主界面配置
vim /etc/httpd/conf.d/userdir.conf

UserDir public_html

AuthType Basic
AuthName "please login"
AuthuserFile /etc/httpd/userfile
Require user tom
注意: 访问用户主界面通过什么协议访问
指定网站访问方式(ip)通过哪种协议可以匹配
2.创建资源信息
#useradd tom
#mkdir /home/tom/public_html
#echo this is tom > /home/tom/public_html/index.html
#chmod o+rx /home/tom
#htpasswd -c /etc/httpd/userfile tom
3.重启
4.firewalld setenfore

搭建动态网站
LAMP
1.linux平台部署web服务
2.配置web服务
(1).安装web服务
(2).根据配置定义加载网页资源文件的路径

[root@localhost uc_server]# cat /etc/httpd/conf.d/vhosts.conf

AllowOverride none
Require all granted

DocumentRoot /www
ServerName 192.168.153.128

(3).根据配置创建资源文件

#mkdir /www
#cd /www  
#unzip Discuz_X3.4_SC_UTF8_20191201.zip

(4).重启服务

3.部署mariadb

[root@localhost install]# yum install mairadb-server -y
[root@localhost www]# systemctl start mariadb
[root@localhost www]# mysql_secure_installation 初始化数据库
enter
y
redhat
redhat
一直y
[root@localhost www]# mysql -uroot -predhat // -u用户名 -p密码
MariaDB [(none)]> create database luntan;
MariaDB [(none)]>quit
[root@localhost www]# systemctl restart mariadb

4.安装PHP应用程序

yum install php* -y
[root@localhost upload]# pwd
/www/upload
[root@localhost upload]# chmod o+w data config uc_* -R

NFS

1.NFS 网络文件系统(文件共享协议)
通过nfs服务器可以共享文件,客户端主机通过挂载方式访问共享文件。
2.挂载的特点:(文件访问)
通过客户端主机挂载点目录连接服务端共享的nfs文件系统,类似与所有文件都在本地,但实际上所有文
件都在服务端主机中,通过服务端主机可以控制客户某些主机可以访问该文件。
3.挂载方式:
1)临时挂载
2)开机自动挂载
3)自动挂载
一个挂载点可以同时连接多个文件系统(不推荐)注意:RHEL7.X 多个nfs文件系统不支持同时挂载到
一个挂载点目录,但RHEL8.x 多个nfs文件系统不支持同时挂载到一个挂载点目录,但通过挂载点访问的是最后一次连接的文件系统。
同一个文件系统可以挂载到多个挂载点目录。
4.nfs 文件共享的原理

5.nfs服务搭建
服务端
1)安装软件包rpcbind nfs-server
2)自定设置,编辑配置文件

vim /etc/exports
共享目录 允许访问的主机(参数,...)

ro rw
root_squash
no_root_squash
all_squash
anonuid=
anongid=
no_all_squash
sync
async
atime
noatime
  1. 创建资源文件
    创建共享主目录,以及主目录对于用户访问权限设置
    4)systemctl start nfs-server
    exportfs -ra
    5)防火墙 ,selinux
    客户端:linux
    1).showmount -e 服务端ip 查询服务主机共享文件系统
    2).挂载文件系统
    6.服务是否启动
    systemctl is-active httpd
systemctl status httpd
ps -aux | grep httpd
ss -tunlp | grep 2048
netstat -tunlp | grep httpd
lsof -i:80
rpcinfo -p

7.nfs优缺点

**案例:架设一台NFS服务器,并按照以下要求配置 **

1、开放/nfs/shared目录,供所有用户查询资料
2、开放/nfs/upload目录,为192.168.100.0/24网段主机可以上传目录,
并将所有用户及所属的组映射为nfs-upload,其UID和GID均为210

3、将/home/tom目录仅共享给192.168.100.136这台主机,并只有用户tom可以完全访问该目录
autofs
能够动态管理文件系统,在系统需要该文件系统资源时,将文件系统动态挂载可以动态取消挂载。

1.安装自动挂载服务程序
yum install autofs -y
2.自定义触发条件,满足该条件后,将文件系统自动挂载
vim /etc/auto.master 主参数文件中定义挂载条件
#挂载点主目录 子参数文件(连接autofs文件系统)
/nfs /etc/auto.nfs
vim /etc/auto.nfs
#触发条件(挂载点目录) 文件系统名称
test 192.168.153.128:/test
3.加载参数
systemctl restart autofs
查看挂载点主目录是否自动创建
手动: cd /nfs cd test
自动触发:
mount /dev/sr0 /pub/sr0

**搭建web服务通过域名访问网站资源文件,网站资源文件通过nfs服务器共享个web服务端主机,提供用
户解析和查询 **

1.web服务器
yum install httpd
[root@localhost ~]# cat /etc/httpd/conf.d/vhosts.conf

AllowOverride none
Require all granted

DocumentRoot /www/129
ServerName 192.168.153.129

2、安装自动挂载服务程序
yum install autofs -y
vim /etc/auto.master
/www /etc/auto.web
vim /etc/auto.web
129 192.168.153.128:/test
systemctl restart autofs
yum install php*
yum install mariadb-server -y
systemctl restart mariadb
mysql_secure_installation
mysql -uroot -predhat
create database wordpress;
exit
systemctl start mairadb
systemctl restart httpd

3.nfs服务器 wordpress
#rpm -qa | grep nfs
#rpm -qa | grep rpcbind
#vim /etc/exports
#mkdir /test
#cd /test
通过xftp将wordpress包传到共享主目录/test#unzip wordpress-5.9.2.zip
#unzip wordpress-5.9.2.zip
[root@localhost test]# ll
total 19800
drwxr-xr-x. 5 root root 4096 Mar 10 19:39 wordpress
-rw-r--r--. 1 root root 20270503 Mar 27 04:30 wordpress-5.9.2.zip
[root@localhost test]# systemctl restart nfs-server
[root@localhost test]# systemctl stop firewalld
[root@localhost test]# setenforce 0
[root@localhost wordpress]# cp wp-config-sample.php wp-config.php

linux邮件客户端的配置

第三方邮件客户端程序验证能够通过linux主机将信件发送到外网邮件服务器。

yum install mailx -y

vim  /etc/mail.rc

set [email protected]      # 邮箱账号
set smtp=smtp.163.com                         #邮件服务器的主机名
set [email protected]    # 邮箱账号
set smtp-auth-password=QUREDFYKLNBRAIAA   #授权码
set smtp-auth=login             

(1)#echo "邮件内容" | mail -s '邮件主题'     收件用户的邮箱账号

(2)#echo  邮件内容 > /a.txt

mail -s  '主题'  -a  /a.txt  收件用户的邮箱账号   <  /a.txt

nmcli

### 配置网卡冗余(主备)

#nmcli connection add type team ifname team0 con-name team0 config '{"runner":       {"name": "activebackup"}}

#nmcli connection add type  team-slave ifname ens224 con-name team0-port1 master team0

#nmcli connection add type team-slave  ifname ens256 con-name team0-port2 master team0

#nmcli connection show 

#nmcli con   up team0-port1

#nmcli con   up team0-port2

#teadctl team0   stat

#nmcli connection modify team0 ipv4.addresses 192.168.153.111/24   +ipv4.addresses 192.168.153.111/24ipv4.gateway 192.168.153.2  ipv4.dns 114.114.114.114 ipv4.method  manual  connection.autoconnect yes

## 桥接网卡

#nmcli connection add type bridge-slave   ifname ens160 con-name br1-port1 master br1
 #nmcli connection show 
 #nmcli connection up br1-port1

环境准备:

1、下载环境:

2、解压:100G左右

3、打开:

  • 方法一:双击RH294.vmx
  • 方法二:vmware打开RH294.vmx

4、远程连接:

  • 给win的虚拟网卡:VMware Network Adapter VMnet1增加一个ip:
    • ip:172.25.254.1/255.255.255.0,不需要网关
  • 远程连接:
    • IP:172.25.254.250 kiosk/redhat
    • root用户远程登录密码:Asimov
    • student:student

5、设置课程:考试和工作都不用

[kiosk@foundation0 ~]$ rht-setcourse rh294
/content/rhel8.0/x86_64/vms /home/kiosk
/home/kiosk
Course set to rh294

6、启动课程环境:

[kiosk@foundation0 ~]$ rht-vmctl status all
bastion DEFINED
workstation DEFINED
servera DEFINED
serverb DEFINED
serverc DEFINED
serverd DEFINED

[kiosk@foundation0 ~]$ rht-vmctl start classroom 
[kiosk@foundation0 ~]$ rht-vmctl start all 
Starting bastion.
Starting workstation.
Starting servera.
Starting serverb.
Starting serverc.
Starting serverd.

重置虚拟机:
[kiosk@foundation0 ~]$ rht-vmctl reset  all 
Are you sure you want to reset bastion workstation servera serverb serverc serverd? (y/n) y

查看状态:
[kiosk@foundation0 ~]$ rht-vmctl status all
bastion RUNNING
workstation RUNNING
servera RUNNING
serverb RUNNING
serverc RUNNING
serverd RUNNING
[kiosk@foundation0 ~]$ rht-vmctl status classroom 
classroom RUNNING

学会查看帮助:
[kiosk@foundation0 ~]$ rht-vmctl --help

This utility manages the Red Hat Training supplied VMs on the local
hypervisor.

Usage: rht-vmctl [-y|--yes] VMCMD VMNAME [DATETIME]
       rht-vmctl [-i|--inquire] VMCMD VMNAME [DATETIME]
       rht-vmctl -h|--help

  where VMCMD is one of:
    view       - launches console viewer of VMNAME
    start      - obtain and start up VMNAME
    stop       - stop a running VMNAME
    restart    - if running, stop then start VMNAME
    poweroff   - if running, force stop VMNAME
    reset      - poweroff, return to saved or original state, start VMNAME
    save       - stop, save image, start VMNAME (to DATETIME)
    restore    - poweroff, restore to save (to DATETIME), start VMNAME
    listsaves  - list the saves of VMNAME
    status     - display libvirt status of VMNAME
    get        - if not here, obtain VMNAME from server
    remove     - remove VMNAME from system
    fullreset  - poweroff, reobtain from server, start VMNAME (bad save/image)

  -i|--inquire - confirm each VMNAME first
  -y|--yes     - confirm nothing, just do it

  VMNAME of "all" processes all VMs available in the course

注意:重新开机之后,只需要执行rht-vmctl start all

练习环境:
[kiosk@foundation0 ~]$ ssh student@workstation
Warning: Permanently added 'workstation,172.25.250.9' (ECDSA) to the list of known hosts.
Activate the web console with: systemctl enable --now cockpit.socket

[student@workstation ~]$

ansible后面的命令:自己去了解一下

student@master:~$ ansible-
ansible-community   ansible-connection  ansible-doc         ansible-inventory   ansible-pull        
ansible-config      ansible-console     ansible-galaxy      ansible-playbook    ansible-vault  

student@master:~/ansibleDemo$ ansible-inventory --list
{
    "_meta": {
        "hostvars": {}
    },
    "all": {
        "children": [
            "ungrouped"
        ]
    }
}

双网卡绑定team

堡垒机或跳板机

双网卡绑定:

  • 轮询:轮流响应用户请求。缺点:如果某一块网卡出现故障,可能会导致访问异常。
  • 主备:正常情况下,只有一个网卡工作。缺点:浪费了一块网卡资源。优点:高可用。
  • 负载均衡:流量分担。

扩展内容:

双网卡绑定:team

前提:需要俩块相同的类型的网卡

查看:

[root@master ~]# nmcli connection show
NAME   UUID                                  TYPE      DEVICE
ens33  4f0220d5-7ac9-456a-ba4a-852f14911ac7  ethernet  ens33

修改连接名:

[root@master ~]# nmcli connection modify ens33 con-name ens33

查看team配置:

[root@master yum.repos.d]# cd /usr/share/doc/teamd-1.29/example_configs/

配置:

1、创建team0设备和team0会话

[root@master example_configs]# nmcli connection add type team con-name team0 ifname team0 config '{"runner":{"name":"activebackup"}}'

2、配置team0地址信息

[root@master example_configs]# nmcli connection modify team0 ipv4.method manual ipv4.addresses 192.168.11.100/24 ipv4.gatwag 192.168.11.2 ipv4.dns 114.114.114.114 autoconnect yes

3、添加设备到team0

[root@master example_configs]# nmcli connection add type team-slave con-name team0-1 ifname ens33 master team0
[root@master example_configs]# nmcli connection add type team-slave con-name team0-2 ifname ens34 master team0

4、激活设备

在虚拟机中去做,xshell会中断

[root@master example_configs]# nmcli connection up team0-1
[root@master example_configs]# nmcli connection up team0-2
[root@master example_configs]# nmcli connection up team0

5、查看

[root@master example_configs]# teamdctl team0 state

NFS服务器

案例一:共享/data目录给192.168.11.0/24整个网段可读可写

1、安装软件

[root@master ~]# yum install nfs-utils.x86_64  rpcbind.x86_64  -y

2、编写配置文件

[root@master ~]# cat /etc/exports
/data 192.168.11.0/24(rw,sync,no_root_squash)

3、创建目录

[root@master ~]# mkdir /data

4、测试

[root@master ~]# showmount -e
Export list for master.itcast.com:
/data 192.168.11.0/24

挂载:

  • 手动挂载:mount
  • 开机自动挂载:/etc/fstab
  • 按需挂载:autofs,使用时挂载,灵活

案例:配置autofs挂载光盘到/mnt/dvd

1、安装软件

[root@master ~]# yum install autofs.x86_64 -y

2、写配置文件

[root@master ~]# vim /etc/auto.master
上层目录 配置文件
/mnt /etc/auto.cdrom

[root@master ~]# cat /etc/auto.cdrom

dvd     -fstype=iso9660,ro,nosuid,nodev :/dev/cdrom

3、重启服务

[root@master ~]# systemctl enable --now autofs.service

4、测试

[root@master ~]# ls /mnt/

[root@master ~]# ll /mnt/dvd
total 1670
-rw-rw-r--. 1 root root      14 Jul 26  2022 CentOS_BuildTag
drwxr-xr-x. 3 root root    2048 Jul 26  2022 EFI
-rw-rw-r--. 1 root root     227 Aug 30  2017 EULA
-rw-rw-r--. 1 root root   18009 Dec 10  2015 GPL
drwxr-xr-x. 3 root root    2048 Jul 26  2022 images
drwxr-xr-x. 2 root root    2048 Jul 26  2022 isolinux
drwxr-xr-x. 2 root root    2048 Jul 26  2022 LiveOS
drwxr-xr-x. 2 root root 1671168 Jul 26  2022 Packages
drwxr-xr-x. 2 root root    4096 Jul 26  2022 repodata
-rw-rw-r--. 1 root root    1690 Dec 10  2015 RPM-GPG-KEY-CentOS-7
-rw-rw-r--. 1 root root    1690 Dec 10  2015 RPM-GPG-KEY-CentOS-Testing-7
-r--r--r--. 1 root root    2883 Jul 27  2022 TRANS.TBL
[root@master ~]# df -h
Filesystem               Size  Used Avail Use% Mounted on
devtmpfs                 475M     0  475M   0% /dev
tmpfs                    487M     0  487M   0% /dev/shm
tmpfs                    487M  7.8M  479M   2% /run
tmpfs                    487M     0  487M   0% /sys/fs/cgroup
/dev/mapper/centos-root   17G  1.9G   16G  11% /
/dev/sda1               1014M  139M  876M  14% /boot
tmpfs                     98M     0   98M   0% /run/user/0
/dev/sr0                 9.6G  9.6G     0 100% /mnt/dvd

DNS服务器

unbound

1、安装unbound

[root@master ~]# yum install unbound -y

2、编辑配置文件,对全局参数进行配置

[root@master ~]# vim /etc/unbound/unbound.conf
        access-control: 192.168.11.0/24 allow
        username: ""
        domain-insecure: "openlab.edu"
 		include: /etc/unbound/local.d/*.conf

3、进入配置解析域

[root@master ~]# cd /etc/unbound/local.d/
[root@master local.d]# ls
block-example.com.conf
[root@master local.d]# more  block-example.com.conf
# entries in this file override toe global DNS
#
# Example blocking email going out to example.com
#
#       local-data: "example.com. 3600 IN MX 5 127.0.0.1"
#       local-data: "example.com. 3600 IN A 127.0.0.1"

# This can also be done dynamically using: unbound-control local-data [...]

# For more complicated redirection, use conf.d/ with stub-add: or forward-add:

4、配置正向解析记录和反向解析目录

[root@master local.d]# cat domain.conf
local-zone:"openlab.edu." static
local-data:"openlab.edu. 86400 IN SOA dns1.openlab.edu. root.openlab.edu 2023031501 1D 1H 1W 1H"
local-data:"dns1.openlab.edu. IN  A 192.168.11.121"
local-data:"www.openlab.edu. IN A  192.168.11.111"
local-data:"web.openlab.edu.IN CNAME www.openlab.edu."
local-data:"mail.openlab.edu. IN A 192.168.11.222"
local-data:"openlab.edu. IN MX 5 mail.openlab.edu."

# 反向解析
local-data-ptr:"192.168.11.121 dns1.openlab.edu"
local-data-ptr:"192.168.11.111 www.openlab.edu"
local-data-ptr:"192.168.11.111 web.openlab.edu"
local-data-ptr:"192.168.11.222 mail.openlab.edu"

5、配置转发

[root@master local.d]# vim /etc/unbound/unbound.conf
forward-zone:
        name: "."
        forward-addr:223.5.5.5

6、语法检测

[root@master local.d]# unbound-checkconf

7、重启服务

[root@master ~]# systemctl restart unbound

8、测试

客户端:
[root@master local.d]# yum install bind-utils.x86_64 -y

[root@master ~]# cat /etc/resolv.conf
# Generated by NetworkManager
search localdomain itcast.com
nameserver 192.168.11.121

[root@master ~]#nslookup
> 192.168.11.121

bind---常用

1、安装软件

[root@master ~]# yum install bind -y

2、关闭防火墙或者放行DNS服务

[root@master ~]# firewall-cmd --permanent --add-service=dns
success
[root@master ~]# firewall-cmd --reload
success

3、修改配置文件

[root@master ~]# vim /etc/named.conf
options {
        listen-on port 53 { 192.168.11.148; }; #修改这一行IP,注意分号
        //listen-on-v6 port 53 { ::1; }; # IPV6的,可以注释掉
        directory       "/var/named";
        dump-file       "/var/named/data/cache_dump.db";
        statistics-file "/var/named/data/named_stats.txt";
        memstatistics-file "/var/named/data/named_mem_stats.txt";
        recursing-file  "/var/named/data/named.recursing";
        secroots-file   "/var/named/data/named.secroots";
        allow-query     { 192.168.11.0/24; }; # 修改为本网段,或者用any

4、区域文件

[root@master ~]# vim /etc/named.rfc1912.zones # 路径在配置文件中有
正向解析:
zone "openlab.edu" IN {
        type master;
        file "openlab.edu.zone";
};

[root@master ~]# cd /var/named/
[root@master named]# ll
total 16
drwxrwx---. 2 named named    6 Jan 26 00:48 data
drwxrwx---. 2 named named    6 Jan 26 00:48 dynamic
-rw-r-----. 1 root  named 2253 Apr  5  2018 named.ca
-rw-r-----. 1 root  named  152 Dec 15  2009 named.empty
-rw-r-----. 1 root  named  152 Jun 21  2007 named.localhost
-rw-r-----. 1 root  named  168 Dec 15  2009 named.loopback
drwxrwx---. 2 named named    6 Jan 26 00:48 slaves
[root@master named]# cp -a named.localhost  openlab.edu.zone #注意带权限修改
[root@master named]# vim openlab.edu.zone
[root@master named]# cat openlab.edu.zone
$TTL 1D
@       IN SOA  dns1.openlab.edu. admin.openlab.edu. (
                                        2023031601      ; serial
                                        1D      ; refresh
                                        1H      ; retry
                                        1W      ; expire
                                        3H )    ; minimum
        NS      dns1.openlab.edu.
        MX 5    mail.openlab.edu.
dns1    A       192.168.11.148
mail    A       192.168.11.222
www     A       192.168.11.111
web     CNAME   www

5、语法检测

# 7版本的语法:
[root@master named]# named-checkzone "openlab.edu" /var/named/openlab.edu.zone
zone openlab.edu/IN: loaded serial 2023031601
OK

6、重启服务

[root@master named]# systemctl enable --now named.service
Created symlink from /etc/systemd/system/multi-user.target.wants/named.service to /usr/lib/systemd/system/named.service.

7、客户端测试

安装bind-utils
[root@node01 ~]# yum install bind-utils.x86_64  -y
[root@node01 ~]# more /etc/resolv.conf
# Generated by NetworkManager
search localdomain itcast.com
nameserver 192.168.11.148

[root@node01 ~]# nslookup
> dns1.openlab.edu
Server:         192.168.11.148
Address:        192.168.11.148#53

Name:   dns1.openlab.edu
Address: 192.168.11.148
> www.openlab.edu
Server:         192.168.11.148
Address:        192.168.11.148#53

Name:   www.openlab.edu
Address: 192.168.11.111
> set type=cname
> web.openlab.edu
Server:         192.168.11.148
Address:        192.168.11.148#53

web.openlab.edu canonical name = www.openlab.edu.

正向解析成功接下来配置反向解析

1、修改主配置文件

[root@master ~]# vim /etc/named.rfc1912.zones # 路径在配置文件中有
zone "11.168.192.in-addr.arpa" IN {
        type master;
        file "192.168.11.zone";
};

2、修改模板文件

[root@master named]# vim /etc/named.rfc1912.zones
[root@master named]# cp -a named.loopback 192.168.11.zone
[root@master named]# vim 192.168.11.zone
[root@master named]# cat 192.168.11.zone
$TTL 1D
@       IN SOA  dns1.openlab.edu. admin.openlab.edu. (
                                        2023031601      ; serial
                                        1D      ; refresh
                                        1H      ; retry
                                        1W      ; expire
                                        3H )    ; minimum
        NS      dns1.openlab.edu.
dns1.openlab.edu.       A       192.168.11.148
148     PTR     dns1.openlab.edu.
111     PTR     www.openlab.edu.
111     PTR     web.openlab.edu.
222     PTR     mail.openlab.edu.

3、语法检测+重启服务

[root@master named]# named-checkzone "openlab.edu" 192.168.11.zone
zone openlab.edu/IN: loaded serial 2023031601
OK
[root@master named]# systemctl restart named

4、测试

[root@node01 ~]# host -t PTR 192.168.11.148
148.11.168.192.in-addr.arpa domain name pointer dns1.openlab.edu.
[root@node01 ~]# nslookup
> 192.168.11.111
111.11.168.192.in-addr.arpa     name = www.openlab.edu.
111.11.168.192.in-addr.arpa     name = web.openlab.edu.

主从DNS服务器

区域完全传送(主从DNS)

需要俩台DNS服务器:master slave

M:192.168.11.148

S:192.168.11.138

主服务器配置

1、主配置文件

添加允许传送的从服务器,allow-transfer { address_match_elment;...};

[root@master named]# vim /etc/named.conf
options {
        listen-on port 53 { 192.168.11.148; };
        //listen-on-v6 port 53 { ::1; };
        directory       "/var/named";
        dump-file       "/var/named/data/cache_dump.db";
        statistics-file "/var/named/data/named_stats.txt";
        memstatistics-file "/var/named/data/named_mem_stats.txt";
        recursing-file  "/var/named/data/named.recursing";
        secroots-file   "/var/named/data/named.secroots";
        allow-query     { 192.168.11.0/24; };
        allow-transfer { 192.168.11.138;}; # 添加从服务器地址

2、数据文件

[root@master named]# cat openlab.edu.zone
$TTL 1D
@       IN SOA  dns1.openlab.edu. admin.openlab.edu. (
                                        2023031602      ; serial
                                        1D      ; refresh
                                        1H      ; retry
                                        1W      ; expire
                                        3H )    ; minimum
        NS      dns1.openlab.edu.
        NS      dns2.openlab.edu.
        MX 5    mail.openlab.edu.
dns1    A       192.168.11.148
dns2    A       192.168.11.138
mail    A       192.168.11.222
www     A       192.168.11.111
web     CNAME   www


[root@master named]# cat 192.168.11.zone
$TTL 1D
@       IN SOA  dns1.openlab.edu. admin.openlab.edu. (
                                        2023031602      ; serial
                                        1D      ; refresh
                                        1H      ; retry
                                        1W      ; expire
                                        3H )    ; minimum
        NS      dns1.openlab.edu.
        NS      dns2.oppenlab.edu.
dns1.openlab.edu.       A       192.168.11.148
dns2.openlab.edu.       A       192.168.11.138
148     PTR     dns1.openlab.edu.
138     PTR     dns2.openlab.edu.
111     PTR     www.openlab.edu.
111     PTR     web.openlab.edu.
222     PTR     mail.openlab.edu.

3、语法检测

[root@master named]# named-checkzone "openlab.edu" 192.168.11.zone
zone openlab.edu/IN: loaded serial 2023031602
OK

[root@master named]# named-checkzone "openlab.edu" openlab.edu.zone
zone openlab.edu/IN: loaded serial 2023031602
OK

4、重启服务

[root@master named]# systemctl restart named

从服务器配置

1、安装软件

[root@node02 ~]# yum install bind -y

2、主配置文件

[root@node02 ~]# vim /etc/named.conf
options {
        listen-on port 53 { 192.168.11.138; }; # 指向自己的IP
        //listen-on-v6 port 53 { ::1; };
        directory       "/var/named";
        dump-file       "/var/named/data/cache_dump.db";
        statistics-file "/var/named/data/named_stats.txt";
        memstatistics-file "/var/named/data/named_mem_stats.txt";
        secroots-file   "/var/named/data/named.secroots";
        recursing-file  "/var/named/data/named.recursing";
        allow-query     {192.168.11.0/24; }; # 指向网段即可

3、数据文件

[root@node02 ~]# vim /etc/named.rfc1912.zones
zone "openlab.edu" IN {
        type slave;
        file "slaves/opnlab.edu.zone";
        masters {192.168.11.148;};
}; 
zone "11.168.192.in-addr.arpa" IN {
        type slave;
        file "slaves/192.168.11.zone";
        masters {192.168.11.148;};
};

4、语法检测

[root@node02 ~]# named-checkconf

5、测试

[root@node02 ~]# firewall-cmd --permanent --add-service=dns
success
[root@node02 ~]# firewall-cmd --reload
success
[root@node02 ~]# systemctl enable --now named.service
Created symlink /etc/systemd/system/multi-user.target.wants/named.service → /usr/lib/systemd/system/named.service.

[root@node02 ~]# ll /var/named/slaves/
total 8
-rw-r--r--. 1 named named 508 Mar 16 14:25 192.168.11.zone
-rw-r--r--. 1 named named 475 Mar 16 14:25 opnlab.edu.zone

# 可以在本机上测试
[root@node02 ~]# nslookup
> server 192.168.11.138
Default server: 192.168.11.138
Address: 192.168.11.138#53
> www.openlab.edu
Server:         192.168.11.138
Address:        192.168.11.138#53

Name:   www.openlab.edu
Address: 192.168.11.111
> 192.168.11.111
111.11.168.192.in-addr.arpa     name = www.openlab.edu.
111.11.168.192.in-addr.arpa     name = web.openlab.edu.

区域增量传送(主从DNS)

[root@master named]# cat openlab.edu.zone
$TTL 1D
@       IN SOA  dns1.openlab.edu. admin.openlab.edu. (
                                        2023031603      ; serial
                                        1D      ; refresh
                                        1H      ; retry
                                        1W      ; expire
                                        3H )    ; minimum
        NS      dns1.openlab.edu.
        NS      dns2.openlab.edu.
        MX 5    mail.openlab.edu.
dns1    A       192.168.11.148
dns2    A       192.168.11.138
mail    A       192.168.11.222
www     A       192.168.11.111
web     CNAME   www
ftp     A       192.168.11.112
[root@master named]# cat 192.168.11.zone
$TTL 1D
@       IN SOA  dns1.openlab.edu. admin.openlab.edu. (
                                        2023031603      ; serial
                                        1D      ; refresh
                                        1H      ; retry
                                        1W      ; expire
                                        3H )    ; minimum
        NS      dns1.openlab.edu.
        NS      dns2.oppenlab.edu.
dns1.openlab.edu.       A       192.168.11.148
dns2.openlab.edu.       A       192.168.11.148
148     PTR     dns1.openlab.edu.
138     PTR     dns2.openlab.edu.
111     PTR     www.openlab.edu.
111     PTR     web.openlab.edu.
222     PTR     mail.openlab.edu.
112     PTR     ftp.openlab.edu.

重启服务

[root@master named]# systemctl restart named.service

测试

[root@node02 named]# nslookup ftp.openlab.edu 192.168.11.138
Server:         192.168.11.138
Address:        192.168.11.138#53

Name:   ftp.openlab.edu
Address: 192.168.11.112

[root@node02 named]# nslookup 192.168.11.148  192.168.11.138
148.11.168.192.in-addr.arpa     name = dns1.openlab.edu.

web服务器

1、安装软件

[root@node01 ~]# yum install httpd -y

2、设置为开机自启动

[root@node01 ~]# systemctl enable --now httpd

3、查看状态

[root@node01 ~]# systemctl status httpd

4、查看进程

[root@node01 ~]# ps -ef | grep httpd
root        2447       1  0 15:57 ?        00:00:00 /usr/sbin/httpd -DFOREGROUND
root        2521    2146  0 15:58 pts/2    00:00:00 grep --color=auto httpd

5、查看端口

[root@node01 ~]# netstat -lntup | grep 80
tcp6       0      0 :::80                   :::*                    LISTEN      2447/httpd
[root@node01 ~]# ss -lntup | grep 80
tcp   LISTEN 0      128                *:80              *:*    users:(("httpd",pid=2573,fd=4),("httpd",pid=2572,fd=4),("httpd",pid=2571,fd=4),("httpd",pid=2447,fd=4))

6、关闭防火墙或者放行服务

[root@node01 ~]# firewall-cmd --permanent --add-service=http
success
[root@node01 ~]# firewall-cmd --reload
success

7、默认测试

8、默认测试路径

[root@node01 ~]# echo "欢迎来我的web页面" > /var/www/html/index.html
[root@node01 ~]# curl 192.168.11.104
欢迎来我的web页面

虚拟目录别名

1、创建虚拟目录存放位置及虚拟目录默认首页文件

[root@node01 ~]# mkdir /openlab/xxgc -p
[root@node01 ~]# cat /var/www/html/index.html
欢迎访问信息工程系主页!

2、创建、编辑虚拟目录子配置文件

[root@node01 ~]# cat /etc/httpd/conf.d/vdir.conf
Alias /xxgcx "/openlab/xxgc"

    AllowOverride None
    Options Indexes FollowSymLinks
    Require all granted

3、语法检测+重启服务

[root@node01 ~]# httpd -t
Syntax OK
[root@node01 ~]# setenforce 0
[root@node01 ~]# systemctl restart httpd.service

4、测试页面

虚拟主机

三类:

  • 基于IP:一台服务器申请多个IP
  • 基于端口:同一个IP,不同的端口
  • 基于域名:使用同样的IP,同样的端口,不同的域名

如何配?

安装一个在线帮助文档,查看帮助配置

[root@node01 ~]# yum install httpd-manual -y
[root@node01 ~]# systemctl restart httpd.service

基于IP

1、创建目录,准备测试页面

[root@node01 ~]# mkdir -p /openlab/{news,blog,bbs}
[root@node01 ~]# echo "新闻测试页!" > /openlab/news/index.html

[root@node01 ~]# echo "blog测试页!" > /openlab/blog/index.html

[root@node01 ~]# echo "bbs测试页!" > /openlab/bbs/index.html

2、给网卡添加IP,绑定对应的测试页面

news:192.168.11.104
blog:192.168.11.110
bbs:192.168.11.120
[root@node01 ~]# nmcli connection modify ens160 +ipv4.addresses 192.168.11.110/24
[root@node01 ~]# nmcli connection modify ens160 +ipv4.addresses 192.168.11.120/24
[root@node01 ~]#
[root@node01 ~]# nmcli connection up ens160
Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/2)
[root@node01 ~]# ip a
1: lo:  mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: ens160:  mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether 00:0c:29:6b:0b:72 brd ff:ff:ff:ff:ff:ff
    inet 192.168.11.110/24 brd 192.168.11.255 scope global noprefixroute ens160
       valid_lft forever preferred_lft forever
    inet 192.168.11.120/24 brd 192.168.11.255 scope global secondary noprefixroute ens160
       valid_lft forever preferred_lft forever
    inet 192.168.11.104/24 brd 192.168.11.255 scope global secondary dynamic noprefixroute ens160
       valid_lft 1796sec preferred_lft 1796sec
    inet6 fe80::20c:29ff:fe6b:b72/64 scope link noprefixroute
       valid_lft forever preferred_lft forever

3、配置虚拟主机

[root@node01 ~]# cd /etc/httpd/conf.d/
[root@node01 conf.d]#
[root@node01 conf.d]# ls
autoindex.conf  manual.conf  README  userdir.conf  vdir.conf  welcome.conf
[root@node01 conf.d]# vim VirtualHost.conf
[root@node01 conf.d]# cat VirtualHost.conf

    AllowOverride None
    Options Indexes FollowSymLinks
    Require all granted
	


    DocumentRoot "/openlab/news/"
    ServerName news.openlab.edu
    ErrorLog "/openlab/news/error_log"
    CustomLog "/openlab/news/access_log" combined



    DocumentRoot "/openlab/blog/"
    ServerName blog.openlab.edu
    ErrorLog "/openlab/blog/error_log"
    CustomLog "/openlab/blog/access_log" combined





    DocumentRoot "/openlab/bbs/"
    ServerName bbs.openlab.edu
    ErrorLog "/openlab/bbs/error_log"
    CustomLog "/openlab/bbs/access_log" combined

4、语法检测+重启服务

[root@node01 conf.d]# httpd -t
Syntax OK
[root@node01 conf.d]# systemctl restart httpd.service

5、测试

6、恢复环境

[root@node01 conf.d]# nmcli connection modify ens160 -ipv4.addresses 192.168.11.120/24
[root@node01 conf.d]# nmcli connection modify ens160 -ipv4.addresses 192.168.11.110/24
[root@node01 conf.d]# nmcli connection up ens160

基于端口

1、修改配置文件

[root@node01 conf.d]# cat VirtualHost.conf

    DocumentRoot "/openlab/news/"
    ServerName news.openlab.edu
    ErrorLog "/openlab/news/error_log"
    CustomLog "/openlab/news/access_log" combined



    DocumentRoot "/openlab/blog/"
    ServerName blog.openlab.edu
    ErrorLog "/openlab/blog/error_log"
    CustomLog "/openlab/blog/access_log" combined





    DocumentRoot "/openlab/bbs/"
    ServerName bbs.openlab.edu
    ErrorLog "/openlab/bbs/error_log"
    CustomLog "/openlab/bbs/access_log" combined



    AllowOverride None
    Options Indexes FollowSymLinks
    Require all granted

Listen 81
Listen 82

2、重启服务 + 关闭防火墙 +selinux

[root@node01 conf.d]# systemctl restart httpd.service
[root@node01 conf.d]# systemctl stop firewalld.service
[root@node01 conf.d]# setenforce 0
[root@node01 conf.d]# systemctl restart httpd.service
[root@node01 conf.d]# ss -lntup | grep 81
tcp   LISTEN 0      128                *:81              *:*    users:(("httpd",pid=39951,fd=9),("httpd",pid=39601,fd=9),("httpd",pid=39600,fd=9),("httpd",pid=39599,fd=9),("httpd",pid=39476,fd=9))
[root@node01 conf.d]# ss -lntup | grep 82
tcp   LISTEN 0      128                *:82              *:*    users:(("httpd",pid=39951,fd=11),("httpd",pid=39601,fd=11),("httpd",pid=39600,fd=11),("httpd",pid=39599,fd=11),("httpd",pid=39476,fd=11))
[root@node01 conf.d]# ss -lntup | grep 80
tcp   LISTEN 0      128                *:80              *:*    users:(("httpd",pid=39951,fd=4),("httpd",pid=39601,fd=4),("httpd",pid=39600,fd=4),("httpd",pid=39599,fd=4),("httpd",pid=39476,fd=4))

3、测试

基于域名

1、修改配置文件

[root@node01 conf.d]# cat VirtualHost.conf

    DocumentRoot "/openlab/news/"
    ServerName news.openlab.edu
    ErrorLog "/openlab/news/error_log"
    CustomLog "/openlab/news/access_log" combined



    DocumentRoot "/openlab/blog/"
    ServerName blog.openlab.edu
    ErrorLog "/openlab/blog/error_log"
    CustomLog "/openlab/blog/access_log" combined





    DocumentRoot "/openlab/bbs/"
    ServerName bbs.openlab.edu
    ErrorLog "/openlab/bbs/error_log"
    CustomLog "/openlab/bbs/access_log" combined



    AllowOverride None
    Options Indexes FollowSymLinks
    Require all granted

2、重启服务

[root@node01 conf.d]# systemctl restart httpd.service

3、没有DNS情况下修改hosts文件

[root@node01 conf.d]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6

192.168.11.104 news.openlab.edu blog.openlab.edu bbs.openlab.edu

4、测试

[root@node01 conf.d]# curl news.openlab.edu
新闻测试页!
[root@node01 conf.d]# curl blog.openlab.edu
blog测试页!
[root@node01 conf.d]# curl bbs.openlab.edu
bbs测试页!

个人页面网站

1、修改redhat权限

[root@node01 conf.d]# cd /home/redhat/
[root@node01 redhat]# chmod 711 /home/redhat/

2、创建public_html目录

[root@node01 redhat]# mkdir public_html

3、写index.html默认页面

[root@node01 redhat]# echo "这是redhat个人测试页面" > public_html/index.html

4、关闭防火墙和selinux

[root@node01 redhat]# systemctl is-active firewalld.service
inactive
[root@node01 redhat]# getenforce
Permissive

5、修改配置文件

[root@node01 conf.d]# vim userdir.conf

    #UserDir disabled
    UserDir public_html

6、语法检测+重启服务

[root@node01 conf.d]# httpd -t
Syntax OK
[root@node01 conf.d]# systemctl restart httpd.service

加密解密

案例:基于https的静态站点

第一阶段:制作CA根证书

1、制作CA秘钥

操作过程:设置CA秘钥口令(123456)

[root@node01 httpd]# mkdir /etc/httpd/ssl
[root@node01 httpd]# cd /etc/httpd/ssl/
[root@node01 ssl]# openssl genrsa -des3 -out ca.key 2048
Generating RSA private key, 2048 bit long modulus (2 primes)
............+++++
............................................................................................................................................................+++++
e is 65537 (0x010001)
Enter pass phrase for ca.key:
Verifying - Enter pass phrase for ca.key:

2、制作CA根证书申请

[root@node01 ssl]# openssl req -new -key ca.key  -out ca.csr
Enter pass phrase for ca.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) []:SX
Locality Name (eg, city) [Default City]:Sx
Organization Name (eg, company) [Default Company Ltd]:openlab
Organizational Unit Name (eg, section) []:openlab
Common Name (eg, your name or your server's hostname) []:tom
Email Address []:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

3、生成根签名证书

[root@node01 ssl]# openssl x509 -req -days 3650 -signkey ca.key -in ca.csr -out ca.crt
Signature ok
subject=C = CN, ST = SX, L = Sx, O = openlab, OU = openlab, CN = tom
Getting Private key
Enter pass phrase for ca.key:

[root@node01 ssl]# ls
ca.crt  ca.csr  ca.key

第二阶段:制作服务器证书

1、制作服务器秘钥

[root@node01 ssl]# openssl genrsa -des3 -out server.key 2048
Generating RSA private key, 2048 bit long modulus (2 primes)
..........................................................................................+++++
..................................+++++
e is 65537 (0x010001)
Enter pass phrase for server.key:
Verifying - Enter pass phrase for server.key:

2、制作服务器证书签名申请

[root@node01 ssl]# openssl req -new -key server.key -out server.csr
Enter pass phrase for server.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) []:SC
Locality Name (eg, city) [Default City]:cd
Organization Name (eg, company) [Default Company Ltd]:it
Organizational Unit Name (eg, section) []:it
Common Name (eg, your name or your server's hostname) []:www.it.edu
Email Address []:

Please enter the following 'extra' attributes
to be sent with your certificate request
A challenge password []:
An optional company name []:

3、签署证书

[root@node01 ssl]# openssl x509 -req -days 3560 -CA ca.crt -CAkey ca.key  -CAcreateserial -in server.csr -out server.crt
Signature ok
subject=C = CN, ST = SC, L = cd, O = it, OU = it, CN = www.it.edu
Getting CA Private Key
Enter pass phrase for ca.key:
[root@node01 ssl]# ls
ca.crt  ca.csr  ca.key  ca.srl  server.crt  server.csr  server.key

4、配置虚拟主机

[root@node01 ssl]# vim /etc/httpd/conf.d/vhost.conf

DocumentRoot /var/www/web
ServerName www.openlab.edu
SSLEngine on
SSLProtocol all -SSLv2
SSLCipherSuite HIGH:MEDIUM:!aNULL:!MD5:!IDEA
SSLCertificateFile /etc/httpd/ssl/server.crt
SSLCertificateKeyFile /etc/httpd/ssl/server.key
SSLCertificateChainFile  /etc/httpd/ssl/ca.crt

5、测试页面

[root@node01 ~]# mkdir /var/www/web
[root@node01 ~]# echo "https测试页面!..."> /var/www/web/index.html

6、重启服务

[root@node01 ssl]# systemctl restart httpd.service
Enter TLS private key passphrase for www.openlab.edu:443 (RSA) : ******

LAMP环境

1、安装软件

[root@node01 ~]# yum install httpd mariadb-server php  php-gd php-mysqlnd.x86_64  -y

2、测试环境

Apache和php协同

[root@node01 ~]# cd /var/www/html/
[root@node01 html]# vim phpinfo.php
[root@node01 html]# cat phpinfo.php

[root@node01 html]# systemctl enable --now httpd php-fpm.service

php与mariadb协同

启动数据库

[root@node01 html]# systemctl enable --now mariadb

初始安全设置

[root@node01 html]# mysql_secure_installation

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user.  If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none):
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.

Set root password? [Y/n] y
New password:
Re-enter new password:
Password updated successfully!
Reloading privilege tables..
 ... Success!


By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] y
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] y
 ... Success!

By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] y
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] y
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

测试php数据库

[root@node01 html]# cat php_mysql.php
connect_error)
  {
  die('Could not connect: ' . $con->connect_error);
  }
else{
echo "Success!";
}
// some code
mysql_close($con);
?>

测试完毕!删除这俩个文件!

3、部署php应用

博客 论坛 门户网站

1> 上传软件

2> 解压到指定目录

3> 修改权限

4> 向导安装

FTP服务器

服务端:

1、安装软件

[root@node01 ~]# yum install vsftpd.x86_64 -y

2、重启服务

[root@node01 ~]# systemctl restart vsftpd.service

3、查看状态

[root@node01 ~]# systemctl status vsftpd.service

4、查看端口

[root@node01 ~]# ss -lntup | grep ftp
tcp   LISTEN 0      32                 *:21              *:*    users:(("vsftpd",pid=2669,fd=3))

5、放行服务

[root@node01 ~]# firewall-cmd --permanent --add-service=ftp
success
[root@node01 ~]# firewall-cmd --reload
success
[root@node01 ~]# firewall-cmd --list-all
public (active)
  target: default
  icmp-block-inversion: no
  interfaces: ens160
  sources:
  services: cockpit dhcpv6-client ftp ssh
  ports:
  protocols:
  forward: no
  masquerade: no
  forward-ports:
  source-ports:
  icmp-blocks:
  rich rules:

6、修改主配置文件

[root@node01 ~]# vim /etc/vsftpd/vsftpd.conf
#anonymous_enable=NO
anonymous_enable=yes

[root@node01 ~]# systemctl restart vsftpd.service

客户端

1、安装软件

[root@node02 ~]# yum install ftp.x86_64  lftp -y

2、连接

[root@node02 ~]# ftp 192.168.11.104
Connected to 192.168.11.104 (192.168.11.104).
220 (vsFTPd 3.0.3)
Name (192.168.11.104:root): anonymous
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp>bye


[root@node02 ~]# lftp 192.168.11.104
lftp 192.168.11.104:~> user ftp
Password:
lftp [email protected]:~> ls
drwxr-xr-x    2 0        0               6 Apr 22  2021 pub
lftp [email protected]:/> exit

案例:扩展学校的FTP服务器

1、建立用于维护网站的禁止登录且家目录为/var/www/web1的用户user1 设置用户密码 创建用于测试的文件

[root@node01 ~]# mkdir -p /var/www/web1
[root@node01 ~]# echo "www.openlab.edu" > /var/www/web1/本地用户访问ftp.txt
[root@node01 ~]# chmod -R 757 /var/www/web1/

[root@node01 ~]# useradd user1 -s /bin/bash

[root@node01 ~]# echo 123456 | passwd --stdin user1
Changing password for user user1.
passwd: all authentication tokens updated successfully.
[root@node01 ~]# chown -R user1 /var/www/web1/

[root@node01 ~]# ll -d /var/www/web1/
drwxr-xrwx. 2 user1 root 39 Mar 18 14:23 /var/www/web1/

2、编辑主配置文件 重启服务

[root@node01 ~]# vim /etc/vsftpd/vsftpd.conf
local_enable=YES
anonymous_enable=NO
local_root=/var/www/web1
write_enable=YES
local_umask=022
connect_from_port_20=YES
chroot_local_user=NO
chroot_list_enable=YES
chroot_list_file=/etc/vsftpd/chroot_list
allow_writeable_chroot=YES
[root@node01 ~]# systemctl restart vsftpd.service

3、建立/etc/vsftpd/chroot_list文件,锁定用户

[root@node01 ~]# cat /etc/vsftpd/chroot_list
user1

4、测试

[root@node02 ~]# ftp 192.168.11.104
Connected to 192.168.11.104 (192.168.11.104).
220 (vsFTPd 3.0.3)
Name (192.168.11.104:root): user1
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp>

案例:配置一个虚拟用户访问ftp

本地用户user2

虚拟用户z3 l4

虚拟用户目录:

z3 /ftp/public 下载

l4 /var/www/web2 上传下载

1、创建虚拟用户对应的本地用户及目录

[root@node01 ~]# useradd user2 -s /sbin/nologin
[root@node01 ~]# mkdir -p /ftp/public /var/www/web2
[root@node01 ~]# echo "test file "> /ftp/public/f1.txt
[root@node01 ~]# echo "test file "> /var/www/web2/f1.txt
[root@node01 ~]# chown user2 /var/www/web2/ /ftp/public/
[root@node01 ~]# chmod  -R 755 /var/www/web2/ /ftp/public/

2、创建虚拟用户文件

[root@node01 ~]# cat /etc/vsftpd/vuser.list
z3
123
l4
456

3、转换虚拟用户文件

[root@node01 ~]# db_load -T -t hash -f /etc/vsftpd/vuser.list  /etc/vsftpd/vuser.db
[root@node01 ~]# chmod 600 /etc/vsftpd/vuser.*

4、创建用户用户登录时的PAM文件

[root@node01 ~]# cd /etc/pam.d/
[root@node01 pam.d]# cp -p vsftpd vuser.vu
[root@node01 pam.d]# vim vuser.vu
[root@node01 pam.d]# cat vuser.vu
#%PAM-1.0
auth    sufficient      pam_userdb.so   db=/etc/vsftpd/vuser
account sufficient      pam_userdb.so   db=/etc/vsftpd/vuser
session    optional     pam_keyinit.so    force revoke
auth       required     pam_listfile.so item=user sense=deny file=/etc/vsftpd/ftpusers onerr=succeed
auth       required     pam_shells.so
auth       include      password-auth
account    include      password-auth
session    required     pam_loginuid.so
session    include      password-auth

5、修改配置文件

[root@node01 ~]# vim /etc/vsftpd/vsftpd.conf

anonymous_enable=NO //禁止匿名登录
local_enable=YES //允许本地用户模式,由于映射的系统用户为本地用户,因此此项必须开启
guest_enable=YES //开启虚拟用户模式
guest_username=user2 //指定虚拟用户账号映射到本地账号vftp
pam_service_name=vuser.vu //指定pam文件
chroot_local_user=YES //禁锢用户在其家目录
allow_writeable_chroot=YES //允许禁锢的FTP根目录可写
user_config_dir=/etc/vsftpd/vconfig //指定虚拟用户的权限配置目录
userlist_enable=YES
userlist_deny=YES
virtual_user_local_privs=YES

6、虚拟用户配置专用文件

[root@node01 ~]# mkdir  -p /etc/vsftpd/vconfig

[root@node01 ~]# cat /etc/vsftpd/vconfig/z3
local_root=/ftp/public/
anno_world_readable_only=YES
write_enable=NO
anno_max_rate=500000

[root@node01 ~]# cat /etc/vsftpd/vconfig/l4
local_root=/var/www/web2/
write_enable=YES
anno_upload_enable=YES
anno_mkdir_wirte_enable=YES
anno_other_write_enable=YES
anno_max_rate=500000

你可能感兴趣的:(ansible,linux,bash,运维,服务器)