2010-09-07 67 views
2

我想從Python腳本運行並控制PSFTP,以便將來自UNIX框的日誌文件放到Windows機器上。我可以通過Python腳本控制PSFTP嗎?

我可以啓動PSFTP並登錄,但是當我試圖遠程運行一個命令如'cd'時,它不能被PSFTP識別,而只是在關閉PSFTP時在終端中運行。

而我試圖運行的代碼如下:

import os 

os.system("<directory> -l <username> -pw <password>") 
os.system("cd <anotherDirectory>") 

我只是想知道,如果這實際上是可能的。或者,如果有更好的方法在Python中執行此操作。

謝謝。

回答

2

您需要將PSFTP作爲子流程運行,並直接與流程對話。每次調用它時,os.system都會生成一個單獨的子shell,因此它不能像按順序將命令輸入命令提示符窗口那樣工作。查看標準Python subprocess模塊的文檔。你應該能夠從那裏完成你的目標。另外,還有一些可用的Python SSH軟件包,例如paramikoTwisted。如果你已經對PSFTP感到滿意,那麼我肯定會堅持盡力讓它工作。

子進程模塊提示:

# The following line spawns the psftp process and binds its standard input 
# to p.stdin and its standard output to p.stdout 
p = subprocess.Popen('psftp -l testuser -pw testpass'.split(), 
        stdin=subprocess.PIPE, stdout=subprocess.PIPE) 
# Send the 'cd some_directory' command to the process as if a user were 
# typing it at the command line 
p.stdin.write('cd some_directory\n') 
+0

我看了一下子進程,我可以讓PSFTP運行,但我仍然無法弄清楚如何發送命令給它?有任何想法嗎?? – matt2010 2010-09-07 14:58:55

+0

編輯提供子流程模塊示例 – Rakis 2010-09-07 16:55:01

相關問題