2011-11-19 16 views
2

我試圖將數千個文件複製到遠程服務器。這些文件是在腳本中實時生成的。我正在使用Windows系統,需要將這些文件複製到Linux服務器(因此轉義)。在Python中批量複製的持久WinSCP連接

我目前有:

import os 
os.system("winscp.exe /console /command \"option batch on\" \"option confirm off\" \"open user:[email protected]\" \"put f1.txt /remote/dest/\"") 

我使用Python生成的文件,但需要一種方法來持續的遠程連接,這樣我可以複製的每個文件,到服務器,因爲它是生成(而不是每次都創建一個新的連接)。這樣一來,我只需要改變字段中看跌期權這樣的:如果不使用外部程序(WinSCP賦予)的

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

回答

2

你也可以使用一個蟒蛇SSH文庫樣pyssh

+1

那麼我如何使用pyssh完成我的任務? – Duke

4

我需要做到這一點,發現類似這樣的代碼運行良好:

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: 
     stdout, stderr = winscp.communicate('\n'.join(cmds)) 
    if winscp.returncode: 
     # WinSCP returns 0 for success, so upload failed 
     raise UploadFailed 

這是簡化的(並使用Python 3),但你明白了。