2

次の構造で SFTP から取得しようとしています。

main_dir/
 dir1/
  file1
 dir2/
  file2

以下のコマンドでこれを達成しようとしました:

sftp.get_r(main_path + dirpath, local_path)

また

sftp.get_d(main_path + dirpath, local_path)

ローカル パスは のようなものd:/grabbed_files/target_dirで、リモートパスは のようなもの/data/some_dir/target_dirです。

get_r私はFileNotFound例外を取得しています。空のディレクトリをget_d取得しています(ターゲットディレクトリにディレクトリ以外のファイルがある場合、正常に動作します)。

ディレクトリがこのパスに存在することは完全に確信しています。私は何を間違っていますか?

4

3 に答える 3

1

これは私にとってはうまくいきますが、ディレクトリをダウンロードするとローカルにフルパスが作成されます。

pysftp.Connection.get_r()

downloadシンプルなanduploadメソッドも作成しました。

def download_r(sftp, outbox):
    tmp_dir = helpers.create_tmpdir()
    assert sftp.isdir(str(outbox))
    assert pathlib.Path(tmp_dir).is_dir()
    sftp.get_r(str(outbox), str(tmp_dir))
    tmp_dir = tmp_dir / outbox
    return tmp_dir


def upload_r(sftp, inbox, files):
    assert sftp.isdir(str(inbox))
    if pathlib.Path(files).is_dir():
        logger.debug(list(files.iterdir()))
        sftp.put_r(str(files), str(inbox))
    else:
        logger.debug('No files here.')
于 2018-08-28T17:06:41.480 に答える
0

なぜ機能しないのか理解できなかったので、独自の再帰的ソリューションで終了しました。

def grab_dir_rec(sftp, dirpath):
    local_path = target_path + dirpath
    full_path = main_path + dirpath
    if not sftp.exists(full_path):
        return
    if not os.path.exists(local_path):
        os.makedirs(local_path)

    dirlist = sftp.listdir(remotepath=full_path)
    for i in dirlist:
        if sftp.isdir(full_path + '/' + i):
            grab_dir_rec(sftp, dirpath + '/' + i)
        else:
            grab_file(sftp, dirpath + '/' + i)
于 2016-11-15T12:41:36.477 に答える
-1

これを行う pysftp のコンテキスト マネージャー ラッパーが必要な場合は、(github gist をコピー/貼り付けた後) コードがさらに少ないソリューションを次に示します。これを使用すると、次のようになります。

path = "sftp://user:password@test.com/path/to/file.txt"

# Read a file
with open_sftp(path) as f:
    s = f.read() 
print s

# Write to a file
with open_sftp(path, mode='w') as f:
    f.write("Some content.") 

(完全な) 例: http://www.prschmid.com/2016/09/simple-opensftp-context-manager-for.html

このコンテキスト マネージャーには、最初に接続できない場合に備えて自動再試行ロジックが組み込まれています (これは、実稼働環境で予想されるよりも驚くほど頻繁に発生します...)。

ああ、はい、これは、ftp 接続を自動的に閉じるため、接続ごとに 1 つのファイルしか取得しないことを前提としています。

open_sftp のコンテキスト マネージャーの要点: https://gist.github.com/prschmid/80a19c22012e42d4d6e791c1e4eb8515

于 2016-11-28T22:44:52.637 に答える