2014-02-07 53 views
0

我目前是一名IT服務實習生,我被要求使用Python在Linux環境下運行構建一個基於Web的應用程序。這個網絡應用程序必須符合WSGI,我不能使用任何框架。遠程目錄列表Python WSGI

我現在的問題是我想有一個變量設置爲所述目錄中的文件列表。因此,我可以繼續通過打印每行是文件的表來列出這些文件。

我知道os.listdir(),但找不到在遠程服務器上使用它的方法(這不應該是這種情況,考慮谷歌搜索顯示給我...)。

我嘗試過的使用os.system(SSH根@ someip:/路徑/到/ DIR /),但蟒蛇文檔狀態,我無法得到我想要的,因爲它返回一些整數輸出...

以下是我的腳本的一部分。

#ip is = to the ip of the server I want to list. 

ip = 192.............. 

directory = "/var/lib/libvirt/images/" 

command = "ssh [email protected]"+ip+" ls "+directory 

dirs = os.system(command) 


files = "" 
table_open = "<table>" 
table_close = "</table>" 
table_title_open = "<th>Server: " 
table_title_close = "</th>" 
tr_open = "<tr>" 
tr_close = "</tr>" 
td_open = "<td>" 
td_close = "</td>" 
input_open = "<input type='checkbox' name='choice' value='" 
input_close = "'>" 

#If i don't put dirs in brackets it raises an error (dirs not being iterable) 
for file in [dirs]: 

    files = files + tr_open+td_open+file+td_close+td_open+input_open+file+input_close+td_close+tr_close 

table = table_open+table_title_open+str(num_server)+table_title_close+files+table_close 

我試過用本地目錄(與os.listdir),它完美的作品。我遇到麻煩只與遠程目錄列表...

我希望我的問題很清楚,如果不是,我會盡我所能來更準確。

在此先感謝, -卡林克。

+0

檢查[子模塊](http://docs.python.org/2/library/subprocess.html)它可以讓你獲得輸出 –

+0

謝謝,我會看看它。 – Karink

回答

4

您可以使用subprocess module,這裏有一個例子:

import subprocess 
ls = subprocess.Popen(['ssh','[email protected]', 'ls'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
out, err = ls.communicate() 
print out 
print err 
+1

再次問好,SSH Key問題很少,但現在一切正常,所以我只想感謝你的幫助。祝你今天愉快 ! ;) – Karink