通過pymongo實現python對mongodb的操作。
具體看python**
#!/usr/bin/python
#coding=utf-8
#python實現對mongodb的操作
#需要安裝python2、pymongo、安裝pymongo可能需要pip,logging列印日誌
#改指令碼主要功能就是每5秒改一次mongodb中儲存的ip,5秒後再改回來
import
pymongo
import
logging
import
datetime
import
osimport
time
import
traceback
import
sys,gc
#初始化logging
logging.basicconfig(level=logging.notset,
format='
%(asctime)s %(filename)s[line:%(lineno)d] [%(levelname)s] %(message)s',
datefmt='
%y-%m-%d %h:%m:%s',
filename='
clear_screenshot_based_on_db.log',
filemode='a'
)#set to print log to console at the same time
console =logging.streamhandler()
console.setlevel(logging.notset)
formatter = logging.formatter('
%(asctime)s %(name)s [%(levelname)s] %(message)s')
console.setformatter(formatter)
logging.getlogger(
'').addhandler(console)
class
mongodb_util():
#寫乙個類,用於例項化pymongo物件以及對mongo的增刪改查
def__init__(self, user, password, host, port, database, max_pool_size=2):
try:
client = pymongo.mongoclient(host=host, port=port, maxpoolsize=max_pool_size)
#例項化物件,需要mongo的相關引數
if client ==none:
logging.error(
"mongodb_util.__init__ : initialize mongodb client object error,host:%s port:%s
" %(
host, port))
raise exception("
initialize mongodb client object error")
try:
admin_db = client['
admin
'] #
指定連線的庫
admin_db.authenticate(user, password) #
身份驗證
self.persist_db = admin_db #
賦值屬性,通過該屬性執行其他操作
except
exception as exp:
logging.error(
"mongodb_util.__init__ : authtication failed,host:%s port:%s database:%s user:%s password:%s
" %(host, port, database, user, password))
raise
exp
except
exception as exp:
logging.error(
"mongodb_util.__init__ : exception has occured : %s
" % str(sys.exc_info()[1]))
raise
exp
defupdate(self):
#update方法,對mongodb執行update操作
tom =none
try:
if self.persist_db ==none:
logging.error(
'mongodb_util.delete : persist object has not been initialised')
raise exception('
persist object has not been initialised')
collection = self.persist_db['
fuzzing_agent.configuration
'] #
鏈結fuzzing_agent.configuration表
abc=collection.find() #
執行find命令
for i in
abc:
tom = i["
default_value"]
if tom == "
10.10.1.179":
#判斷該值是否為179,如果是則通過update改為134
collection.update(,
})collection.update(,
})logging.debug(
"179 > 134")
time.sleep(5)
else
: collection.update(,
})collection.update(,
})logging.debug(
"134 > 179")
time.sleep(5)
return
except
exception as exp:
logging.error(
'mongodb_util.delete : exception has occured :
' + str(sys.exc_info()[1]))
raise
expdef
change_ip(mongodb_host) :
result =false
try:
mongo_util = mongodb_util('
username
', '
password
', mongodb_host, 27017, '
admin
',max_pool_size = 2) #使用者名稱,密碼,mongodb的ip,埠,連線庫,連線池
mongo_util.update()
result =true
except
: logging.error(
'change_ip: exception has occured :
' +traceback.format_exc())
finally
:
return
result
if__name__ == '
__main__':
while
true :
try:
if change_ip(mongodb_host = '
127.0.0.1
') :
#mongodb的ip位址
logging.debug(
'update is done !!!')
else
: logging.error(
'not update done')
except
: logging.error(
'main : exception has occured :
' +traceback.format_exc())
finally
: logging.debug(
"one loop %s
" %datetime.datetime.now())
pymongo的使用總結
本地執行ez setup.py檔案,然後在環境變數path下加入可執行easy install的指令碼路徑.python安裝pymongo,easy install pymongo 我安裝的版本pymongo是3.0的,所以有些語法和網上找到的不太一樣,需要自己除錯 coding utf 8 imp...
pymongo的基本使用
pymongo可以直接使用pip來安裝pip install pymongo 基本使用也很簡單 import pymongo client pymongo.mongoclient mongodb user password address 27017 資料庫名稱 帶密碼登入 db client.資料...
pymongo的簡單使用
防止鏈結重複做的乙個cache defgen mongo connection conn name global mongo conns if conn name in mongo conns return mongo conns conn name conn mongoclient mongos ...