2014-05-16 35 views
0

它的缺點是,我需要一個程序,通過sftp將本地目錄中的所有txt文件上傳到特定的遠程目錄。如果我從sftp命令行運行mput * .txt,而im已經在正確的本地目錄中,那麼這就是我正在拍攝的內容。Python代碼,子進程使用glob嗎?

這裏是代碼即時嘗試。沒有錯誤,當我運行它,但沒有結果要麼當我sftp到服務器和ls的上傳目錄,它的空。我可能會一起吠叫錯誤的樹。我看到其他的解決方案,比如在bash中使用mget的lftp ...但我真的希望這可以與python一起使用。無論如何,我還有很多東西需要學習。這是幾天後讀到關於一些stackoverflow用戶的建議,幾個圖書館可能會有所幫助。即時通訊不知道我可以用「子進程」來做「所有文件中的我:」。

import os 
import glob 
import subprocess 

os.chdir('/home/submitid/Local/Upload') #change pwd so i can use mget *.txt and glob similarly 

pwd = '/Home/submitid/Upload' #remote directory to upload all txt files to 

allfiles = glob.glob('*.txt') #get a list of txt files in lpwd 

target="[email protected]" 


sp = subprocess.Popen(['sftp', target], shell=False, stdin=subprocess.PIPE) 


sp.stdin.write("chdir %s\n" % pwd) #change directory to pwd 

for i in allfiles: 
    sp.stdin.write("put %s\n" % allfiles) #for each file in allfiles, do a put %filename to pwd 

sp.stdin.write("bye\n")  


sp.stdin.close() 

回答

0

當你遍歷allfiles,你是不是傳遞迭代變量sp.stdin.write,但allfiles本身。它應該是

for i in allfiles: 
    sp.stdin.write("put %s\n" % i) #for each file in allfiles, do a put %filename to pwd 

在發出命令之前,您可能還需要等待sftp進行身份驗證。你可以從這個過程讀取標準輸出,或者只是在你的代碼中加入一些延遲。

但是,爲什麼不只是使用scp並構建完整的命令行,然後檢查它是否成功執行?喜歡的東西:

result = os.system('scp %s %s:%s' % (' '.join(allfiles), target, pwd)) 
if result != 0: 
    print 'error!' 
+0

DANG工作!現在,如果我只能擺脫密碼提示。我將不得不閱讀時間。睡覺...謝謝你! – Dogbyte

+0

@Dogbyte您可能會更好使用SSH公鑰身份驗證來繞過密碼。請參閱http://stackoverflow.com/questions/7260/how-do-i-setup-public-key-authentication –

+0

關於SSH公鑰認證,我不知道我有這種級別的訪問遠程服務器,這是向醫療保健提供者發送EDI交易。他們只允許基本的sftp命令。 – Dogbyte

0

你不需要遍歷allfiles

sp.stdin.write("put *.txt\n") 

就足夠了。您指示sftp將所有文件一次放入,而不是逐個放入。