天天看點

實作伺服器資料采集腳本技術點總結

    上周對伺服器資料采集腳本進行了優化和改進,在做的過程中遇到了一些問題,學到了一些知識點,現在總結出來,以供後續學習參考,歡迎大家批評指正,共同學習進步!

一、從别的目錄導入子產品的兩種方式

    方式一、  

    sys.path.append(“想要導入的檔案的存放目錄”)
    import 子產品名      

    方式二、

        在檔案夾建立一個空檔案__init__.py檔案,使檔案夾變為一個包;然後使用os子產品調整此檔案所在的路徑,使其在所要通路的包的上一級目錄

    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    sys.path.append(BASE_DIR)      

                然後就可以導入所想要導入的子產品了

二、python操作mysql資料庫

  import MySQLdb      

    1、對資料庫執行增、删、改操作    

    def exec_curr(sql):
        try:
        #打開資料庫連接配接
      cnn=MySQLdb.connect(host=host,port=port,user=db_user,passwd=db_passwd,charset='utf8',db=db)
      #使用cursor()方法擷取操作遊标
      cur=cnn.cursor()
      #使用execute方法執行SQL語句
      cur.execute(sql)
      cnn.commit()
    except MySQLdb.Error,e:
      print e      

    2、對資料庫執行查詢操作

    def connet_curr(host=host,port=port,db=db,db_user=db_user,db_passwd=db_passwd,sql="select ip from nosql_ip"):
        result=[]
    try:
        cnn=MySQLdb.connect(host=host,port=port,user=db_user,passwd=db_passwd,charset='utf8',db=db)
        cur = cnn.cursor()
        cur.execute(sql)
        #擷取所有記錄清單
        rows=cur.fetchall()
        for row in rows:
            result.append(row)
        return result
    except MySQLdb.Error,e:
        print e      

三、python的序列化和反序列化

    在做資料采集的時候,用到了公司其他部門同僚做好的api,從api取到的資料為字元串格式,需要通過loads轉換一下,成為字典格式以友善操作(當然,這裡不轉化為字典的話,可以使用操作字元串的方式進行操作,但使用字典方式更加友善和準确)

    1、可以使用pickle子產品

    pickle.dumps(dic)
    pickle.loads(byte_data)      

    2、可以使用json子產品(我這裡用到的是json)

    str = json.dumps(dic)
    dic_obj = json.loads(dic_str)      
實作伺服器資料采集腳本技術點總結

四、操作字典的方式方法(字典是無序的,字典的key必須唯一)

  假設字典為 info = {'staff1': "小明",'staff2': "小紅",'staff3': "小李"}
    1、增加操作
        info['staff4'] = “小劉”
    2、修改操作
        info['staff3'] = "小樊"
    3、删除操作
          1)info.pop("staff1")
      2)del info['staff3']
    4、查詢操作
      1)"staff2" in info
      2)info.get("staff2")  如果一個key不存在,隻傳回None
      3)info["staff2"]   如果一個key不存在,就報錯
    5、嵌套字典的查詢隻需要 :字典名[ ][ ] . . .
    6、循環字典
     1)for key in info:
          print(key,info[key])
     2)for k,v in info.items(): #會先把dict轉成list
         print(k,v)      

五、通過ssh連接配接到其他伺服器執行指令的方法

    def    ssh_execute_shell(host,command):                                  
      ssh_shell = ( '''/usr/bin/ssh -n -i 跳闆機的私鑰位址 -p 26387 -o '''
              '''StrictHostKeyChecking=no -o ConnectTimeout=2 root@'%s' '''
              ''' "%s" ''' % (host, command))
        p=subprocess.Popen(ssh_shell,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
        out = p.communicate()
        return out      

六、python的多程序

    1、多程序使用子產品

    from multiprocessing import Process
  import time
  def f(name):
      time.sleep(2)
    print('hello', name)
  if __name__ == '__main__':
      p = Process(target=f, args=('process1',))
    p.start()
    p.join()      

    2、由于程序間記憶體不共享,程序間共享資料的方式有以下幾種

        Queues(消息隊列)

        Pipes(管道)

        Managers

    3、程序池

    from multiprocessing import Process,Pool
  import time
  def Foo(i):
      time.sleep(2)
      return i+100
  pool = Pool(5)
  for i in range(10):
      pool.apply_async(func=Foo, args=(i,))
      #pool.apply(func=Foo, args=(i,))
  pool.close()
  pool.join()#程序池中程序執行完畢後再關閉,如果注釋,那麼程式直接關閉。      

七、使用python發郵件

    import smtplib
  from email.MIMEText import MIMEText
  mailto_list = ["收件人使用者名@staff.sina.com.cn"]
  mail_host = "mail.staff.sina.com.cn"
  mail_user = "發件人使用者名"
  mail_pass = "發件人郵箱密碼"
  mail_postfix = "staff.sina.com.cn"
  def send_mail(to_list, sub, content):
    me = "hello" + "<" + mail_user + "@" + mail_postfix + ">"
    msg = MIMEText(content, _subtype='html', _charset='UTF-8')
    msg['Subject'] = sub
    msg['From'] = me
    msg['To'] = ";".join(to_list)
    try:
      s = smtplib.SMTP()
      s.connect(mail_host)
      s.login(mail_user, mail_pass)
      s.sendmail(me, to_list, msg.as_string())
      s.close()
      return True
    except Exception as e:
      print str(e)
      return False