[内容] Ansible 常模模块 (转载)

Ansible常用模块详解

Ansible常用模块详解

命令模块
command
shell
文件模块
copy
fetch
file
安装模块
yum
服务模块
service
挂载模块
mount
定时任务
cron
用户模块
group
user
压缩解压
unarchive

ansible内置了丰富的模块供用户使用,但是经常使用到的模块却不多。本文主要记录了ansible的一些常用模块以及详细参数 、注意事项等 ,供大家学习。
命令模块

command

概要
命令模块 适合使用简单的命令 无法支持"<",">","|",";","&"等符号
官方文档:https://docs.ansible.com/ansible/latest/modules/command_module.html#command-module

参数	选项/默认值	释义
chdir		在执行命令前,进入到指定目录中
creates		判断指定文件是否存在,如果存在,不执行后面的操作
removes		判断指定文件是否存在,如果存在,执行后面的操作
free_form		必须要输入一个合理的命令
备注:无法支持"<",">","|",";","&"等符号
示例:

root@m01 ~]# ansible dkaiyun -m command -a "hostname"
web01 | CHANGED | rc=0 >>
web01

nfs01 | CHANGED | rc=0 >>
nfs01

backup01 | CHANGED | rc=0 >>
backup
1
2
3
4
5
6
7
8
9
chdir

[root@m01 ~]# ansible dkaiyun -m command -a "chdir=/data ls -l"
web01 | CHANGED | rc=0 >>
total 4
-rw-r--r-- 1 root root 158 Jan 12 11:11 hosts

backup01 | CHANGED | rc=0 >>
total 4
-rw-r--r-- 1 root root 4 Jan 13 18:06 lol.txt

nfs01 | CHANGED | rc=0 >>
total 4
-rw-r--r-- 1 root root 13 Jan 17 18:45 bbb.txt
1
2
3
4
5
6
7
8
9
10
11
12
creates

[root@m01 ~]# ansible dkaiyun -m command -a "touch /data/lol.txt creates=/data/lol.txt"
 [WARNING]: Consider using the file module with state=touch rather than running touch.  If you need to use command because file is insufficient you can add
warn=False to this command task or set command_warnings=False in ansible.cfg to get rid of this message.

nfs01 | CHANGED | rc=0 >>


backup01 | SUCCESS | rc=0 >>
skipped, since /data/lol.txt exists

web01 | CHANGED | rc=0 >>


1
2
3
4
5
6
7
8
9
10
11
12
13
removes

[root@m01 ~]# ansible dkaiyun -m command -a "rm -f /data/hosts removes=/data/hosts"
nfs01 | SUCCESS | rc=0 >>
skipped, since /data/hosts does not exist

backup01 | SUCCESS | rc=0 >>
skipped, since /data/hosts does not exist

 [WARNING]: Consider using the file module with state=absent rather than running rm.  If you need to use command because file is insufficient you can add
warn=False to this command task or set command_warnings=False in ansible.cfg to get rid of this message.

web01 | CHANGED | rc=0 >>

1
2
3
4
5
6
7
8
9
10
11
12
shell

概要
类似command模块升级版—万能模块
官方文档:https://docs.ansible.com/ansible/latest/modules/shell_module.html#shell-module

参数	选项/默认值	释义
chdir		在执行命令前,进入到指定目录中
creates		判断指定文件是否存在,如果存在,不执行后面的操作
removes		判断指定文件是否存在,如果存在,执行后面的操作
free_form		必须要输入一个合理的命令
备注:可以使用"<",">","|",";","&"等符号特殊符号
示例:

[root@m01 ~]# ansible dkaiyun -m shell -a "ps -ef |grep /[s]sh"
backup01 | CHANGED | rc=0 >>
root       2042      1  0 09:06 ?        00:00:00 /usr/sbin/sshd -D

nfs01 | CHANGED | rc=0 >>
root       1258      1  0 08:32 ?        00:00:00 /usr/sbin/sshd -D

web01 | CHANGED | rc=0 >>
root       1197      1  0 11:39 ?        00:00:00 /usr/sbin/sshd -D

1
2
3
4
5
6
7
8
9
10
注:其它参数参考command模块 使用方法一致

文件模块

copy

概要
主要用于将管理主机上的数据信息传送给多台主机
官方文档:https://docs.ansible.com/ansible/latest/modules/copy_module.html#copy-module

参数	选项/默认值	释义
src		指定将本地管理主机的什么数据信息进行远程复制
backup	no* yes	默认数据复制到远程主机,会覆盖原有文件(yes 将源文件进行备份)
content		在文件中添加信息
dest(required)		将数据复制到远程节点的路径信息
group		文件数据复制到远程主机,设置文件属组用户信息
mode		文件数据复制到远程主机,设置数据的权限 eg 0644 0755
owner		文件数据复制到远程主机,设置文件属主用户信息
remote_src	no* yes	如果设置为yes,表示将远程主机上的数据进行移动操作如果设置为no, 表示将管理主机上的数据进行分发操作
备注 (required)为必须使用的参数
*为默认参数
copy模块在复制数据时,如果数据为软链接文件,会将链接指定源文件进行复制
修改权限时候 需要加0 例如:chmod 0644 0755
示例:

[root@m01 ~]# ansible web01 -m copy -a "src=./anaconda-ks.cfg  dest=/data"
web01 | CHANGED => {
    "changed": true, 
    "checksum": "9d791df2961e299fac1206c2e1c6ab1cde2c86a2", 
    "dest": "/data/anaconda-ks.cfg", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "221e5656c9b59aec6c7596568fff8ad3", 
    "mode": "0644", 
    "owner": "root", 
    "size": 1499, 
    "src": "/root/.ansible/tmp/ansible-tmp-1548229670.84-2879942383233/source", 
    "state": "file", 
    "uid": 0
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
backup

[root@m01 ~]# ansible web01 -m copy -a "src=./anaconda-ks.cfg  dest=/data backup=yes"
web01 | CHANGED => {
    "backup_file": "/data/anaconda-ks.cfg.4263.2019-01-23@15:52:43~", 
    "changed": true, 
    "checksum": "9d791df2961e299fac1206c2e1c6ab1cde2c86a2", 
    "dest": "/data/anaconda-ks.cfg", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "221e5656c9b59aec6c7596568fff8ad3", 
    "mode": "0644", 
    "owner": "root", 
    "size": 1499, 
    "src": "/root/.ansible/tmp/ansible-tmp-1548229931.86-180942706957431/source", 
    "state": "file", 
    "uid": 0
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[root@web01 ~]# ll /data/
total 8
-rw-r--r-- 1 root root 1499 Jan 23 15:52 anaconda-ks.cfg
-rw-r--r-- 1 root root 1505 Jan 23 15:52 anaconda-ks.cfg.4263.2019-01-23@15:52:43~
1
2
3
4
owner group mode

[root@m01 ~]# ansible web01 -m copy -a "src=./anaconda-ks.cfg  dest=/data owner=www group=www mode=0644"
web01 | CHANGED => {
    "changed": true, 
    "checksum": "9d791df2961e299fac1206c2e1c6ab1cde2c86a2", 
    "dest": "/data/anaconda-ks.cfg", 
    "gid": 1086, 
    "group": "www", 
    "md5sum": "221e5656c9b59aec6c7596568fff8ad3", 
    "mode": "0644", 
    "owner": "www", 
    "size": 1499, 
    "src": "/root/.ansible/tmp/ansible-tmp-1548230667.08-106764271060692/source", 
    "state": "file", 
    "uid": 1086
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[root@web01 data]# ll
total 4
-rw-r--r-- 1 www www 1499 Jan 23 16:04 anaconda-ks.cfg
1
2
3
content

[root@m01 ~]# ansible web01 -m copy -a "content=test  dest=/data/anaconda-ks.cfg "
web01 | CHANGED => {
    "changed": true, 
    "checksum": "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3", 
    "dest": "/data/anaconda-ks.cfg", 
    "gid": 1086, 
    "group": "www", 
    "md5sum": "098f6bcd4621d373cade4e832627b4f6", 
    "mode": "0644", 
    "owner": "www", 
    "size": 4, 
    "src": "/root/.ansible/tmp/ansible-tmp-1548231000.52-150895010308573/source", 
    "state": "file", 
    "uid": 1086
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@web01 data]# cat anaconda-ks.cfg 
test[root@web01 data]#
注:content添加内容不会添加回车符 
1
2
3
fetch

概要
抓取文件到管理机上
官方文档:https://docs.ansible.com/ansible/latest/modules/fetch_module.html#fetch-module

参数	选项/默认值	释义
src(required)		要获取的远程系统上的文件,必须是文件,而不是目录
dest		用于保存文件的目录
备注
示例:

[root@m01 ~]# ansible web01 -m fetch -a "src=/root/lol.txt dest=/root"
web01 | CHANGED => {
    "changed": true, 
    "checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709", 
    "dest": "/root/web01/root/lol.txt", 
    "md5sum": "d41d8cd98f00b204e9800998ecf8427e", 
    "remote_checksum": "da39a3ee5e6b4b0d3255bfef95601890afd80709", 
    "remote_md5sum": null
}
[root@m01 ~]# tree ~
/root
└── web01
    └── root
        └── lol.txt

2 directories, 1 file
[root@m01 ~]# 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
file

概要
实现创建/删除文件信息 对数据权限进行修改
官方文档:https://docs.ansible.com/ansible/latest/modules/file_module.html#file-module

参数	选项/默认值	释义
dest/path/name(required)		将数据复制到远程节点的路径信息
group		文件数据复制到远程主机,设置文件属组用户信息
mode		文件数据复制到远程主机,设置数据的权限 eg 0644 0755
owner		文件数据复制到远程主机,设置文件属主用户信息
src		指定将本地管理主机的什么数据信息进行远程复制
state	absent	将数据进行删除
=	directory	创建一个空目录信息
=	file	查看指定目录信息是否存在
=	touch	创建一个空文件信息
=	hard/link	创建链接文件
备注
示例:

安装模块

yum

概要
使用yum软件包管理器安装,升级,降级,删除和列出软件包和组。
官方文档:https://docs.ansible.com/ansible/latest/modules/yum_repository_module.html#yum-repository-module

参数	选项/默认值	释义
name(required)		指定软件名称信息
state	absent/removed	将软件进行卸载(慎用)
=	present/installed	将软件进行安装
latest		安装最新的软件 yum update
备注
示例:

[root@m01 ~]# ansible web01 -m yum -a "name=httpd-tools state=installed"
1
服务模块

service

概要
用于管理服务运行状态
官方文档:https://docs.ansible.com/ansible/latest/modules/service_module.html#service-module

参数	选项/默认值	释义
enabled	no yes	设置服务是否开机自启动 如果参数不指定,原有服务开机自启动状态进行保留
name (required)		设置要启动/停止服务名称
state=	reloaded	平滑重启
=	restarted	重启
=	started	启动
=	stopped	停止
备注
示例:

[root@m01 ~]# ansible web01 -m service -a "name=crond state=started enabled=yes"
1
挂载模块

mount

概要
用于批量管理主机进行挂载卸载操作
官方文档:https://docs.ansible.com/ansible/latest/modules/mount_module.html#mount-module

参数	选项/默认值	释义
fstype		指定挂载的文件系统类型
opts		指定挂载的参数信息
path		定义一个挂载点信息
src		定义设备文件信息
state	absent	会进行卸载,也会修改fstab文件信息
=	unmounted	会进行卸载,不会修改fstab文件
=	present	不会挂载,只会修改fstab文件
=	mounted	会进行挂载,会修改fstab文件
在进行挂载的时候,使用state=mounted
在进行卸载的时候,使用state=absent
示例:

[root@m01 ~]# ansible web01 -m mount -a "src=172.16.1.31:/data/  path=/mnt fstype=nfs state=present"
以上信息只是在/etc/fstab文件中添加了配置信息,不会真正进行挂载(mount -a)
[root@m01 ~]# ansible web01 -m mount -a "src=172.16.1.31:/data/  path=/mnt fstype=nfs state=mounted"
以上信息是在/etc/fstab文件中添加了配置信息,并且也会真正进行挂载
1
2
3
4
定时任务

cron

概要
定时任务模块
官方文档:https://docs.ansible.com/ansible/latest/modules/cron_module.html#cron-module

参数	选项/默认值	释义
minute/hour/day/month/weekday		和设置时间信息相关参数
job		和设置定时任务相关参数
name(required)		设置定时任务注释信息
state	absent	删除指定定时任务
disabled	yes	将指定定时任务进行注释
=	no	取消注释
备注:时间参数不写时,默认为 *
示例:
每五分钟同步一次时间

[root@m01 ~]# ansible web01 -m cron -a "name='ntpdate time' minute=*/5 job='/usr/sbin/ntpdate ntp1.aliyun.com &>/dev/null' "
web01 | CHANGED => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "None", 
        "ntpdate time"
    ]
}

1
2
3
4
5
6
7
8
9
10
结果

[root@web01 data]# crontab -l
#Ansible: ntpdate time
*/5 * * * * /usr/sbin/ntpdate ntp1.aliyun.com &>/dev/null
1
2
3
删除定时任务

[root@m01 ~]# ansible web01 -m cron -a "name='ntpdate time' state=absent"
web01 | CHANGED => {
    "changed": true, 
    "envs": [], 
    "jobs": []
}

1
2
3
4
5
6
7
注释定时任务
注意:注释和取消注释时必须填写 job和时间 参数

[root@m01 ~]# ansible web01 -m cron -a "name='ntpdate time' minute=*/5 job='/usr/sbin/ntpdate ntp1.aliyun.com &>/dev/null' disabled=yes"
web01 | CHANGED => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "ntpdate time"
    ]
}

1
2
3
4
5
6
7
8
9
结果

[root@web01 data]# crontab -l
#Ansible: ntpdate time
#*/5 * * * * /usr/sbin/ntpdate ntp1.aliyun.com &>/dev/null

1
2
3
4
取消注释

[root@m01 ~]# ansible web01 -m cron -a "name='ntpdate time' minute=*/5 job='/usr/sbin/ntpdate ntp1.aliyun.com &>/dev/null' disabled=no"
web01 | CHANGED => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "ntpdate time"
    ]
}

1
2
3
4
5
6
7
8
9
结果

[root@web01 data]# crontab -l
#Ansible: ntpdate time
*/5 * * * * /usr/sbin/ntpdate ntp1.aliyun.com &>/dev/null

1
2
3
4
用户模块

group

概要
远程批量创建用户组信息
官方文档:https://docs.ansible.com/ansible/latest/modules/group_module.html#group-module

参数	选项/默认值	释义
gid		指创建的组ID信息
name		指创建组名称信息
state	absent	删除指定的用户组
=	present	创建指定的用户组
备注
示例:
创建一个指定的用户组dkaiyun gid=1055

ansible web01 -m group -a "name=dkaiyun gid=1055"
1
删除一个指定的用户组dkaiyun gid=1055

ansible web01 -m group -a "dkaiyun gid=1055 state=absent"
1
user

概要
远程批量创建用户信息
官方文档:https://docs.ansible.com/ansible/latest/modules/user_module.html#user-module

参数	选项/默认值	释义
password		请输入密码信息
name		指定用户名信息
uid		指定用户uid信息
group		指定用户主要属于哪个组
groups		指定用户属于哪个附加组信息
shell	/bin/bash或/sbin/nologin	指定是否能够登录
create_home	yes/no	是否创建家目录信息
home		指定家目录创建在什么路径 默认/home
备注:password设置密码时不能使用明文方式,只能使用密文方式
可以给用户设置密码 还可以给用户修改密码
示例:

压缩解压

unarchive

概要

官方文档:https://docs.ansible.com/ansible/latest/modules/unarchive_module.html#unarchive-module

参数	选项/默认值	释义
备注
示例:


————————————————
版权声明:本文为CSDN博主「最爱下一站」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_34646546/article/details/86606408

注明:所有转载内容皆直接从被转载文章网页的标题和内容的文本中复制而来

CC 4.0 BY-SA 版权协议网址:https://creativecommons.org/licenses/by-sa/4.0/deed.z

[内容] Django 模型层 Models Layer 常用数据库字段

内容一:Django Models 常用的文本字段

1.1 CharField() 字符串字段

1.1.1 CharField() 字符串字段的格式
<field> = models.CharField(max_length = <string length>, <option>)
1.1.2 CharField() 字符串字段的必选项
max_length = <text length>

或者:

max_length = None
1.1.3 CharField() 字符串字段的可选项
1) blank = True

值可以为空


2) null = True

值可以为空


3) default = '<default value>'

值可以为空,可以设置成其他的值


4) unique = True

值唯一

1.1.4 CharField() 字符串字段的使用案例
item = models.CharField(max_length = 20, unique = True)

(补充:这里以设置名为 item,且是唯一的 CharField() 字符串字段为例)

1.2 TextField() 文本字段

1.2.1 TextField() 文本字段的格式
<field> = models.TextField(max_length = <string length>, <option>)
1.2.2 TextField() 文本字段的必选项
max_length = <text length>

或者:

max_length = None
1.2.3 TextField() 文本字段的可选项
1) blank = True

值可以为空


2) null = True

值可以为空


3) default = '<default value>'

值可以为空,可以设置成其他的值


4) unique = True

值唯一

1.2.4 TextField() 文本字段的使用案例
item = models.TextField(max_length = 20, unique = True)

(补充:这里以设置名为 item,且是唯一的 TextField() 文本字段为例)

内容二:Django Models 常用的数值字段

2.1 IntegerField() 整数字段

2.1.1 IntegerField() 整数字段的格式
<field> = models.IntegerField(<option>)
2.1.2 IntegerField() 整数字段的可选项
1) blank = True

值可以为空


2) null = True

值可以为空


3) default = '<default value>'

值可以为空,可以设置成其他的值

2.1.3 IntegerField() 整数字段的使用案例
item = models.IntegerField()

(补充:这里以设置名为 item 的整数字段为例)

2.2 PositiveIntegerFiled() 正整数字段

2.2.1 PositiveIntegerFiled() 正整数字段的格式
<field> = models.IntegerField(<option>)
2.2.2 PositiveIntegerFiled() 正整数字段的可选项

1) blank = True

值可以为空


2) null = True

值可以为空


3) default = '<default value>'

值可以为空,可以设置成其他的值

2.2.3 PositiveIntegerFiled() 正整数字段的使用案例
item = models.TextField()

(补充:这里以设置名为 item 的正整数字段为例)

2.3 DecimalField() 小数字段

2.3.1 DecimalField() 小数字段的格式
<field> = models.DecimalField(max_digits = <total number of decimal places>, decimal_places = <how many places after the decimal point>)
2.3.2 DecimalField() 小数字段的必选项
1) max_digits = <total number of decimal places>

小数字段总共位数

2) decimal_places = <how many places after the decimal point>

小数字段小数点后保留几位

2.2.3 DecimalField() 小数字段的使用案例
item = models.DecimalField(max_digits = 5, decimal_places = 2)

(补充:这里以设置名为 item,长度为 5,小数点后保留 2 位的 DecimalField() 小数字段为例)

内容三:Django Models 常用的日期字段

3.1 DateField() 日期字段

3.1.1 DateField() 日期字段的格式
<field> = models.DateField(<option>)
3.1.2 DateField() 日期字段的可选项
auto_now = True

自动更新创建时间

3.1.3 DateField() 日期字段的使用案例
item = models.DateField(auto_now_add=True)

(补充:这里以设置名为 item,可自动更新的 DateField() 日期字段为例)

3.2 DateTimeField() 日期时间字段

3.2.1 DateTimeField() 日期时间字段的格式
<field> = models.DateTimeField(<option>)
3.2.2 DateTimeField() 日期时间字段的可选项
auto_now = True

自动更新创建时间

3.2.3 DateTimeField() 日期时间字段的使用案例
item = models.DateTimeField(auto_now_add=True)

(补充:这里以设置名为 item,可自动更新的 DateTimeField() 日期时间字段为例)

内容四:Django Models 常用的标准格式字段

4.1 GenericIPAddressField() IPv4 地址字段

4.1.1 GenericIPAddressField() IPv4 地址字段的格式
<field> = models.IPAddressField()


补充:
在老的 Django 版本里,此字段的真实名称是:

models.IPAddressField()
)
4.1.2 GenericIPAddressField() IPv4 地址字段的使用案例
item = models.IPAddressField()

(补充:这里以设置名为 item 的 IPAddressField() IPv4 地址字段为例)


补充:
在老的 Django 版本里,此字段的真实名称是:

models.IPAddressField()
)

4.2 EmailField() 邮件地址字段

4.2.1 EmailField() 邮件地址字段的格式
<field> = models.EmailField(<option>)
4.2.2 EmailField() 邮件地址字段的可选项
unique = True

值唯一

4.2.3 EmailField() 邮件地址字段的使用案例
item = models.EmailField(unique = True)

(补充:这里以设置名为 item 的,且是唯一的 EmailField() 邮件地址字段为例)

4.3 UUIDField() UUID 字段

4.3.1 UUIDField() UUID 字段的格式
<field> = models.UUIDField()
4.3.2 UUIDField() UUID 字段的案例
item = models.UUIDField()

(补充:这里以设置名为 item 的 UUIDField() UUID 字段为例)

内容五:Django Models 常用的逻辑字段

5.1 AutoField() 自动递增字段

5.1.1 AutoField() 自动递增字段的格式
<field> = models.AutoField(<option>)
5.1.2 AutoField() 自动递增的可选项
primary_key = True

设置为主键

5.1.3 AutoField() 自动递增的使用案例
item = models.AutoField(primary_key = True)

(补充:这里以设置名为 item 的,且设置为主键的 AutoField() 自动递增字段为例)

5.2 BooleanField() 布尔(boolean)值字段

5.2.1 BooleanField() 布尔(boolean)值字段的格式
<field> = models.BooleanField(<option>)
5.2.2 BooleanField() 布尔(boolean)值字段的可选项
default=<default value>

(补充:设置布尔(boolean)值的默认值,默认值可选项有且只有:True 和 False)

5.2.3 BooleanField() 布尔(boolean)值字段的案例
item = models.BooleanField(default=False)

(补充:这里以设置名为 item 的,且默认值为 False 的布尔(boolean)值字段为例)

内容六:Django Models 常用的外部资源字段

6.1 FileField() 文件字段

6.1.1 FileField() 文件字段的格式
<field> = models.FileField(upload_to = "<directory/file>", <option>)
6.1.2 FileField() 文件字段的必选项
upload_to='<directory/file>'
6.1.3 FileField() 文件字段的可选项
max_length = '<length size>'
6.1.4 FileField() 文件字段的使用案例
item = models.FileField(upload_to ="./file", max_length = '4096')

(补充:这里以设置名为 item 的,读取本地的 ./file 文件,大小为 4096 的 FileField() 文件字段为例)

6.2 URLField() URL 字段

6.2.1 URLField() URL 字段的格式
<field> = models.URLField(max_length=<URL size>, <option>)
6.2.2 URLField() URL 字段的可选项
1) verify_exists = True

默认值为 True,如果 URL 不存在,则会返回 404


2) max_length=<URL size>

默认值为 200

6.2.3 URLField() URL 字段的使用案例
item = models.URLField(max_length= 200)

(补充:这里以设置名为 items 的,大小的为 200 的 URLField() URL 字段为例)

6.3 ImageField() 图片字段

6.3.1 ImageField() 图片字段的格式
item = models.ImageField(upload_to = "<directory/file>", <option>)
6.3.2 ImageField() 图片字段的可选项
1) height_field = <height size>
2) width_field = <width size>
3) max_length = <image size>
6.3.3 ImageField() 图片字段的使用案例
item = models.ImageField(upload_to = "./file")

(补充:这里以设置名为 item 的,读取本地的 ./file 文件的 ImageField() 图片字段为例)

参考文献:

https://docs.djangoproject.com/en/3.2/ref/models/fields/

[步骤] SELinux 的启用 (openSUSE & SLE 版) (不建议)

软件准备:

在 SELinuxProject 的官网上下载 SELinux 策略 UseRefpolicy:

https://github.com/SELinuxProject/refpolicy/wiki/UseRefpolicy

注意:

1) 如果使用此文的方法将 openSUSE & SLE 的 SELinux 设置为 Enforcing 则系统将无法设置 IP 地址
2) 如果使用此文的方法开启了 SELinux 并且将所有的布尔(boolean)值开启,则系统将无法关机,开启所有布尔值的方法:# for i in semanage boolean -l | awk '{print $1}'; do echo $i;setsebool -P $i 1; done

正文:

步骤一:安装 SELinux 组件

# zypper in libselinux1 libsemanage1 libsepol-devel libsepol1 libselinux-devel mcstrans libselinux1-32bit policycoreutils checkpolicy libsemanage-devel setools-tcl setools-libs setools-java setools-devel setools-console selinux-tools python3-policycoreutils python3-selinux python3-semanage python3-setools restorecond

步骤二:安装 SELinux 策略

2.1 解压包含 SELinux 策略的压缩包

# tar -xvf refpolicy-2.20210203.tar.bz2

(补充:这里以解压 refpolicy-2.20210203.tar.bz2 压缩包为例)

2.2 将 SELinux 策略移动到 SELinux 配置文件的位置

# mv refpolicy /etc/selinux/

2.3 进入到和 SELinux 策略相同目录下

# cd /etc/selinux/refpolicy/

2.4 显示 SELinux 策略的安装手册

# cat INSTALL

2.5 创建 SELinux 策略的配置文件

# make conf

2.6 创建 SELinux 策略

# make policy

2.7 编译 SELinux 策略

# make install

2.8 安装 SELinux 策略

# make load

步骤三:配置 SELinux 配置文件

3.1 在 SELinux 配置文件中将 SELinux 设置为 Permissive 状态

# 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=permissive
# SELINUXTYPE= can take one of three values:
#     targeted - Targeted processes are protected,
#     minimum - Modification of targeted policy. Only selected processes are protected.
#     mls - Multi Level Security protection.
SELINUXTYPE=refpolicy

3.2 在系统内核中禁止使用 AppArmor 使用 SELinux 并且将 SELinux 状态设置为 Permissive

3.2.1 设置 /etc/default/grub 配置文件
# vim /etc/default/grub

在这一行里:

GRUB_CMDLINE_LINUX_DEFAULT="......"
添加以下内容:
GRUB_CMDLINE_LINUX_DEFAULT="...... security=selinux selinux=1 enforcing=0"
3.2.2 让刚刚设置的 /etc/default/grub 配置文件生效
# grub2-mkconfig -o /boot/grub2/grub.cfg

3.3 刷新系统内所有文件的标签

# restorecon -Rp /

步骤四:重启系统让 SELinux 生效

# reboot

参考文献:

https://documentation.suse.com/sles/15-SP2/html/SLES-all/cha-selinux.html

[内容] Linux SELinux 状态的设置

内容一:SELinux 的状态

1) Disabled:完全关闭 SELinux
2) Permissive:即使违反了策略也依旧可以执行,但是违反策略的记录会被记录在日志中
3) Enforcing:如果违反了策略就不能之行

内容二:永久切换 SELinux 状态

2.1 将 SELinux 永久切换至 Disabled 状态

2.1.1 修改 SELinux 配置文件
# vim /etc/selinux/config

将以下内容:

......
SELINUX=......
......

修改为:

......
SELINUX=disabled
......
2.1.2 重启系统
# reboot
2.1.3 显示 SELinux 状态
# getenforce 
Disabled

2.2 将 SELinux 永久切换至 Permissive 状态

2.2.1 修改 SELinux 配置文件
# vim /etc/selinux/config

将以下内容:

......
SELINUX=......
......

修改为:

......
SELINUX=permissive
......
2.2.2 重启系统
# reboot
2.2.3 显示 SELinux 状态
# getenforce 
Permissive

2.3 将 SELinux 永久切换至 Enforcing 状态

2.3.1 修改 SELinux 配置文件
# vim /etc/selinux/config

将以下内容:

......
SELINUX=......
......

修改为:

......
SELINUX=enforcing
......
2.3.2 重启系统
# reboot
2.3.3 显示 SELinux 状态
# getenforce 
Enforcing

内容三:临时切换 SELinux 状态

3.1 临时切换到 Permissive 状态

3.1.1 临时切换到 Permissive 状态
# setenfoce 0


注意:
1) 系统重启后失效
2) 只能从 Enforcing 状态切换到 Permissive 状态

3.1.2 显示 SELinux 状态
# getenforce 
Permissive

3.2 临时切换到 Enforcing 状态

3.2.1 临时切换到 Enforcing 状态
# setenfoce 1


注意:
1) 系统重启后失效
2) 只能从 Permissive 状态切换到 Enforcing 状态

3.2.2 显示 SELinux 状态
# getenforce 
Enforcing

[实验] Django 页码功能的实现

注意:

文中的 python 系统名、mysite 项目和 movies 应用只是站主在本次操作中随意取的名称,读者可以根据自己的喜好换成任意别的名称

正文:

步骤一:系统环境要求

1) 服务器的系统需要是 openSUSE 15.2 版本
2) 服务器要关闭防火墙
3) 服务器系统要配置好可用的软件源(最好是软件数量最多的官方版本)
4) 服务器要能够连接外网

步骤二:安装 Django

2.1 安装 Python3

[root@python ~]# zypper -n install python3

(补充:在此次操作发生时,最新的 python 版本是 3.6.12)

2.2 创建并进入 Django 项目的目录

[root@python ~]# mkdir project
[root@python ~]# cd project

2.3 将 Django 项目的目录指定为 Django 环境

[root@python project]# python3 -m venv django_env

2.4 进入 Django 环境

[root@python project]# source django_env/bin/activate
(django_env) [root@python project]# pip install django

(补充:在此次操作发生时,最新的 Django 版本是 3.2)

步骤三:创建 mysite 项目

3.1 创建 mysite 项目

(django_env) [root@python project]# django-admin startproject mysite

3.2 mysite 项目的目录

3.2.1 安装 tree 目录显示软件
(django_env) [root@python project]# zypper -n install tree
3.2.2 显示 mysite 项目的目录
(django_env) [root@python project]# cd mysite
(django_env) [root@python mysite]# tree
.
├── manage.py
└── mysite
    ├── __init__.py
    ├── asgi.py
    ├── settings.py
    ├── urls.py
    └── wsgi.py

1 directory, 5 files
3.3.3 Django 项目目录介绍

1) mysite 此 Django 项目的容器
2) manage.py 命令行工具,与 Django 项目进行交互
3) mysite/__init__.py 空文件,通知 Python 此项目是 1 个 Python 包
4) mysite/settings.py 此 Django 项目的配置文件
5) mysite/urls.py 此 Django 项目的 URL 声明和 Django 的网站“目录”
6) mysite/wsgi.py WSGI 兼容 Web 服务器的入口

步骤四:创建 users 应用

4.1 创建 users 应用

(django_env) [root@python mysite]# django-admin startapp movies

4.2 users 应用的目录

4.2.1 显示 users 应用的目录
(django_env) [root@python mysite]# tree
.
├── manage.py
├── mysite
│   ├── __init__.py
│   ├── asgi.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── movies
    ├── __init__.py
    ├── admin.py
    ├── apps.py
    ├── migrations
    │   └── __init__.py
    ├── models.py
    ├── tests.py
    └── views.py

3 directories, 13 files
4.2.2 Django 应用目录介绍

1) movies/app.py 此 Django 应用的容器
2) movies/__init__.py 空文件,通知 Python 此项目是 1 个 Python 包
3) movies/admin.py 此 Django 应用自带的后台管理相关的类
4) movies/app.py 此 Django 应用指定应用名的文件
5) movies/migrations.py 此 Django 应用通过 python 代码生成数据库表时里面会产生一些迁移文件
6) movies/models.py 可以在里面创建一些 Python 对象并通过这些对象在数据库里创建对应的表
7) movies/test.py 此 Django 应用的测试文档
8) movies/views.py 此 Django 应用的视图,接收前端数据,把数据传递给后端,响应相关页面

步骤五:实现 movies 应用的层级多链接

5.1 在 mysite 应用中添加 1 个链接并链接 movies 应用的链接

创建 mysite/movies/urls.py 并添加以下内容:

#coding=utf-8
from django.conf.urls import url, include
from users.views import register

urlpatterns = [
    url(r'^movies/', include('movies.urls')),
]

(补充:这里以设置 page 链接对应 movies 应用的链接为例)

5.2 在 mysite 应用中导入 movies 应用

在 mysite/mysite/settings.py 中添加以下内容:

......
INSTALLED_APPS = [
......
    'movies',
]
......

步骤六:实现连接 MariaDB 数据库

6.1 安装 MairaDB 数据库和客户端

(django_env) [root@python mysite]# zypper -n install mariadb mariadb-devel mariadb-server mariadb-client

6.2 安装 Django 连接 MariaDB 的模块

(django_env) [root@python mysite]# pip3 install hexdump
(django_env) [root@python mysite]# pip3 install pymysql

6.3 在 mysite 应用中添加 Django 连接 MariaDB 的模块

在 mysite/mysite/__init__.py 中添加以下内容:

......
import pymysql
pymysql.install_as_MySQLdb()

6.4 创建用于 Django 的 MairaDB 的库、表、数据和用户并插入测试数据

6.4.1 进入 MairaDB 数据库
(django_env) [root@python mysite]# mysql -h 127.0.0.1 -p
6.4.2 创建用于 Django 的库
MariaDB [(none)]> create databases movies;

(补充:这里以创建 movies 库为例)

6.4.3 创建用于 Django 的表
6.4.3.1 进入用于 Django 到库
MariaDB [(none)]> use movies;

(补充:这里以进入 moives 库为例)

6.4.3.2 创建用于 Django 的表
MariaDB [movies]> create table movies(mid INT AUTO_INCREMENT,mname VARCHAR(100) NOT NULL,mdesc TEXT,mimg VARCHAR(120) NOT NULL,mlink VARCHAR(200) NOT NULL,PRIMARY KEY( mid ),UNIQUE( mname ));
Query OK, 0 rows affected (0.058 sec)


补充:这利以创建
1) mid 是 INT 字段,且自动增加
2) mname 是 VARCHAR 字段,长度为 100,且非空
3) mdesc 是 TEXT 字段,长度为 120,且非空
4) mlink 是 VARCHAR 字段,长度为 200,且非空
5) mid 为主键
6) mname 不能重复
为例

6.4.3.3 查看刚创建的表的表结构
MariaDB [movies]> desc movies; 
+-------+--------------+------+-----+---------+----------------+
| Field | Type         | Null | Key | Default | Extra          |
+-------+--------------+------+-----+---------+----------------+
| mid   | int(11)      | NO   | PRI | NULL    | auto_increment |
| mname | varchar(100) | NO   | UNI | NULL    |                |
| mdesc | text         | YES  |     | NULL    |                |
| mimg  | varchar(120) | NO   |     | NULL    |                |
| mlink | varchar(200) | NO   |     | NULL    |                |
+-------+--------------+------+-----+---------+----------------+
5 rows in set (0.001 sec)

(补充:这里以查看 movies 表的表结构为例)

6.4.4 创建用于 Django 的数据
6.4.4.1 进入用于 Django 到库
MariaDB [(none)]> use movies;

(补充:这里以进入 moives 库为例)

6.4.4.2 创建用于 Django 的数据
MariaDB [movies]> insert into movies (mname,mdesc,mimg,mlink) VALUES("Titanic","Accidents and love story, UHD, Dolby Vision,Dolby Atmos","eternalcenter.com/titanic/image","eternalcenter.com/titanic");
Query OK, 1 row affected (0.008 sec)
MariaDB [movies]> 
MariaDB [movies]> insert into movies (mname,mdesc,mimg,mlink) VALUES("World War","Science fiction, UHD, Dolby Vision,Dolby Atmos","eternalcenter.com/world-war/image","eternalcenter.com/world-war");
Query OK, 1 row affected (0.008 sec)
MariaDB [movies]> 
MariaDB [movies]> insert into movies (mname,mdesc,mimg,mlink) VALUES("Maleficent","Magic, UHD, Dolby Vision,Dolby Atmos","eternalcenter.com/maleficent/image","eternalcenter.com/maleficent");
Query OK, 1 row affected (0.012 sec)
MariaDB [movies]> 
MariaDB [movies]> insert into movies (mname,mdesc,mimg,mlink) VALUES("Cars","Animation, UHD, Dolby Vision,Dolby Atmos","eternalcenter.com/cars/image","eternalcenter.com/cars");
Query OK, 1 row affected (0.011 sec)
MariaDB [movies]> 
MariaDB [movies]> insert into movies (mname,mdesc,mimg,mlink) VALUES("News","Animation, UHD, Dolby Vision,Dolby Atmos","eternalcenter.com/news/image","eternalcenter.com/news");
Query OK, 1 row affected (0.011 sec)

(补充:这里以符合 movies 表结构的规范,随意向 movies 插入 5 条数据为例)

6.4.4.3 查看刚刚创建的数据
MariaDB [movies]> select * from movies;
+-----+------------+---------------------------------------------------------+------------------------------------+------------------------------+
| mid | mname      | mdesc                                                   | mimg                               | mlink                        |
+-----+------------+---------------------------------------------------------+------------------------------------+------------------------------+
|   1 | Titanic    | Accidents and love story, UHD, Dolby Vision,Dolby Atmos | eternalcenter.com/titanic/image    | eternalcenter.com/titanic    |
|   3 | World War  | Science fiction, UHD, Dolby Vision,Dolby Atmos          | eternalcenter.com/world-war/image  | eternalcenter.com/world-war  |
|   4 | Maleficent | Magic, UHD, Dolby Vision,Dolby Atmos                    | eternalcenter.com/maleficent/image | eternalcenter.com/maleficent |
|   5 | Cars       | Animation, UHD, Dolby Vision,Dolby Atmos                | eternalcenter.com/cars/image       | eternalcenter.com/cars       |
|   6 | News       | Animation, UHD, Dolby Vision,Dolby Atmos                | eternalcenter.com/news/image       | eternalcenter.com/news       |
+-----+------------+---------------------------------------------------------+------------------------------------+------------------------------+
5 rows in set (0.000 sec)

(补充:这里以查看 movies 表里的所有数据为例)

6.4.5 创建用于 Django 的用户
6.4.5.1 创建用于 Django 到用户
MariaDB [(movies)]> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'password' WITH GRANT OPTION;

(补充:这里以创建 root 用户,密码是 password 为例)

6.4.5.2 刷新权限
MariaDB [(movies)]> flush privileges;

6.5 退出 MariaDB 数据库

MariaDB [(none)]> exit

6.6 重启 MariaDB 数据库

(django_env) [root@python mysite]# systemctl restart mariadb

步骤七:实现连接 MariaDB 数据库

7.1 安装 Django 连接 MariaDB 的模块

(django_env) [root@python mysite]# pip3 install hexdump
(django_env) [root@python mysite]# pip3 install pymysql

7.2 在 mysite 应用中添加 Django 连接 MariaDB 的模块

在 mysite/mysite/__init__.py 中添加以下内容:

import pymysql
pymysql.install_as_MySQLdb()

7.3 在 mysite 应用中设置连接到 MariaDB 数据库

将 mysite/mysite/settings.py 中的以下内容:

......
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
......

修改为:

......
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'movies',
        'HOST': '127.0.0.1’,
        'PORT': '3306',
        'USER': 'root',
        'PASSWORD': 'password',
    }
}
......


补充:这里以
1) 使用的库是 movies
2) 使用的服务器是 127.0.0.1
3) 使用的端口是 3306
4) 使用的用户是 root
5) 使用的密码是 password
为例

步骤八:根据数据库表结构生成 Django 数据库模型

(django_env) [root@python mysite]# python3 manage.py inspectdb>movies/models.py

步骤九:实现页码功能

9.1 在 movies 应用中添加 1 个页码功能的 HTML 模板

创建 mysite/movies/templates/movies/index.html 并添加以下内容:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        <!--avoid collapse after floating-->
        .clearfix{
                zoom:1;
        }
        .clearfix:after{
                content: "";display: block;visibility: hidden;line-height: 0;clear: both;
        }

        body,div{
            margin:0 auto;
        }

        div{
            border:1px solid gray;
            width:750px;
            text-align: center;
        }

        ul{
            list-style-type: none;
            display: inline-block;
        }


        #header li{
            float: left;
            margin-left:10px;
            font-size:16px;
            font-family: 'Microsoft elegant black';
            color: #666666;

        }
        #header li:hover{
            cursor: pointer;
            background:blue;
            color: white;
        }

        #content li{
            float: left;
            display: inline;
            margin-right:15px;
            text-align: center;
            height:225px;
            overflow: hidden;
            padding-top:10px;
            padding-bottom:5px;

        }
        #content h1{
            font-size:14px;
            margin:0;

        }

        .tip{
            display: block;
            font-size:12px;
        }

       .h1,.tip{
            width:110px;
           text-align: center;
        }
        
        #content ul{
            /*remove the inner and outer margins of UL*/
            margin:0;
            padding:0;

        }
    </style>

</head>
<body>
    <div id="header"  class="clearfix">
        <ul class="clearfix">
            <li>home page</li>
            <li>record</li>
            <li>love</li>
            <li>ethic</li>
            <li>comic</li>
            <li>science fiction</li>
            <li>history</li>
            <li>warfare</li>
            <li>short film</li>
            <li>natural</li>
        </ul>
    </div>
    <div id="content" >
        <ul class="clearfix">
            {% for movie in nowpage %}
                <li>
                    <a href="{{ movie.mlink }}"><img src="{{ movie.mimg }}"/></a>
                    <h1 class="h1">{{ movie.mname }}</h1>
                    <span class="tip">{{ movie.mdesc }}</span>
                </li>
            {% endfor %}
        </ul>
    </div>
    <div>
        <a href="/movies/?page=1">Home</a>
        <!—show home page—>

        {% if nowpage.has_previous %}
            <a href="/movies/?page={{ nowpage.previous_page_number }}">prepage</a>
        {% endif %}
        <!--show previous page when current page exists-->

        {% for tnum in pagelist %}
            {% if currentpage == tnum %}
                <a href="/movies/?page={{ tnum }}" style="font-size: 28px;color:red;">{{ tnum }}</a>&emsp;
                <!--font size and red when page number equals current page-->
            {% else %}
                <a href="/movies/?page={{ tnum }}">{{ tnum }}</a>&emsp;
            {% endif %}          
        {% endfor %}
        <!--displays the page numbers of five pages before and after the current page-->

        {% for num in items.page_range %}
            {% if currentpage == tnum %}
                <a href="/movies/?page={{ tnum }}" style="font-size: 28px;color:red;">{{ tnum }}</a>&emsp;
                <!--when the number of page numbers equals the current page, the font becomes large and red-->
            {% else %}
                <a href="/movies/?page={{ tnum }}">{{ tnum }}</a>&emsp;
            {% endif %}
        {% endfor %}
        <!--show all page numbers-->

        {% if nowpage.has_next %}
            <a href="/movies/?page={{ nowpage.next_page_number }}">nextpage</a>
        {% endif %}
        <!--display the next page when it exists-->

        <a href="/movies/?page={{ items.num_pages }}">Last</a>
        <!—show end page—>
    </div>
</body>
</html>


补充:这里主要以
1) 生成 1 个展示每条数据的 mlink 字段、mimg 字段、mname 字段 和 mdesc 字段的表格,且每条数据就是 1 个表格
2) 显示首页和尾页并为其设置对应的链接
3) 在当前页的前提下,如果有前 1 页或后 1 页,则显示出来并为其设置对应的链接
4) 显示当前页前后 5 页页码并为其设置对应的链接
5) 显示全部页码并为其设置对应的链接
为例

9.2 在 movies 应用中添加一个网页返回值的模块并实现所需功能

在 mysite/movies/views.py 中添加以下内容:

......
from .models import Movies
from django.core.paginator import Paginator,PageNotAnInteger,EmptyPage
import math
......

def movies(request):

    page = request.GET.get('page',1)

    page = int(page)
    #Convert page to an integer

    movies = Movies.objects.all()
    #Read all data

    items = Paginator(movies,3)
    #Creating a pager object
 
    try:
        nowpage = items.page(page)
        #Get current page number
    except PageNotAnInteger:
        nowpage = items.page(1)
        #When page is not a numeric value, the data of the first page is returned
    except EmptyPage:
        nowpage = items.page(items.num_pages)
        #Returns the data of the last page when the number of pages corresponding to the page value does not exist

    beginpage = (page-int(math.ceil(10.0/2)))
    if beginpage < 1:
        beginpage = 1
    #Let beginpage be equal to the current page. When beginpage is less than 5, it is equal to 1

    endpage = beginpage + 9
    if endpage > items.num_pages:
        endpage = items.num_pages
    #When endpage is equal to beginpage plus 9, if endpage is greater than the maximum number of pages, it is equal to the maximum number of pages

    if endpage <= 10:
        beginpage = 1
    else:
        beginpage = endpage - 9
    #Let begingpage equal to endpage minus 9

    pagelist = range(beginpage,endpage+1)
    #Pagelist is from beginpage to endpage to array. The result of range (1,3) is [1,2] instead of [1,2,3]

    return render(request,'movies/index.html',{'items':items,'nowpage':nowpage,'pagelist':pagelist,'currentpage':page})


补充:这里主要以:
1) 设置 movies 模块并返回 movies/index.html
2) 从 movies/index.html 中获取 page 值,且当 page 值不存在时,其默认值为 1,并将其强行转换成整数
3) 这里的 movies = Movies.objects.all() 是指将 Movies 模块对应数据库里的所有数据导入给 movies 变量
4) 调用 Paginator 模块将 movies 变量生成每页为 3 条数据的分页的 items 对象,并将当前页数据赋予给 nowpage 变量
5) 调用 PageNotAnInteger 模块当页码不是 1 个数值时返回页码是 1 的数据
6) 调用 EmptyPage 模块当页码不存在时返回最后 1 页的数据
7) 利用逻辑将 pagelist 变量设置成当前页前后 5 页的页码
8) 给予 movies/index.html items、nowpage、pagelist 和 currentage 变量,同时将对应的值赋予给它们
为例

9.3 在 movies 应用中添加一个链接并设置对应的模块

创建 mysite/movies/urls.py 并添加以下内容:

#coding=utf-8
from django.conf.urls import url
from movies.views import movies

urlpatterns = [
    url(r'^$', movies),
]

(补充:这里以设置空链接链接对应 movies 模块为例)

步骤十:启动 Django 服务

(django_env) [root@python mysite]# python3 manage.py runserver

步骤十一:测试页码功能

1) 打开浏览器输入以下网址:

http://127.0.0.1:8000/movies/

2) 可以看到对应的展示模版有 3 条数据
3) 可以看到首页和尾页的链接
4) 可以看到前 1 页和后 1 页的链接(如果有的话)
5) 可以看到当前页前后 5 页的链接(如果有的话)
6) 可以看到所有页的链接