2015-02-10 75 views
2

我在Ubuntu上编写了一个python程序。在那个程序中,我正努力在连接RaspberryPi的远程网络上使用命令askopenfilename选择一个文件。从Python中的远程计算机中选择文件

任何人都可以指导我如何使用askopenfilename命令或类似的东西在远程机器选择一个文件?

from Tkinter import * 
from tkFileDialog import askopenfilename 
import paramiko 

if __name__ == '__main__': 

    root = Tk() 

    client = paramiko.SSHClient() 
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
    client.connect('192.168.2.34', username='pi', password='raspberry') 
    name1= askopenfilename(title = "Select File For Removal", filetypes = [("Video Files","*.h264")]) 
    stdin, stdout, stderr = client.exec_command('ls -l') 
    for line in stdout: 
     print '... ' + line.strip('\n') 
    client.close() 
+3

用'sshfs'挂载远程文件系统是否更加可行,以便远程文件可以作为本地文件访问?您似乎已经拥有了ssh访问权限。 – 2015-02-10 15:56:13

+0

@RafaelLerm我该怎么做 – 2015-02-10 15:57:12

+0

@ IrfanGhaffar7这取决于您在计算机上使用的操作系统。例如,Google上有[Windows 8手册](http://igikorn.com/sshfs-windows-8/)。只是谷歌“如何安装sshfs(您的操作系统)”。 – 2015-02-10 16:04:56

回答

3

哈哈,你好!

无法使用tkinter的文件对话框来列出(或选择)远程计算机上的文件。您需要使用例如SSHFS(如问题评论中提到的)挂载远程计算机的驱动器,或使用显示远程文件列表(位于stdout变量中)的自定义tkinter对话框,并让您选择一个。

你可以自己写一个对话窗口,这里有一个快速演示:

from Tkinter import * 


def double_clicked(event): 
    """ This function will be called when a user double-clicks on a list element. 
     It will print the filename of the selected file. """ 
    file_id = event.widget.curselection() # get an index of the selected element 
    filename = event.widget.get(file_id[0]) # get the content of the first selected element 
    print filename 

if __name__ == '__main__': 
    root = Tk() 
    files = ['file1.h264', 'file2.txt', 'file3.csv'] 

    # create a listbox 
    listbox = Listbox(root) 
    listbox.pack() 

    # fill the listbox with the file list 
    for file in files: 
     listbox.insert(END, file) 

    # make it so when you double-click on the list's element, the double_clicked function runs (see above) 
    listbox.bind("<Double-Button-1>", double_clicked) 

    # run the tkinter window 
    root.mainloop() 

最简单的解决方案,而一个tkinter是 - 你可以让用户使用raw_input()功能键入文件名。

喜欢这样:

filename = raw_input('Enter filename to delete: ') 
client.exec_command('rm {0}'.format(filename)) 

因此,用户必须输入文件名要被删除;那么该文件名将直接传递给rm命令。

这不是一个真正安全的方法 - 您绝对应该逃避用户的输入。想象一下,如果用户输入'-rf /*'作为文件名,该怎么办。没有什么好处,即使你没有作为根连接。
但是,当你正在学习和保持脚本给自己,我猜这是正常的。

+0

但实际上在'askforfilename'中,我只需要选择它,而不是输入文件名以用于删除目的。 我的文件名非常长,很典型,所以我想用它。 – 2015-02-10 16:12:47