import os import paramiko baseconfig = { "ip": "121.4.38.187", "port": 22, "username": "", "password": "", "localdir": "E:\javawork\moodapi\target\classes", "remotedir": "/www/wwwroot/zshapi", "startsplit": "target", "exclude": [], "include": ["Info"], "fielExt": ".class", "succExec": "", "skipDircheck": False } # 遍历所有文件夹下的文件 def walkFiles(path, endpoint=None): file_list = [] for root, dirs, files in os.walk(path): for file in files: file_path = os.path.join(root, file) if endpoint: if file_path.endswith(endpoint): file_list.append(file_path) else: file_list.append(file_path) return file_list def getRemotedir(f): if baseconfig["startsplit"] != "": p = f.split(baseconfig["startsplit"])[1].replace("\", "/") return p def checkExclude(file): filename = os.path.split(file)[1] filename = filename.lower() for regstr in baseconfig["exclude"]: if filename.__contains__(regstr.lower()): return True return False def checkInclude(file): filename = os.path.split(file)[1] filename = filename.lower() for regstr in baseconfig["include"]: if filename.__contains__(regstr.lower()): return True return False def upload(files): if len(files) == 0: return ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname=baseconfig["ip"], port=baseconfig["port"], username=baseconfig["username"], password=baseconfig["password"]) ssh.get_transport() sftp = paramiko.SFTPClient.from_transport(ssh.get_transport()) for f in files: if checkExclude(f): print("跳过:%s" % f) continue if len(baseconfig["include"]) > 0: if checkInclude(f) == False: continue p = baseconfig["remotedir"] + getRemotedir(f) if baseconfig["skipDircheck"] == False: remotedir = os.path.split(p)[0] stdin, stdout, stderr = ssh.exec_command("ls " + remotedir) if stdout.readline() == '': stdin, stdout, stderr = ssh.exec_command("mkdir -p " + remotedir) stdout.readline() print("上传:%s至%s" % (f, p)) sftp.put(f, p) if baseconfig["succExec"] != "": stdin, stdout, stderr = ssh.exec_command(baseconfig["succExec"]) stdout.readline() ssh.close() if __name__ == '__main__': files = walkFiles(baseconfig["localdir"], endpoint=baseconfig["fielExt"]) upload(files)