使用fabric 2.5.0 上传文件

python3.6使用fabric2.5.0。最近开发东西都是在windows里面使用vs编写,然后传送到远端服务器上做编译。为了方便及时同步代码,编写了一个脚本来处理这个事情。
处理步骤:

  1. 检查本地文件目录下,svn状态列表中被修改、添加的文件;
  2. 对比本地文件和远程文件是否md5码匹配;
  3. 通过fabric2.5.0上传到远程服务;
#!/usr/bin/python
# encoding: utf-8
# pip install svn
# pip install fabric
#
import logging
import os
import svn.local
from fabric import Connection
import hashlib

logging.basicConfig(level=logging.INFO,format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',datefmt='%a, %d %b %Y %H:%M:%S')

# 指定远程的服务器目录地址
path_remoate = "/home/cq/work/server/"

# 计算本地文件md5码
def GetFileMd5(filename):
    if not os.path.isfile(filename):
        return
    myhash = hashlib.md5()
    f = open(filename,'rb')
    while True:
        b = f.read(8096)
        if not b :
            break
        myhash.update(b)
    f.close()
    return myhash.hexdigest()


def main():
    # 链接远程服务器的配置
    c = Connection(host="10.0.20.117",
        user="cq",
        connect_kwargs={"key_filename": "E:/software/keyfile/id_rsa_abel",})
    c.open()
    logging.info(c.is_connected)
    # 测试执行执行指令
    c.run("pwd")
    # 获取本地svn文件状态
    l = svn.local.LocalClient('./')
    entries = l.status()
    for filename in entries:
        # 选择“修改”、“添加”状态的文件
        if filename.type_raw_name=='modified' or 'added' == filename.type_raw_name:
            name = filename.name
            name = name.replace("\\","/")
            logging.info("put name: {0}".format(name))
            # 通过Linux指令计算出远程的文件md5,并且赋值给retstr
            cmd = "md5sum {0}{1}".format(path_remoate,name) + "|awk '{print $1}'"
            retstr = c.run(cmd)
            # 计算本地m5,并且匹配
            selfmd5 = GetFileMd5(name)
            print(selfmd5)
            # 命令行返回的md5将会带一个\n,需要去除
            if retstr.stdout[:-1] == selfmd5:
                print("match")
            else:
                print("not match")
                # 不匹配的情况下,将会开始使用fabric的put命令上传文件
                c.put(name,"{0}{1}".format(path_remoate,name))
    c.close()

if __name__ == '__main__':
    main()
发布了76 篇原创文章 · 获赞 13 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/erlang_hell/article/details/103793634