您好,登錄后才能下訂單哦!
這篇文章主要介紹python中如何實現rsync服務器之間文件夾同步腳本,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
About rsync
配置兩臺服務器之間3ssh-key后,可以實現自動化無需手動輸入密碼,腳本如下:
import argparse import datetime from functools import partial import multiprocessing as mp import os import paramiko as pmk import time def check_ssh(host, user, port, passwd, dest_path): ssh_client = pmk.SSHClient() ssh_client.load_system_host_keys() ssh_client.set_missing_host_key_policy(pmk.AutoAddPolicy()) try: ssh_client.connect(host, username=user, port=port, timeout=10, password=passwd) ssh_client.exec_command('mkdir ' + os.path.join(dest_path, 'data')) except BaseException as e: print 'failed to connect to host: %r: %r' % (host, e) return False else: return True def select_from_file(file_path): file_list = [] if os.path.exists(file_path): path_dir = os.listdir(file_path) for all_dir in path_dir: file_list.append(os.path.join('%s' % all_dir)) return file_list def sync_file(file_name, remote_host, remote_user, remote_port, src_path, dest_path): sync_cmd = "rsync -azrvhP --progress -e 'ssh -p " + str(remote_port) + "' --skip-compress=gz/zip/ " + \ file_name + " " + remote_user + "@" + remote_host + ":" + os.path.join(dest_path,'data') print sync_cmd os.chdir(src_path) os.system(sync_cmd) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('-w', '--workers', dest='workers', type=int, default=12) parser.add_argument('-H', '--host', dest='host', type=str, default='192.168.254.156') parser.add_argument('-u', '--user', dest='user', type=str, default='shubao') parser.add_argument('-p', '--password', dest='password', type=str, default='123456') parser.add_argument('-P', '--port', dest='port', type=int, default=22) parser.add_argument('-r', '--remotepath', dest='remotepath', type=str, default='/home/shubao/') parser.add_argument('-s', '--srcpath', dest='srcpath', type=str, default='/home/Jesse/data') args = parser.parse_args() if not check_ssh(args.host, args.user, args.port, args.password, args.remotepath): print 'SSH connect faild!' exit(-1) pool = mp.Pool(processes=args.workers) try: while True: print "New check start at %s..." % str(datetime.datetime.now()) file_list_ = select_from_file(args.srcpath) print "File_list: " print file_list_ p_work = partial(sync_file, remote_host=args.host, remote_user=args.user, remote_port=args.port, src_path=args.srcpath, dest_path=args.remotepath) pool.map(p_work, file_list_) time.sleep(10) finally: pool.terminate() pool.join()
以上是“python中如何實現rsync服務器之間文件夾同步腳本”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。