远程目录列表Python WSGI

时间:2014-02-07 13:49:09

标签: python linux list wsgi dir

我目前是IT服务的实习生,并且我被要求使用将在Linux环境中运行的Python构建基于Web的应用程序。这个Web应用程序必须符合WSGI,我不能使用任何框架。

我目前的问题是我想将变量设置为所述目录中的文件列表。因此,我可以通过打印每行都是文件的表来继续列出这些文件。

我知道os.listdir()但是找不到在远程服务器上使用它的方法(考虑到google搜索显示我的情况,这应该不是这样的。)。

我尝试了一个os.system(ssh root @ someip:/ path / to / dir /)但是作为python doc状态,我无法得到我想要的输出,因为它返回一些整数......

下面是我的一个剧本。

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

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

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

command = "ssh root@"+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)并且它完美运行。我只在远程目录列表中遇到麻烦...

我希望我的问题非常明确,如果不是,我会尽力做到更准确。

提前致谢, -Karink。

2 个答案:

答案 0 :(得分:5)

您可以使用subprocess module,这是一个示例:

import subprocess
ls = subprocess.Popen(['ssh','user@xx.xx.xx.xx', 'ls'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err =  ls.communicate()
print out
print err   

答案 1 :(得分:0)

您也可以使用pysftp 首先使用 pip install pysftp 安装它,然后下面的代码也可以从Windows列出远程Linux机器上的文件

import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None

with pysftp.Connection('ipLinuxmachine', username='username', password='passwd',cnopts=cnopts) as sftp:
    out=sftp.execute('cd path of directory ; ls')
    print out