rpm、yum、sed总结及shell脚本练习

1、每12小时备份并压缩/etc/目录至/backup目录中,保存文件名称格式为,"etc-年-月-日-时-分.tar.gz"

0 */12 * * * /usr/bin/tar -jcP -f /backups/etc-$(date +\%F-\%H).tar.xz /etc

2、rpm包管理功能总结以及实例应用演示。

程序包管理器
源代码 --> 目标二进制格式 --> 组织成为一个或有限几个"包"文件;
安装、升级、卸载、查询、校验

功能:将编译好的应用程序的各组成文件打包成一个或几个程序包文件,从而更方便地实现程序包的安装、升级、卸载和查询等管理操作;

CentOS系统上rpm命令管理程序包
安装、升级、卸载、查询、和校验、数据库维护

rpm命令:rpm [OPTIONS] [PACKAGE_FILE]
安装:-i, --install
升级:-U, --update, -F, --feshen
卸载:-e, --erase
查询:-q, --query
校验:-V, --verify
数据库维护:--builddb, --initdb

安装
rpm {-i|--install} [install-options] PACKAGE_FILE ...

rpm -ivh PACKAGE_FILE ...

GENERAL OPTIONS
-v:verbose,详细信息
-vv:更详细的输出

[install-options]:
-h:hash marks输出进度条;每个#表示2%的进度;
--test:测试安装,检查并报告依赖关系及冲突消息等;
--nodeps:忽略依赖关系;不建议;

注意:rpm可以自带脚本;
四类: --noscripts
preinstall:安装过程开始之前运行的脚本,%pre,--nopre
postinstall:安装过程完成之后运行的脚本,%post, --nopost
preuninstall:卸载过程真正开始执行之前运行的脚本,%preun, --preun
postuninstall:卸载过程完成之后运行的脚本,%postun, --nopostun

--nosignature: 不检查包前面信息,不检查来源合法性;
--nodigest: 不检查包完整信息;

实例:

[root@CentOS7 Packages]# rpm -ivh zsh-5.0.2-31.el7.x86_64.rpm 
Preparing...                          ################################# [100%]
Updating / installing...
   1:zsh-5.0.2-31.el7                 ################################# [100%]

升级
rpm {-U|--upgrade} [install-options] PACKAGE_FILE ...
rpm {-F|--freshen} [install-options] PACKAGE_FILE ...
-U:升级或安装;
-F:升级

rpm -Uvh PACKAGE_FILE ...
rpm -Fvh PACKAGE_FILE ...

--oldpackage:降级;
--force:强制升级;

注意:(1)不要对内核做升级操作;Linux支持多内核版本并存,因此,直接安装新版本内核;
(2)如果某原程序包的配置文件安装后曾被修改过,升级时,新版本的程序提供的同一个配置文件不会覆盖原有版本的配置文件,而是吧新版本的配置文件名重命名为(FILENAME.rpmnew)后提供;

[root@CentOS7 Packages]# rpm -Uvh zsh-5.0.2-31.el7.x86_64.rpm 
Preparing...                          ################################# [100%]
Updating / installing...
   1:zsh-5.0.2-31.el7                 ################################# [100%]

卸载
rpm {-e|--erase} [--allmatches] [--justdb] [--nodeps] [--noscripts][--notriggers] [--test] PACKAGE_NAME ...

--allmatches:卸载所有匹配的指定名称的程序包的各版本;
--nodeps:忽略依赖关系
--test:测试卸载,dry run模式

[root@CentOS7 Packages]# rpm -e zsh

查询
rpm {-q|--query} [select-options] [query-options]

[select-options]
PACKAGE_NAME:查询指定的程序包是否已经安装,及其版本;
-a, --all:查询所有已经安装过的包;
-f FILE: 查询指定的文件由那个程序包生成;

-p, --package PACKAGE_FILE:用于实现对未安装的程序包执行查询操作;

--whatprovides CAPABILITY:查询指定的CAPABILITY由哪个程序包提供;
--whatrequires CAPABILITY:查询指定的CAPABILITY被哪个包依赖;

[query-options]
--changelog:查询rpm包的changelog;
-l, --list:程序安装生成的所有文件列表;
-i, --info:程序包相关的信息,版本号、大小、所属的包组,等;
-c, --configfiles:查询指定的程序包提供的配置文件;
-d, --docfiles:查询指定的程序包提供的文档;
--provides:列出指定的程序包提供的所有的CAPABILITY
-R,--requires:查询指定的程序包的依赖关系;
--scripts:查看程序包自带的脚本片段;

用法:
-qi PACKAGE, -qf FILE, -qc PACKAGE, -ql PACKAGE, -qd PACKAGE
-qpi PACKAGE_FILE, -qpl PACKAGE_FILE, -qpc PACKAGE_FILE, ...

[root@CentOS7 Packages]# rpm -qpi zsh-5.0.2-31.el7.x86_64.rpm 
Name        : zsh
Version     : 5.0.2
Release     : 31.el7
Architecture: x86_64
Install Date: (not installed)
Group       : System Environment/Shells
Size        : 5854390
License     : MIT
Signature   : RSA/SHA256, Mon 12 Nov 2018 10:49:55 PM CST, Key ID 24c6a8a7f4a80eb5
Source RPM  : zsh-5.0.2-31.el7.src.rpm
Build Date  : Wed 31 Oct 2018 12:48:17 AM CST
Build Host  : x86-01.bsys.centos.org
Relocations : (not relocatable)
Packager    : CentOS BuildSystem 
Vendor      : CentOS
URL         : http://zsh.sourceforge.net/
Summary     : Powerful interactive shell
Description :
The zsh shell is a command interpreter usable as an interactive login
shell and as a shell script command processor.  Zsh resembles the ksh
shell (the Korn shell), but includes many enhancements.  Zsh supports
command line editing, built-in spelling correction, programmable
command completion, shell functions (with autoloading), a history
mechanism, and more.
[root@CentOS7 Packages]# rpm -qi zsh-5.0.2-31.el7.x86_64.rpm 
package zsh-5.0.2-31.el7.x86_64.rpm is not installed

校验
rpm {-V|--verify} [select-options] [verify-options]

S file Size differs
M Mode differs (includes permissions and file type)
5 digest (formerly MD5 sum) differs
D Device major/minor number mismatch
L readLink(2) path mismatch
U User ownership differs
G Group ownership differs
T mTime differs
P caPabilities differ

包来源合法性验证和完整性验证:
来源合法性验证:
完整性验证:

获取并导入信任的包制作者的秘钥:
对于CentOS发行版来说:rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7

验证
(1)安装此组织签名的程序时,会自动执行验证;
(2)手动验证:rpm -K PACKAGE_FILE

数据库重建
rpm管理器数据库路径:/var/lib/rpm/
查询操作:通过此处的数据库进行;

获取帮助
CentOS 6: man rpm
CentOS 7:man rpmdb

rpm {--initdb|--rebuilddb} [-v] [--dbpath DIRECTORY] [--root DIRECTORY]
--initdb:初始化数据库,当前无任何数据库可实现初始化创建一个新的;当前有时不执行任何操作;
--rebuilddb:重新构建,通过读取当前系统上所有已经安装过的程序包进行重新创建;

3、yum的配置和使用总结以及yum私有仓库的创建。

YUM:yellow dog, Yellow Update Modifier

yum repository: yum repo
存储了众多rpm包,以及包的相关的元数据文件(放置于特点目录下:repodata)

yum客户端

配置文件
/etc/yum.conf: 为所有仓库提供公共配置
/etc/yum.repos.d/*.repo: 为仓库指向提供配置

仓库的定义
[repositoryID]
name=Some name for this repository
baseurl=url://path/to/repository/
enabled={1|0}
gpgcheck={1|0}
gpgkey=URL
enablegroups={1|0}
fileovermethod={roundrobin|priority}
默认为:roundrobin, 意为随机挑选;
cost=
默认为1000
yum命令的用法:
yum [options] [command] [package ...]
command is one of:

  • install package1 [package2] [...]
  • update [package1] [package2] [...]
  • update-to [package1] [package2] [...]
  • update-minimal [package1] [package2] [...]
  • check-update
  • upgrade [package1] [package2] [...]
  • upgrade-to [package1] [package2] [...]
  • distribution-synchronization [package1] [package2] [...]
  • remove | erase package1 [package2] [...]
  • autoremove [package1] [...]
  • list [...]
  • info [...]
  • provides | whatprovides feature1 [feature2] [...]
  • clean [ packages | metadata | expire-cache | rpmdb | plugins | all ]
  • makecache [fast]
  • groups [...]
  • search string1 [string2] [...]
  • shell [filename]
  • resolvedep dep1 [dep2] [...]
    (maintained for legacy reasons only - use repoquery or yum provides)
  • localinstall rpmfile1 [rpmfile2] [...]
    (maintained for legacy reasons only - use install)
  • localupdate rpmfile1 [rpmfile2] [...]
    (maintained for legacy reasons only - use update)
  • reinstall package1 [package2] [...]
  • downgrade package1 [package2] [...]
  • deplist package1 [package2] [...]
  • repolist [all|enabled|disabled]
  • repoinfo [all|enabled|disabled]
  • repository-packages [package2] [...]
  • version [ all | installed | available | group-* | nogroups* | grouplist | groupinfo ]
  • history [info|list|packages-list|packages-info|summary|addon-info|redo|undo|rollback|new|sync|stats]
  • load-transaction [txfile]
  • updateinfo [summary | list | info | remove-pkgs-ts | exclude-updates | exclude-all | check-running-kernel]
  • fssnapshot [summary | list | have-space | create | delete]
  • fs [filters | refilter | refilter-cleanup | du]
  • check
  • help [command]

显示仓库列表
repolist [all|enabled|disabled]

显示程序包
list
# yum list [all | glob_exp1] [glob_exp2] [...]
# yum list {available|installed|updates} [glob_exp1] [...]

安装程序包
install package1 [package2] [...]
reinstall package1 [package2] ...

升级程序包:
update [package1] [package2] [...]
downgrade package1 [package2] [...] (降级)

检查可用升级
check-update

卸载程序包
remove | erase package1 [package2] [...]

查看程序包information:
info [...]

查看指定的特性(可以是某文件)是由哪个程序包所提供
provides | whatprovides feature1 [feature2] [...]

清理本地缓存
clean [packages | metadata | expire-cache | rpmdb |plugins | all]

构建缓存
makecache

搜索
search string1 [string2] [...]
以指定的关键字搜索程序包名及summary信息;

查看指定包所依赖的capabilities:
deplist package1 [package2] [...]

查看yum事务历史

  • history [info|list|packages-list|packages-info|summary|addon-info|redo|undo|rollback|new|sync|stats]

安装及升级本地程序包

  • localinstall rpmfile1 [rpmfile2] [...]
    (maintained for legacy reasons only - use install)
  • localupdate rpmfile1 [rpmfile2] [...]
    (maintained for legacy reasons only - use update)

包组管理相关命令

  • groups [...]

如何使用光盘当做本地yum仓库
(1)挂载光盘至某目录,例如/media/cdrom
# mount -r -t iso9660 /dev/cdrom /media/cdrom

(2)创建配置文件
[CentOS7]
name=
baseurl=
gpgcheck=
enabled=

[base]
name=CentOS 7Release 7.6.1810
baseurl=file:///media/cdrom
enabled=1
gpgcheck=0
yum的命令行选项:
--nogpgcheck: 禁止进行gpg check;
-y: 自动回答为“yes”;
-q: 静默模式;
--disablerepo=repoidglob: 临时禁用此处指定的repo;
--enablerepo=repoidglob: 临时启用此处指定的repo;
--noplugins: 禁用所有插件;

yum的repo配置文件中可用的变量:
$releasever: 当前OS的发行版的主版本号;
$arch: 平台;
$basearch: 基础平台;
$YUM0-$YUM9

http://mirrors.magedu.com/centos/$releasever/$basearch/os

创建yum仓库:
createrepo [options]

4、写一个脚本实现列出以下菜单给用户:

(1)disk:show disk info信息
(2)mem: show memory info信息
(3)cpu: show cpu info信息
(*)quit

cat << EOF
disk) show disks info
mem) show memory info
cpu) show cpu info
*) QUIT
EOF
 
read -p "Your choice: " option
 
if [[ "$option" == "disk" ]]; then
    fdisk -l /dev/[sh]d[a-z]
elif [[ "$option" == "mem" ]]; then
    free -m
elif [[ "$option" == "cpu" ]]; then
    lscpu
else
    echo "Unkown option."
    exit 3
fi

5、sed用法总结并结合实例演示

sed命令
sed: Stream Editor,流编辑器。

使用方法
sed [OPTION]... 'script' [input-file]...

常用选项
-n:不输出模式空间中的内容至屏幕;
-e script:--expression=script:多点编辑;(sed -e 's@^#[[:space:]]*@@' -e '/^UUID/d' /etc/fstab)
-f /PATH/TO/SED_SCRIPT_FILE
每行一个编辑命令;
-r, --regexp-extended: 支持使用扩展正则表达式;
-i[SUFFIX], --in-place[=SUFFIX]:直接编辑源文件;

地址定界
(1) 空地址:对全文进行处理;
(2) 单地址:
#:指定行;
/pattern/:被此模式匹配到的每一行;
(3)地址范围
#,#:
#,+#:
#,/pat1/
/pat1/,/pat2/
(4)步进:~
1~2:所有奇数行
2~2:所有偶数行
$最后一行

编辑命令
d:删除
p:显示模式空间中的内容
a \text:在行后面追加文本"text",支持使用\n实现多行追加;
i \text:在行前面插入文本"text",支持使用\n实现多行插入;
c \text:把匹配到的行替换为此处指定的文本"text";
w /PATH/TO/SOMEFILE:保存模式空间匹配到的行至指定文件中;
r /PATH/FROM/SOMEFILE:读取指定文件的内容至当前文件被模式匹配到的行处;文件合并;
=:为模式匹配到的行打印行号;
i:条件区反;
地址定界!编辑命令;
s///:查找替换,其分隔符可自行指定,常用的有s@@@,s###等;
替换标记:
g:全局替换;
w:/PATH/TO/SOMEFILE:将替换成功的结果保存至指定文件中;
p:显示替换成功的行;

实例:
1:删除/boot/grub/grub2.cfg文件总所有以空白字符开头的行的行首的空白字符;
[root@www scripts]# sed 's@^[[:space:]]\+@@' /etc/grub2.cfg

2:删除/etc/fstab文件中所有以#开头的行的行首的#号及#后面的所有空白字符;
[root@www scripts]# sed 's@^#[[:space:]]*@@' /etc/fstab

3:输出一个绝对路径给sed命令,取出其目录,其行为类似于dirname
echo "/var/log/messages" | sed 's@[^/]\+/\?$@@'
echo "/var/log/messages" | sed -r 's@[^/]+/?$@@'

6、 用bash实现统计访问日志文件中状态码大于等于400的IP数量并排序

#!/bin/bash
lines=$(wc -l /tmp/log.txt | cut -d" " -f1)
let lines+=1
#echo $lines
#echo $(head -n 1 /tmp/log.txt | tail -n 1 | cut -d" " -f9 | grep -o "[0-9]\{3\}")
for line in $(seq 1 $lines); do
    code=$(head -n $line /tmp/log.txt | tail -n 1 | cut -d" " -f9 | grep -o "[0-9]\{3\}")
#   echo $code
    if [[ $code -ge 400 ]]; then
            head -n $line /tmp/log.txt | tail -n 1 | cut -d" " -f1 >> /tmp/log400.txt
    fi
done

cat /tmp/log400.txt  | sort -t $'.' -k1 -n:wq

7、 使用自制的yum源安装ftp、openssh、curl、wget、tcpdump等软件包

cp /media/cdrom/Packages/* /tmp/Packages/
[root@CentOS7 ~]# cd /tmp/
[root@CentOS7 tmp]# createrepo /tmp/
Spawning worker 0 with 1006 pkgs
Spawning worker 1 with 1005 pkgs
Spawning worker 2 with 1005 pkgs
Spawning worker 3 with 1005 pkgs
Workers Finished
Saving Primary metadata
Saving file lists metadata
Saving other metadata
Generating sqlite DBs
Sqlite DBs complete

[root@CentOS7 tmp]# vim /etc/yum.repos.d/local.repo 
    [base]
    name=CentOS 7Release 7.6.1810
    baseurl=file:///tmp/
    enabled=1
    gpgcheck=0

[root@CentOS7 yum.repos.d]# yum repolist 
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
repo id                                                  repo name                                                            status
base                                                     CentOS 7Release 7.6.1810                                             10,019
epel/7/x86_64                                            Fedora EPEL                                                          13,332
repolist: 23,351


[root@CentOS7 yum.repos.d]# yum install -y ftp openssh curl wget tcpdump
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
Package openssh-7.4p1-16.el7.x86_64 already installed and latest version
Package curl-7.29.0-51.el7.x86_64 already installed and latest version
Package matching wget-1.14-18.el7.x86_64 already installed. Checking for update.
Package 14:tcpdump-4.9.2-3.el7.x86_64 already installed and latest version
Resolving Dependencies
--> Running transaction check
---> Package ftp.x86_64 0:0.17-67.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

====================================================================================================================================
 Package                     Arch                           Version                              Repository                    Size
====================================================================================================================================
Installing:
 ftp                         x86_64                         0.17-67.el7                          base                          61 k

Transaction Summary
====================================================================================================================================
Install  1 Package

Total download size: 61 k
Installed size: 96 k
Downloading packages:
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : ftp-0.17-67.el7.x86_64                                                                                           1/1 
  Verifying  : ftp-0.17-67.el7.x86_64                                                                                           1/1 

Installed:
  ftp.x86_64 0:0.17-67.el7                                                                                                          

Complete!
[root@CentOS7 yum.repos.d]# 

你可能感兴趣的:(rpm、yum、sed总结及shell脚本练习)