python写linux脚本_Linux下设置python脚本文件为服务
(最簡單的方式nohup python xxx.py)
-------------------------------------------------------------------------------------------------------------------
Python腳本開機自動運行;本帖適用于使用systemd的Linux系統(tǒng),現(xiàn)在流行的Linux發(fā)行版都使用systemd。
后臺服務(wù)程序是隨系統(tǒng)自啟動的,我們只要把Python腳本配置為服務(wù)就行了。需要注意的一點是你Python腳本的啟動時機,它依賴不依賴其他服務(wù)(網(wǎng)絡(luò)連接、一些分區(qū)的掛載等等)。
#1 Python腳本
一個你要自啟動的Python腳本,我使用 /home/snail/autorun.py為例。
#2 創(chuàng)建Unit配置文件
1
$sudo vim/lib/systemd/system/autorun.service
寫入如下內(nèi)容:
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 的服務(wù),它在multi-user環(huán)境起來之后運行;ExecStart參數(shù)指定我們要運行的程序;idle確保腳本在其他東西加載完成之后運行,它的默認值是simple。
注意使用絕對路徑。
為了獲得腳本的輸出信息,我們可以重定向到文件:
1
ExecStart=/usr/bin/python/home/snail/autorun.py>/home/snail/autorun.log2>&1
更改配置文件的權(quán)限:
1
$sudo chmod644/lib/systemd/system/autorun.service
#3 使配置文件生效
1
2
$sudo systemctl daemon-reload
$sudo systemctl enable autorun.service
#4 重啟
1
$sudo reboot
#5 查看服務(wù)狀態(tài)
1
$sudo systemctl status autorun.service
#6 服務(wù)操作命令
systemctl命令是系統(tǒng)服務(wù)管理器指令,它實際上將
任務(wù)
舊指令
新指令
使某服務(wù)自動啟動
chkconfig --level 3
systemctl enable httpd.service
使某服務(wù)不自動啟動
chkconfig --level 3 httpd off
systemctl disable httpd.service
檢查服務(wù)狀態(tài)
service httpd status
systemctl status httpd.service (服務(wù)詳細信息) systemctl is-active httpd.service (僅顯示是否 Active)
顯示所有已啟動的服務(wù)
chkconfig --list
systemctl list-units --type=service
啟動某服務(wù)
service httpd start
systemctl start httpd.service
停止某服務(wù)
service httpd stop
systemctl stop httpd.service
重啟某服務(wù)
service httpd restart
systemctl restart httpd.service
實例
1.啟動nfs服務(wù)
systemctl start nfs-server.service
2.設(shè)置開機自啟動
systemctl enable nfs-server.service
3.停止開機自啟動
systemctl disable nfs-server.service
4.查看服務(wù)當(dāng)前狀態(tài)
systemctl status nfs-server.service
5.重新啟動某服務(wù)
systemctl restart nfs-server.service
6.查看所有已啟動的服務(wù)
systemctl list -units --type=service
開啟防火墻22端口
iptables -I INPUT -p tcp --dport 22 -j
如果仍然有問題,就可能是SELinux導(dǎo)致的
關(guān)閉SElinux:
修改/etc/selinux/config文件中的SELINUX=””為disabled,然后重啟。
徹底關(guān)閉防火墻:
sudo systemctl status firewalld.service
sudo systemctl stop firewalld.service
sudo systemctl disable firewalld.service
與50位技術(shù)專家面對面20年技術(shù)見證,附贈技術(shù)全景圖總結(jié)
以上是生活随笔為你收集整理的python写linux脚本_Linux下设置python脚本文件为服务的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux 查看开放的端口_如何在 Li
- 下一篇: iframe内联元素有白边原因_教你如何