Irfan Ghaffar7
Irfan Ghaffar7

Reputation: 1185

File Selection From Remote Machine In Python

I am writing a program in python on Ubuntu. In that program I am struggling to select a file using the command askopenfilename on a remote network connected RaspberryPi.

Can anybody guide me on how to select a file from the remote machine using askopenfilename command or something similar?

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()

Upvotes: 2

Views: 1785

Answers (1)

Igor Hatarist
Igor Hatarist

Reputation: 5442

Haha, hello again!

It's not possible to use a tkinter's file dialogs to list (or select) files on remote machine. You would need to mount the remote machine's drive using, for example, SSHFS (as mentioned in the question's comment), or use a custom tkinter dialog which displays the remote files list (that is in the stdout variable) and lets you choose the one.

You can write a dialog window yourself, here's a quick demo:

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()

The easiest solution without a tkinter is - you could make the user type the filename using the raw_input() function.

Kind of like that:

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

So the user would have to enter the filename that is to be deleted; then that filename gets passed directly to the rm command.

It's not really a safe approach - you should definitely escape the user's input. Imagine what if the user types '-rf /*' as a filename. Nothing good, even if you're not connected as a root.
But while you're learning and keeping the script to yourself I guess it's alright.

Upvotes: 4

Related Questions