暗黑模式
systemd
is a powerful system and service manager for Linux. It helps manage and control system services, daemons, and other system-wide tasks. Here’s a guide to get you started with using systemd
effectively:
1. Check the Status of a Service
To check the status of a service:
bash
sudo systemctl status <service-name>
1
For example:
bash
sudo systemctl status sshd
1
2. Start, Stop, Restart, and Reload Services
- Start a service:bash
sudo systemctl start <service-name>
1 - Stop a service:bash
sudo systemctl stop <service-name>
1 - Restart a service:bash
sudo systemctl restart <service-name>
1 - Reload a service configuration (if it supports reloading without restarting):bash
sudo systemctl reload <service-name>
1
3. Enable or Disable Services
- Enable a service (start it automatically on boot):bash
sudo systemctl enable <service-name>
1 - Disable a service (prevent it from starting on boot):bash
sudo systemctl disable <service-name>
1
4. Check All Active Services
To list all active services:
bash
systemctl list-units --type=service
1
To list all services (including inactive or failed):
bash
systemctl list-units --type=service --all
1
5. Create and Manage Custom Services
If you want to create your own service (e.g., to run a custom script), follow these steps:
(a) Create a Unit File
Create a custom service unit file in /etc/systemd/system/
:
bash
sudo nano /etc/systemd/system/myservice.service
1
Add the following content (replace placeholders with your details):
ini
[Unit]
Description=My Custom Service
After=network.target
[Service]
ExecStart=/path/to/your-script.sh
Restart=always
[Install]
WantedBy=multi-user.target
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
(b) Reload systemd
and Start the Service
- Reload
systemd
to recognize the new service:bashsudo systemctl daemon-reload
1 - Start the new service:bash
sudo systemctl start myservice
1 - Optionally enable it to start at boot:bash
sudo systemctl enable myservice
1
6. Check Logs
To view logs for a specific service:
bash
sudo journalctl -u <service-name>
1
For example:
bash
sudo journalctl -u sshd
1
7. Disable the Graphical Mode (Optional)
On some systems, you can switch to a non-graphical mode by changing the default systemd
target:
- Switch to multi-user (non-GUI) mode:bash
sudo systemctl set-default multi-user.target
1 - Revert to GUI mode:bash
sudo systemctl set-default graphical.target
1
Tips:
- Always reload
systemd
after editing or adding new unit files:bashsudo systemctl daemon-reload
1 - Use the
--now
option to start/stop a service immediately while enabling/disabling it persistently:bashsudo systemctl enable --now <service-name> sudo systemctl disable --now <service-name>
1
2
Let me know if you'd like a deeper dive into a specific systemd
feature!