Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/meteor/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将文件从本地计算机同步到外部主机(sftp或ssh)的脚本_Python_Ssh_Synchronization_Sftp - Fatal编程技术网

Python 将文件从本地计算机同步到外部主机(sftp或ssh)的脚本

Python 将文件从本地计算机同步到外部主机(sftp或ssh)的脚本,python,ssh,synchronization,sftp,Python,Ssh,Synchronization,Sftp,对于我的一个项目,我需要能够用脚本将程序(HTML)的输出复制到我的服务器上,因此只需启动脚本即可完成,无需进一步处理。 上传应该只针对内容已更改的文件,因为在我的程序发布新内容后,日期总是会更改 我在网上找到了一个脚本,它可以做我想做的事情,只是做了一些小改动。现在,当我在计算机上的两个文件夹之间发布时,它可以工作,但我应该能够用sFTP或SSH连接替换我的目标 import os import filecmp import shutil ''' Version: Python 3.3.2

对于我的一个项目,我需要能够用脚本将程序(HTML)的输出复制到我的服务器上,因此只需启动脚本即可完成,无需进一步处理。 上传应该只针对内容已更改的文件,因为在我的程序发布新内容后,日期总是会更改

我在网上找到了一个脚本,它可以做我想做的事情,只是做了一些小改动。现在,当我在计算机上的两个文件夹之间发布时,它可以工作,但我应该能够用sFTP或SSH连接替换我的目标

import os
import filecmp
import shutil

'''
Version: Python 3.3.2
Using python SyncFolder in CMD
Origin: https://gist.github.com/aortbals/5096365
Modified by Louisdj_15
'''
class Dispatch:
    ''' This class represents a synchronization object '''

def __init__(self, name=''):
    self.name=name
    self.node_list=[]
    self.file_copied_count=0
    self.folder_copied_count=0
    self.file_removed_count=0
    self.folder_removed_count=0

def add_node(self, node):
    self.node_list.append(node)


def compare_nodes(self):
    ''' This method takes the nodes in the node_list and compares them '''
    nodeListLength = len(self.node_list)
    # For each node in the list
    for node in self.node_list:
        # If the list has another item after it, compare them
        if self.node_list.index(node) + 1 < len(self.node_list):
            node2 = self.node_list[self.node_list.index(node) + 1]
            '''print(str('\nComparing node ') + str(self.node_list.index(node)) + str(' and Node ') + str(self.node_list.index(node) + 1) + ':')'''
            print('Comparing localhost to server')
            # Pass the two root directories of the nodes to the recursive _compare_directories
            self._compare_directories(node.root_path, node2.root_path)

def _compare_directories(self, left, right):
    ''' This method compares directories. If there is a common directory, the
        algorithm must compare what is inside of the directory by calling this
        recursively.
    '''
    comparison = filecmp.dircmp(left, right)
    if comparison.common_dirs:
       for d in comparison.common_dirs:
           self._compare_directories(os.path.join(left, d), os.path.join(right, d))
    if comparison.left_only:
        self._copy(comparison.left_only, left, right)
    if comparison.right_only:
        self._remove(comparison.right_only, right)
    left_newer = []
    right_newer = []
    if comparison.diff_files:
        for d in comparison.diff_files:
            l_modified = os.stat(os.path.join(left, d)).st_mtime
            r_modified = os.stat(os.path.join(right,d)).st_mtime
            if l_modified > r_modified:
                left_newer.append(d)
            else:
                right_newer.append(d)
    self._copy(left_newer, left, right)
    self._copy(right_newer, right, left)

def _copy(self, file_list, src, dest):
    ''' This method copies a list of files from a source node to a destination node '''
    for f in file_list:
        srcpath = os.path.join(src, os.path.basename(f))
        if os.path.isdir(srcpath):
            shutil.copytree(srcpath, os.path.join(dest, os.path.basename(f)))
            self.folder_copied_count = self.folder_copied_count + 1
            print('Copied directory \"' + os.path.basename(srcpath) + '\" from \"' + os.path.dirname(srcpath) + '\" to \"' + dest + '\"')
        else:
            shutil.copy2(srcpath, dest)
            self.file_copied_count = self.file_copied_count + 1
            print('Copied \"' + os.path.basename(srcpath) + '\" from \"' + os.path.dirname(srcpath) + '\" to \"' + dest + '\"')

def _remove(self, file_list, src):
    ''' This method removes a list of files from a destionation node if doesn't exist any longer on source '''
    for f in file_list:
        srcpath = os.path.join(src, os.path.basename(f))
        if os.path.isdir(srcpath):
            shutil.rmtree(srcpath)
            self.folder_removed_count = self.folder_removed_count + 1
            print('Removed directory \"' + os.path.basename(srcpath) + '\" from \"' + os.path.dirname(srcpath))
        else:
            os.remove(srcpath)
            self.file_removed_count = self.file_removed_count + 1
            print('Removed file \"' + os.path.basename(srcpath) + '\" from \"' + os.path.dirname(srcpath))


class Node:
    ''' This class represents a node in a dispathc synchronization '''
    def __init__(self, path, name=''):
        self.name=name
        self.root_path = os.path.abspath(path)
        self.file_list = os.listdir(self.root_path)


if __name__=="__main__":
    node_source = Node('C:\\source_folder', 'source')
    dispatch = Dispatch('Dispatcher')
    node_dest = Node('HERE I NEED AN SFTP OR SSH LINK', 'dest')
    dispatch.add_node(node_source)
    dispatch.add_node(node_dest)
    count=0
    os.system('color 2')
    os.system('cls')
    print('------------------------------------')
    print('| DISPATCHER:  |')
    print('------------------------------------')
    while (count < 1):
        dispatch.compare_nodes()
        print('')
        print('Total files copied ' + str(dispatch.file_copied_count))
        print('Total folders copied ' + str(dispatch.folder_copied_count))
        print('Total files removed ' + str(dispatch.file_removed_count))
        print('Total folders removed ' + str(dispatch.folder_removed_count))
        print('')
        print('Dispatcher is done! Closing connections!')
        count = count + 1
导入操作系统
导入文件CMP
进口舒蒂尔
'''
版本:Python 3.3.2
在CMD中使用python同步文件夹
来源:https://gist.github.com/aortbals/5096365
由Louisdj_15修改
'''
课堂调度:
''此类表示同步对象''
定义初始化(self,name=''):
self.name=name
self.node_list=[]
self.file\u copied\u count=0
self.folder\u copied\u count=0
self.file\u已删除\u计数=0
self.folder\u已删除\u计数=0
def添加_节点(自身,节点):
self.node\u list.append(节点)
def比较_节点(自身):
''此方法获取节点列表中的节点并进行比较''
nodeListLength=len(self.node\u列表)
#对于列表中的每个节点
对于self.node_列表中的节点:
#如果列表后面有其他项,请进行比较
如果self.node\u list.index(node)+1r_修改:
左_。追加(d)
其他:
右图。追加(d)
自我复制(左、左、右)
自我复制(右、右、左)
定义副本(自身、文件列表、src、目的地):
''此方法将文件列表从源节点复制到目标节点''
对于文件列表中的f:
srcpath=os.path.join(src,os.path.basename(f))
如果os.path.isdir(srcpath):
copytree(srcpath,os.path.join(dest,os.path.basename(f)))
self.folder\u copied\u count=self.folder\u copied\u count+1
打印('Copied directory\'''+os.path.basename(srcpath)+'\'从\'+os.path.dirname(srcpath)+'\'复制到\'+dest+'\')
其他:
shutil.copy2(srcpath,dest)
self.file\u copied\u count=self.file\u copied\u count+1
打印('Copied\''+os.path.basename(srcpath)+'\'从\'+os.path.dirname(srcpath)+'\'复制到\'+dest+'\')
定义删除(自、文件列表、src):
''如果源''上不再存在文件,此方法将从目标节点删除文件列表'
对于文件列表中的f:
srcpath=os.path.join(src,os.path.basename(f))
如果os.path.isdir(srcpath):
shutil.rmtree(srcpath)
self.folder\u removed\u count=self.folder\u removed\u count+1
打印('Removed directory\'”+os.path.basename(srcpath)+'\'自\'+os.path.dirname(srcpath))
其他:
删除操作系统(srcpath)
self.file\u removed\u count=self.file\u removed\u count+1
打印('Removed file\''+os.path.basename(srcpath)+'\'来自\'+os.path.dirname(srcpath))
类节点:
''此类表示dispathc同步中的节点''
定义初始化(self,path,name=''):
self.name=name
self.root_path=os.path.abspath(path)
self.file\u list=os.listdir(self.root\u路径)
如果名称=“\uuuuu main\uuuuuuuu”:
node\u source=node('C:\\source\u文件夹,'source')
分派=分派('分派器')
node_dest=node('这里我需要一个SFTP或SSH链接,'dest')
dispatch.add\u节点(节点\u源)
调度。添加节点(节点目的地)
计数=0
操作系统(“颜色2”)
操作系统(“cls”)
打印('--------------------------------------')
打印(“|调度程序:|”)
打印('--------------------------------------')
而(计数<1):
dispatch.compare_节点()
打印(“”)
打印('复制的文件总数'+str(分派.文件\u复制\u计数))
打印('已复制的文件夹总数'+str(分派文件夹\u已复制\u计数))
打印('Total files removed'+str(dispatch.file\u removed\u count))
打印('Total folders removed'+str(dispatch.folders_removed_count))
打印(“”)
打印('Dispatcher已完成!正在关闭连接!')
计数=计数+1

您可以使用命令轻松地生成sftp文件

从fabric.api导入*
env.hosts=[]
带cd('/tmp'):
放置('/path/to/local/test.txt',文件')

为什么不使用?源计算机是Windows和Mac,几乎从来没有Linux计算机。我还没有找到一个不安装额外软件或库就使用rsync的好例子。@Louisdj在这种情况下,有一个库叫做plumbum w
from fabric.api import *
env.hosts = [<hosts>]
with cd('/tmp'):
    put('/path/to/local/test.txt', 'files')