Synchronizing Windows and Linux files with Python

Source: Internet
Author: User
Tags abs python script

Tag: Service disconnected name with success failure MD5 Code Direct

The purpose of writing a Python script, every time after the Windows edit the file, want to sync to Linux, only to log on to the server, and then use the network copy, the repetition is very large, think of can write a small script to help me synchronize

Logic: Compared to the local and server files MD5, if the MD5 inconsistent, then back up the files on the server, the local to upload up

The code is divided into Windows and server side, some things, let Python one do, write a little tired, think, can the server to provide a port, Windows to call this interface, to complete part of the work

The Python code is as follows:

Additional installation of the Baowei is Paramiko, installation method: Pip install Paramiko can be, code as follows, using Paramiko Sshclient to invoke the server to write its own API (hey, call it API), transport to implement the Sftp file upload,

#!/usr/bin/env pythonImportOSImportHashlibImportParamikoImport TimeImportSYSdefgetmd5 (filename): Filehash=hashlib.md5 () F= open (filename,'RB')     whiletrue:b=f.read (8096)        if  notB: BreakFilehash.update (b) f.close ()returnfilehash.hexdigest ()defsend_files (sftp,ssh,filename,abspathfile,server_dir):Try:        Print("Deleting Files", end=" ")        Print(filename) ssh.exec_command ('bash/root/put_api.sh%s Move'%filename)Print("Delete file succeeded")        Print("Start uploading Files") Server_file=server_dir +filename sftp.put (abspathfile,server_file)Print("File Upload Successful")    except:            Print("File upload failed")    defSearch_file (dir,path,ssh,server_dir):#to define a string that excludes MD endingssuffix='MD'    #Defining Loops    Print("Open SFTP") T= Paramiko. Transport (('Myhostname', 22)) T.connect (username='Root', password='MyPassword') sftp=Paramiko. Sftpclient.from_transport (t) forFileNameinchOs.listdir (path):Print(Time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime ())) Print("Start processing%s"%(filename))#If you end with MD, you continue        iffilename.endswith (suffix):Print("do not process with MD end")            Continue                #Defining absolute pathsAbspathfile=dir +'\\'+filename#get the MD5 of a fileLOCALFILEMD5=GETMD5 (Abspathfile) +'\ n'BYTE_LOCALFILEMD5=localfilemd5.encode (encoding="gb2312")        Print("%s MD5 value%s"%(FILENAME,BYTE_LOCALFILEMD5)) Serverfilemd5=get_server_md5 (ssh,filename)Print("%s Server MD5 value%s"%(FILENAME,SERVERFILEMD5))ifBYTE_LOCALFILEMD5 = =SERVERFILEMD5:Print("MD5 values are consistent and do not need to be uploaded")        Else:            Print("MD5 value inconsistent, upload file")#send_files (Sftp,ssh,filename,abspathfile,server_dir)            Try:#send_files (Ssh,filename,abspathfile,server_dir)send_files (Sftp,ssh,filename,abspathfile,server_dir)except:                Print("Upload failed ...")    Print("Close SFTP") T.close ()defget_server_md5 (ssh,filename): Stdin,stdout,stderr= Ssh.exec_command ('bash/root/put_api.sh%s'%filename) Result=Stdout.read ()returnresultdefMain (): StartTime=time.time ()Print("script starts synchronizing")    Print(Time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime ())) Try: SSH=Paramiko. Sshclient () Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) Ssh.connect (hostname='Myhostname', port=' A', username='Root', password='MyPassword')    except:        Print("Server Connection failed with exception exit") Sys.exit (-1)            #Define PathLocal_dir ='e:\\temp\\note_html'Server_dir='/root/nginx_02/'    #using functions to exclude filessearch_file (Local_dir,local_dir,ssh,server_dir)#print (get_server_md5 (SSH, ' d0180727_install_rabbitmt_png_06.png '))ssh.close () Endtime=time.time ()Print(Time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime ())) Print("server disconnected, this file updated successfully")    Print("Update Time:%.2f s"% (Endtime-starttime)) Print("more precise time:", end=" ") Usedtime= Endtime-StartTimePrint(usedtime,end=" ")    Print("s")        if __name__=="__main__": Main ()

Linux writes its own API:

#!/bin/Bash #判断参数的个数是否大于等于1if[$#-ge1]; Then#定义文件夹 Root_dir="/root/nginx_02/"Backdir="/root/.backup/"Abs_filename= $root _dir$1#判断是否有这个文件if[-F $abs _filename]; Then#利用md5sum工具获取文件的md5值 getfilemd5= ' Md5sum $abs _filename |awk '{print $}'`        Echo "$GETFILEMD 5"#判断第二个参数是否是moveif['Move'== $2]; Then#判断是否存在备份目录, none exists, then move to backup directoryif[-D $backdir]; ThenNowtime=`Date+"%f_%h:%m:%s"`                                MV$abs _filename $backdir $1_$nowtimeif[0-eq $? ]; Then                    Echo "Move Successful"                Else                    Echo "Move failed"                fi                            Else                mkdir-P $backdirfi        fi            Else#报错, there's no such file.Echo "$ No such file or directory"    fiElse#报错, parameter errorEcho "Parameter Error"fi    

The following functions are ultimately implemented:

Synchronizing Windows and Linux files with Python

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.