Recently wrote a python script to replace the previous shell script, found that Python is better than the shell of the most intuitive point python structure is clear, readable (I think) do some records here
This record uses Python Script
1,SVN Backup, Package Paramiko for SFTP and SSH connection and Ssh_exec_command
2. Delete outdated files
1,SVN Backup
Preparation: Python Paramiko Install
Method 1: Install directly using PIP
Pip Install Paramiko
Method 2: Download the source code to install
Paramiko-1.15.2.tar.gz Main Documents
ecdsa-0.13.tar.gz Dependent files
pycrypto-2.6.1.tar.gz Dependent files
1.InstallECDSATarXzf ecdsa-0.13.Tar. GZ && CD ecdsa-0.13&& python setup.pyInstall2.InstallPycryptoTarXzf pycrypto-2.6.1.Tar. GZ && CD pycrypto-2.6.1&& python setup.pyInstall3.InstallParamikoTarXzf paramiko-1.15.2.Tar. GZ && CD paramiko-1.15.2&& python setup.pyInstall
View Code
Python Script
#!/usr/bin/env python#_*_coding:utf-8_*_#Author: ' Lonny '#dateTime: ' 15/11/16 '#motto: ' Good memory as bad written 'ImportdatetimeImportOSImportTarfileImportsubprocess#usvn Backup--------------------------------------------------------------classUsvn_backend (object):# ------------------------------------------------------------------ def __init__(self): Self.date_time= Datetime.datetime.now (). Strftime ('%y-%m-%d-%h') self. Root_directory="/software"self.back_directory="USVN"Self . Remote_send_dir="/install/backup/usvnback" #Packaging Files------------------------------------------------------------ defPackage (self):GlobalTarfile_namePrint "\033[32mwaiting packaging..........\033[0m"Os.chdir (self. root_directory) Tarfile_name="%s-%s.tar.gz"%(self.back_directory, self.date_time) tar= Tarfile.open (Tarfile_name,"W:gz") Tar.add (self.back_directory) tar.close ()ifos.path.exists (tarfile_name):Print "\033[32m ..... PACKAGING is successful!!! \033[32m" Else: Print "\033[32m ..... Packaging is Failed!!! \033[0m"#executes a remote command transfer file---------------------------------------------------------classsshconnection (object):"""""" # ---------------------------------------------------------------------- def __init__(Self, host, username, password, port=22): """Initialize and Setup connection"""self.sftp=None Self.sftp_open=False#Open SSH Transport streamSelf.transport =Paramiko. Transport ((host, Port)) Self.transport.connect (username=username, password=password) self.session= Self.transport.open_channel (kind='Session') # ---------------------------------------------------------------------- def_opensftpconnection (self):"""Opens An SFTP connection if not already open""" if notself.sftp_open:self.sftp=Paramiko. Sftpclient.from_transport (self.transport) Self.sftp_open=True# ---------------------------------------------------------------------- #You need to specify both file names when downloading files defGet (self, remote_path, local_path=None):"""Copies a file from the remote host to the local host. """self._opensftpconnection () self.sftp.get (Remote_path, Local_path)# ---------------------------------------------------------------------- #the transfer file is required both ends to specify the file name defPut (self, local_path, remote_path=None):"""Copies a file from the local host to the remote host"""self._opensftpconnection () self.sftp.put (Local_path, Remote_path)# ---------------------------------------------------------------------- defRun (self, command, nbytes=4096): #Run Command Out|errStdout_data =[] Stderr_data=[] Self.session.exec_command (command) whileTrue:ifSelf.session.recv_ready (): Stdout_data.append (Self.session.recv (nbytes))ifSelf.session.recv_stderr_ready (): Stderr_data.append (Self.session.recv_stderr (nbytes)) ifSelf.session.exit_status_ready (): Break Print "\033[31m*********************\033[0m" Print '\033[32mexit status is: \033[0m', Self.session.recv_exit_status ()Print "\033[31m*********************\033[0m" Print "'. Join (Stdout_data)Print "'. Join (Stderr_data)defClose (self):"""Close SFTP Connection and SSH connection""" ifself.sftp_open:self.sftp.close () Self.sftp_open=False self.transport.close () self.session.close ()if __name__=='__main__': Try: Try: ImportParamikoexceptImporterror:Print "\033[32minstalling paramiko.........\033[0m"Install_paramiko="pip Install Paramiko"Subprocess.call (Install_paramiko, Shell=True)#Run usvn Unpack--------------------------------------------------------------Unpack =usvn_backend () unpack. Package ()#Put usvnback Files to Remote ServerSend_files =sshconnection (IPAddress, user, password)#Set local_path Names,remote_path NamesLocal_path_files ="%s/%s"%(unpack. Root_directory, Tarfile_name) remote_path_files="%s/%s"%(unpack. Remote_send_dir, Tarfile_name) send_files.put (Local_path_files, Remote_path_files)#Remove TarfilesOs.chdir (unpack. root_directory) Os.remove (tarfile_name)#Remove END!!!!send_files.close ()exceptKeyboardinterrupt:Print "contorl+c+z"
View Code
2. Delete outdated files
#!/usr/bin/env python#_*_coding:utf-8_*_#Author: ' Lonny '#dateTime: ' 15/12/15 '#motto: ' Good memory as bad written 'ImportOSImportSYSImport Time#Delete file-----------------------------------------------------------------defRemove (path):"""Remove the file or directory""" ifOs.path.isdir (path):Try: Os.rmdir (path)exceptOSError:Print "Unable to remove folder:%s"%PathElse: Try: ifos.path.exists (path): Os.remove (path)exceptOSError:Print "Unable to remove file:%s"%Path#traverse the input folder, query the file number_of_days days ago, delete---------------------defCleanup (number_of_days, path):"""removes files from the passed on path that is older than or equal to the Number_of_days"""Time_in_secs= Time.time ()-(Number_of_days * 24 * 60 * 60) """calculates the millisecond difference between the current time and number_of_days days ago""" forRoot, dirs, filesinchOs.walk (Path, topdown=False): forFile_inchFiles:full_path=Os.path.join (Root, file_) stat=Os.stat (Full_path)ifStat.st_mtime <=Time_in_secs:remove (Full_path)if notOs.listdir (Root): Remove (Root)# ----------------------------------------------------------------------if __name__=="__main__": #sys.argv[1] Days sys.argv[2] The directory to traversedays, Path = Int (sys.argv[1]), sys.argv[2] Cleanup (days, path)
View Code
Python Backup Files