CentOS 7.x服务器重启后自动执行指定命令的实现方法咨询
Hey there! Let me walk you through a couple of reliable ways to get those commands running automatically right after your CentOS 7 server reboots. I’ll cover two methods—one quick and straightforward, another more robust for better control.
/etc/rc.d/rc.local (Quick & Easy) CentOS 7 still supports the classic rc.local approach for post-boot scripts, though you need to make sure it’s properly enabled first. Here’s how to set it up:
- Open the
rc.localfile in your editor of choice:vi /etc/rc.d/rc.local - Scroll to the bottom and add your three commands in order:
Note:getenforce setenforce 0 systemctl start httpd.servicegetenforcewill just output the current SELinux state, which will be logged in the rc-local service logs if you ever need to check it. - Give the file executable permissions—this is a crucial step since CentOS 7 disables this by default:
chmod +x /etc/rc.d/rc.local - Enable and start the
rc-localservice to activate the setup:systemctl enable rc-local.service systemctl start rc-local.service
If you want better control over the task, proper logging, and standard service management, a custom systemd service is the way to go. This is the modern approach recommended for CentOS 7:
- Create a new service file (we’ll name it
post-boot-tasks.service):vi /etc/systemd/system/post-boot-tasks.service - Paste the following configuration into the file:
Let me break down a few key parts:[Unit] Description=Post-boot tasks: Check SELinux state, set to permissive, start httpd After=network.target [Service] Type=oneshot ExecStart=/usr/sbin/getenforce ExecStart=/usr/sbin/setenforce 0 ExecStart=/usr/bin/systemctl start httpd.service RemainAfterExit=yes [Install] WantedBy=multi-user.targetAfter=network.target: Ensures the tasks run after the network is up, which makes sense since httpd often relies on network connectivity.Type=oneshot: Tells systemd this is a one-time task that finishes once all commands run.RemainAfterExit=yes: Keeps the service marked as "active" even after the commands complete, which helps with status checks.
- Reload systemd to recognize the new service:
systemctl daemon-reload - Enable the service so it runs on every boot:
systemctl enable post-boot-tasks.service - (Optional) Test it out manually to make sure everything works before rebooting:
You can check the logs anytime with:systemctl start post-boot-tasks.servicejournalctl -u post-boot-tasks.service
If you want to permanently disable SELinux instead of just setting it to permissive on each boot, edit /etc/selinux/config and change SELINUX=enforcing to SELINUX=disabled. Then reboot—this way you won’t need the setenforce 0 command anymore. Also, if you’ve already run systemctl enable httpd.service, the systemctl start httpd command is redundant (but harmless to include anyway).
内容的提问来源于stack exchange,提问作者Zac Ram

