(最簡單的方式nohup python xxx.py)
-------------------------------------------------------------------------------------------------------------------
Python腳本開機自動運行;本帖適用於使用systemd的Linux系統,現在流行的Linux發行版都使用systemd。
後臺服務程序是隨系統自啓動的,我們只要把Python腳本配置爲服務就行了。需要注意的一點是你Python腳本的啓動時機,它依賴不依賴其他服務(網絡連接、一些分區的掛載等等)。
#1 Python腳本
一個你要自啓動的Python腳本,我使用 /home/snail/autorun.py爲例。
#2 創建Unit配置文件
1 | $ sudo vim /lib/systemd/system/autorun.service |
---|
寫入如下內容:
1 2 3 4 5 6 7 8 9 10 | [Unit] Description=Test Service After=multi-user.target [Service] Type=idle ExecStart=/usr/bin/python /home/snail/autorun.py [Install] WantedBy=multi-user.target |
---|
上面定義了一個叫 Test Service 的服務,它在multi-user環境起來之後運行;ExecStart參數指定我們要運行的程序;idle確保腳本在其他東西加載完成之後運行,它的默認值是simple。
注意使用絕對路徑。
爲了獲得腳本的輸出信息,我們可以重定向到文件:
1 | ExecStart=/usr/bin/python /home/snail/autorun.py > /home/snail/autorun.log 2>&1 |
---|
更改配置文件的權限:
1 | $ sudo chmod 644 /lib/systemd/system/autorun.service |
---|
#3 使配置文件生效
1 2 | $ sudo systemctl daemon-reload $ sudo systemctl enable autorun.service |
---|
#4 重啓
1 | $ sudo reboot |
---|
#5 查看服務狀態
1 | $ sudo systemctl status autorun.service |
---|
#6 服務操作命令
systemctl命令是系統服務管理器指令,它實際上將 service 和 chkconfig 這兩個命令組合到一起。
任務 | 舊指令 | 新指令 |
---|---|---|
使某服務自動啓動 | chkconfig --level 3 httpd on | systemctl enable httpd.service |
使某服務不自動啓動 | chkconfig --level 3 httpd off | systemctl disable httpd.service |
檢查服務狀態 | service httpd status | systemctl status httpd.service (服務詳細信息) systemctl is-active httpd.service (僅顯示是否 Active) |
顯示所有已啓動的服務 | chkconfig --list | systemctl list-units --type=service |
啓動某服務 | service httpd start | systemctl start httpd.service |
停止某服務 | service httpd stop | systemctl stop httpd.service |
重啓某服務 | service httpd restart | systemctl restart httpd.service |
實例
1.啓動nfs服務
systemctl start nfs-server.service
2.設置開機自啓動
systemctl enable nfs-server.service
3.停止開機自啓動
systemctl disable nfs-server.service
4.查看服務當前狀態
systemctl status nfs-server.service
5.重新啓動某服務
systemctl restart nfs-server.service
6.查看所有已啓動的服務
systemctl list -units --type=service
開啓防火牆22端口
iptables -I INPUT -p tcp --dport 22 -j accept
如果仍然有問題,就可能是SELinux導致的
關閉SElinux:
修改/etc/selinux/config
文件中的SELINUX=””
爲disabled,然後重啓。
徹底關閉防火牆:
sudo systemctl status firewalld.service sudo systemctl stop firewalld.service sudo systemctl disable firewalld.service