3

何千ものファイルをリモート サーバーにコピーしようとしています。これらのファイルは、スクリプト内でリアルタイムに生成されます。私は Windows システムで作業しており、ファイルを Linux サーバーにコピーする必要があります (したがって、エスケープします)。

私は現在持っています:

import os
os.system("winscp.exe /console /command  \"option batch on\" \"option confirm off\" \"open user:pass@host\" \"put f1.txt /remote/dest/\"")

Python を使用してファイルを生成していますが、リモート接続を永続化して、各ファイルを生成時にサーバーにコピーできるようにする方法が必要です (毎回新しい接続を作成するのではなく)。そうすれば、put オプションのフィールドを次のように変更するだけで済みます。

"put f2 /remote/dest"
"put f3 /remote/dest"

4

3 に答える 3

5

これを行う必要があり、次のようなコードがうまく機能することがわかりました。

from subprocess import Popen, PIPE

WINSCP = r'c:\<path to>\winscp.com'

class UploadFailed(Exception):
    pass

def upload_files(host, user, passwd, files):
    cmds = ['option batch abort', 'option confirm off']
    cmds.append('open sftp://{user}:{passwd}@{host}/'.format(host=host, user=user, passwd=passwd))
    cmds.append('put {} ./'.format(' '.join(files)))
    cmds.append('exit\n')
    with Popen(WINSCP, stdin=PIPE, stdout=PIPE, stderr=PIPE,
               universal_newlines=True) as winscp: #might need shell = True here
        stdout, stderr = winscp.communicate('\n'.join(cmds))
    if winscp.returncode:
        # WinSCP returns 0 for success, so upload failed
        raise UploadFailed

これは (そして Python 3 を使用して) 単純化されていますが、アイデアは理解できます。

于 2015-10-29T17:24:22.993 に答える
2

外部プログラム (winscp) を使用する代わりに、pysshのような python ssh-library を使用することもできます。

于 2011-11-19T22:33:45.040 に答える
0

Python で永続的な WinSCP サブプロセスを開始し、putコマンドを標準入力に継続的にフィードする必要があります。

このための Python の例はありませんが、同等の JScript の例があります:
https://winscp.net/eng/docs/guide_automation_advanced#inout
または C# の例:
https://winscp.net/eng/docs/guide_dotnet#input

ただし、Python 用の COM インターフェイス経由で Wi​​nSCP .NET アセンブリを使用する方が簡単です:
https://winscp.net/eng/docs/library

于 2014-06-13T08:20:38.613 に答える