Regular backup profiles for Python Combat series (05)

Source: Internet
Author: User
Tags python script rsync

    1. Background requirements

      The office area uses DHCP to dynamically assign IP addresses, solves the problem of Office users, mobile User (WiFi) address assignment, because of configuration changes, in order to ensure that the configuration file is correct, to prevent the failure to achieve rapid recovery, a backup file is written in a Python script. The way to do this is to keep one months of data locally and upload the backup file to another machine for disaster recovery purposes, which can be performed regularly once a day through crontab.


    2. Program content

Cat /usr/local/sbin/backup_dhcp.py  #!/usr/bin/python#_*_ coding:utf8 _*_#author: happy# Purpose: Backup DHCP configuration file/etc/dhcp/dhcpd.conf# from Happy Lab, happy Learning, together progress import osimport sysimport  Timeimport os.pathimport shutilclass backup (object):          "         configuration file for backing up DHCP           "        dhcp_conf = "/etc/dhcp/dhcpd.conf "         backup_dir =  "/etc/dhcp/backup"          date = time.strftime ('%y-%m-%d ', Time.localtime ())                  def check_path (self):                  '                   checking DHCP configuration files and backup paths                   '                  if not os.path.exists (self.dhcp_conf):                          print  "Dhcpd configuration %s is not exsits"  %  ( self.dhcp_conf)                          return False                  if not os.path.isdir (Self.backup_ DIR):                        &nbSp;os.makedirs (Self.backup_dir)                  return True                         def get_backup_filename (self):                  '                   Get DHCP backup name, similar to:/etc Format of/dhcp/backup/dhcpd-2016-01-01                   '                  if self.check_path ():                         conf =  os.path.split ( self.dhcp_conf) [ -1]                         backup_filename = os.path.join (Self.backup_dir, "%s_%s"  %  (conf, self.date))                          shutil.copyfile (Self.dhcp_conf,backup_filename)                  return backup_ filename                         def upload_backup_filename (self):                  '                   upload the backup file to a remote server, which is implemented via Rsync and is configured in advance with Rsync services                   '                  cmd =  "Rsync -av %s rsync://[email  protected]/upload/dhcp_bak "  %  (Self.get_backup_filename ())                  return os.system (CMD)          def delete_exipre_filename (self):                  '                   Delete expired files with a retention period of one months, where you call the find implementation in the shell directly                   '                  cmd =  ' Find %s -type  f -a -ctime +31 -a -name  "dhcpd.conf*"  | xargs rm -f {} '   %  ( Self.backup_dir)                  return os.system (CMD)                  if __name__ ==  "__main__":         bak  = backup ()         bak.upload_backup_filename ()           bak.delete_exipre_filename ()

3. Regular implementation

Periodic automatic execution through periodic scheduled task crontab, backup by nature can set different backup strategy, such as hourly backup, daily backup, weekly backup, or monthly backup, according to different circumstances, take different backup cycle, write crontab implementation, Examples of daily backups are as follows:

chmod u+x/usr/local/sbin/backup_dhcp.py [[Email protected]_dhcp_gzyc backup]# CRONTAB-E01 01 * * (python/usr/local/sbin/backup_dhcp.py)


4. Summary

Backup is an important part of daily operations, such as database backup, configuration file backup, archive data backup, etc., through the backup strategy, can be in the data failure, take a quick rollback, restore, to a certain extent reduce the loss of data, to ensure the normal operation of the application. The example above provides a backup of the data by backing up a single file, which can be transformed into a generic backup, such as a backup file path, a backup storage path, a remote saved address, and so on.


5. Time Module Learning

In Python, time-related processing is implemented through the temporal module, which summarizes the methods that are commonly used.

    1. Gets the timestamp of the current time

>>> import time>>> time.time () 1452581489.4855039

2. Get the current date

>>> time.ctime () ' Tue Jan 12 14:52:29 2016 '

3. Get eight tuples of time

>>> Time.localtime (Time.struct_time) (tm_year=2016, Tm_mon=1, tm_mday=12, tm_hour=14, tm_min=53, tm_sec=11, Tm_wday=1, tm_yday=12, tm_isdst=0)

4. Convert a timestamp to a date format

>>> time.strftime ("%y-%m-%d", Time.localtime (Time.time ())) ' 2016-01-12 ' >>> time.strftime ("%y-%m- %d%h:%m:%s ", Time.localtime (Time.time ())) ' 2016-01-12 14:55:13 '

5. Convert the time date to eight tuples

>>> time.strptime ("2011-09-28 10:00:00", "%y-%m-%d%h:%m:%s") time.struct_time (tm_year=2011, tm_mon=9, tm_ Mday=28, tm_hour=10, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=271, Tm_isdst=-1)

6. Convert a time date to a timestamp

>>> Time.mktime (Time.strptime ("2011-09-28 10:00:00", "%y-%m-%d%h:%m:%s")) 1317175200.0>>> Time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime (1317175200.0)) ' 2011-09-28 10:00:00 '


This article is from the "Happy Lab" blog, so be sure to keep this source http://happylab.blog.51cto.com/1730296/1734130

Regular backup profiles for Python Combat series (05)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.