其他分享
首页 > 其他分享> > rpm打包快速入门教程

rpm打包快速入门教程

作者:互联网

RPM(Redhat Package Manager)是用于Redhat、CentOS、Fedora等Linux 分发版(distribution)的常见的软件包管理器。rpm工具可以用来制作源码安装包和二进制安装包。本文档提供一个示例来说明如何制作一个rpm二进制包。

1. 准备

安装打包需要的程序:yum install rpm-build rpmdevtools

2. 安装一个简单的hello.sh脚本

3. 使用rpm-build命令制作rpm二进制包

执行rpm-build -bb hello.spec生成二进制rpm包,默认情况下会在当前用户生成目录~/rpmbuild

tree rpmbuild/
rpmbuild/
├── BUILD
├── BUILDROOT
├── RPMS
│   └── x86_64
│       └── hello-2.1-1.ky10.x86_64.rpm
├── SOURCES
├── SPECS
└── SRPMS

**建议定义_topdir宏,将安装包生成到制定目录。**下面的命令生成rpm包到当前目录:

rpmbuild -bb hello.spec --define  "_topdir $PWD/rpmbuild"

4. 自定义rpm包名称

默认安装包名称定义在/usr/lib/rpm/macros文件中:

%_rpmfilename           %{_build_name_fmt}
%_build_name_fmt        %%{ARCH}/%%{NAME}-%%{VERSION}-%%{RELEASE}.%%{ARCH}.rpm

hello.spec的第一行修改%_rpmfilename宏进行自定义包名称安装

%define _rpmfilename hello.rpm

再次执行打包命令,查看rpmbuild/RPMS目录生成自定义rpm包。

tree rpmbuild/
rpmbuild/
├── BUILD
├── BUILDROOT
├── RPMS
│   └── hello.rpm
├── SOURCES
├── SPECS
└── SRPMS

5. 将rpm包中的程序添加systemd`自启动服务

生成systemd自启动服务需要编写hello.service文件,本文并不做hello.service文件格式的具体说明,只是说明打包流程。通过修改hello.spec文件就可以将hello.service添加到systemd自启动服务中:

hello.service文件如下:

[Unit]

[Install]
WantedBy=multi-user.target

[Service]
ExecStart=/usr/local/bin/hello.sh
Restart=always
RestartSec=5
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=%n

修改后的hello.spec文件如下

%define _rpmfilename hello.rpm

Name:     hello
Version:  2.1
Release:  1
Summary:  The "Hello World" script
Summary(zh_CN):  GNU "Hello World" 程序
License:  GPLv3+

%description
The "Hello World" program, done with all bells and whistles of a proper FOSS 
project, including configuration, build, internationalization, help files, etc.

%description -l zh_CN
"Hello World" 程序, 包含 FOSS 项目所需的所有部分, 包括配置, 构建, 国际化, 帮助文件等.

%install
mkdir -p %{buildroot}/usr/local/bin
install -m 755 -t %{buildroot}/usr/local/bin /root/dw/rpmTest/hello.sh

# install the systemd unit file to buildroot.
mkdir -p %{buildroot}/etc/systemd/system
install -t %{buildroot}/etc/systemd/system /root/dw/rpmTest/hello.service


%files
/usr/local/bin/hello.sh
/etc/systemd/system/hello.service

%post
systemctl enable hello.service
systemctl start hello.service

%preun
systemctl stop hello.service
systemctl disable hello.service

安装生成的rpm包,并查看hello.service服务

rpm -ivh rpmbuild/RPMS/hello.rpm

systemctl status hello
● hello.service
   Loaded: loaded (/etc/systemd/system/hello.service; enabled; vendor preset: disabled)
   Active: activating (auto-restart) since Tue 2021-10-12 15:16:37 CST; 80ms ago
  Process: 288322 ExecStart=/usr/local/bin/hello.sh (code=exited, status=0/SUCCESS)
 Main PID: 288322 (code=exited, status=0/SUCCESS)

卸载hello包,执行了停止和移除服务命令

rpm -e hello
Removed /etc/systemd/system/multi-user.target.wants/hello.service.

参考