2013-05-14 150 views
3

我有一個shell腳本來執行一些mongo數據庫操作:shell腳本 - 檢查mongod服務器是否正在運行

例如, mongo testdb --eval "db.dropDatabase()"

,但如果mongod的服務器沒有運行,我得到:

MongoDB shell version: 2.0.4 
connecting to: testdb 
Tue May 14 04:33:58 Error: couldn't connect to server 127.0.0.1 shell/mongo.js:84 

是否有蒙戈我可以檢查連接狀態的方法嗎?最後,我想是這樣的:

if(mongod is running): 
    mongo testdb --eval "db.dropDatabase()" 
else: 
    echo "pls make sure your mongod is running" 
    exit 1 
+0

一個簡單的方法:你可以檢查'%ERRORLEVEL%'在Windows或bash'$?'中查看mongo命令是否返回錯誤代碼。 – WiredPrairie 2013-05-14 12:33:57

+0

@WiredPrairie在bash中。 – Shengjie 2013-05-14 12:46:59

回答

12

你應該能夠創建一個bash腳本是這樣的:

mongo --eval "db.stats()" # do a simple harmless command of some sort 

RESULT=$? # returns 0 if mongo eval succeeds 

if [ $RESULT -ne 0 ]; then 
    echo "mongodb not running" 
    exit 1 
else 
    echo "mongodb running!" 
fi 
+0

如果設置bind_ip和端口 – 2013-11-26 07:34:06

+0

,此腳本失敗嗨,如何檢查mongodb是否正在運行使用shell腳本以auth模式運行並捕獲錯誤代碼。 – 2015-08-11 18:38:24

2

這是我運行檢查的mongod達:

# this script checks if the mongod is running. 
# if not, send mail 
# 

[email protected] 



`ps -A | grep -q '[m]ongod'` 

if [ "$?" -eq "0" ]; then 
    exit 0 
else 
    echo "The mongod server SB2MDB01 is DOWN" | mailx \ 
    -s "Server DOWN: SB2MDB01" $EMAILIST 
fi 

exit 0 
2

嘗試在你的shell腳本中運行這個: -

pgrep mongod

如果值是數字,你知道該進程正在運行,如果你得到一個空值,將其標記爲服務沒有運行...

相關問題