【问题标题】:Remote Directory Listing Python WSGI远程目录列表 Python WSGI
【发布时间】:2014-03-04 23:11:30
【问题描述】:

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

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

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

我尝试了一个 os.system(ssh root@someip:/path/to/dir/) 但正如 python 文档所述,我无法得到我想要的输出,因为它返回了一些整数...

下面是我的一段脚本。

#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)中尝试过这个,它运行良好。我只是在远程目录列表方面遇到了麻烦......

我确实希望我的问题很清楚,否则我会尽力更准确。

提前致谢, -卡林克。

【问题讨论】:

标签: python linux list wsgi dir


【解决方案1】:

你可以使用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   

【讨论】:

  • 您好,SSH 密钥有一些问题,但现在一切正常,所以我只想感谢您的帮助。祝你今天过得愉快 ! ;)
【解决方案2】:

你也可以使用 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

【讨论】:

    猜你喜欢
    • 2015-07-30
    • 1970-01-01
    • 2017-04-28
    • 2010-12-13
    • 1970-01-01
    • 2013-01-02
    • 2016-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多