"/"がディレクトリの最後に指定されていない場合に "test"からディレクトリ全体をコピーし、 "ディレクトリ"内のすべてをコピーする有名なLinux rsyncコマンドの動作を模倣したい。 「/」が存在するときは「テスト/」を選択します。私の地元の「テスト」フォルダがそうのような構造である:rsyncのリモートサーバーへの全体のローカルテスト用フォルダをコピーするにはParamiko SFTPを使用してディレクトリをコピーする
test
.
├── fileA.txt
├── fileB.txt
├── test1
│ └── test3
│ └── file3.txt
└── test2
└── file2.txt
:remotehostのホームディレクトリ内
rsync -avzP test [email protected]:/home/
は
home
.
|__ test
├── fileA.txt
├── fileB.txt
├── test1
│ └── test3
│ └── file3.txt
└── test2
└── file2.txt
だろう
例A
コピーするには
rsync -avzP test/ [email protected]:/home/
ホームディレクトリの構造は次のようになります:自体を除く地域の "テスト" フォルダ内のすべて
home/
.
├── fileA.txt
├── fileB.txt
├── test1
│ └── test3
│ └── file3.txt
└── test2
└── file2.txt
例B
は、私が持っているコードではありません私はパスを分割し、 "テスト"を取り除き、その中のすべてをコピーすることを考えましたが、それは無限のネストされたforループにつながります。もう一つのアイデアはos.listdirを使うことです。それがディレクトリの場合は、ディレクトリを再度一覧表示し、そのディレクトリ内の内容をコピーします。これはもう一つの無限ループです。上記のツリー構造は単純化された例ですが、現実には、ディレクトリが5レベル深くなる可能性があります。 Example Bを実装するにはどうすればよいですか?
def put (self, localpath, remotepath):
sftp = self.ssh.open_sftp()
# Create remote directory if it doesn't exist
try:
sftp.stat (remotepath)
except FileNotFoundError:
sftp.mkdir (remotepath)
if os.path.isfile (localpath):
# Obtain file name from local path & append to remote path
path = os.path.split (localpath) # Returns a tuple (directory, filename)
remote_filename = os.path.join (remotepath, path [1])
print (' Copying %s' % remote_filename)
sftp.put (localpath, remote_filename)
elif os.path.isdir (localpath):
p = os.path.join (remotepath, localpath)
try:
sftp.stat (p)
except FileNotFoundError:
sftp.mkdir (p)
for dirpath, dirnames, filenames in os.walk (localpath):
# Traverse into each child directory and create sub directory if it doesn't exist
if dirnames:
for dirname in dirnames:
subdir = os.path.join (dirpath, dirname)
try:
sftp.stat (subdir)
except FileNotFoundError:
sftp.mkdir (subdir)
for filename in filenames:
local_filename = os.path.join (dirpath, filename)
remote_filename = os.path.join (remotepath, local_filename)
sftp.put (local_filename, remote_filename)