Skip to content Skip to sidebar Skip to footer

Os.walk Remote Linux Server

Is it possible to have os.walk() read the contents of a remote Linux server, without any third-party libraries? I know that on Windows, we can use UNC paths, for example: os.walk(r

Solution 1:

We cannot directly do os.walk in remote machine. But, we can write a similar function, not exactly same functionality, but a best effort approach with the help of open_sftp, listdir_attr and paramiko. One sample I tried.

import paramiko
from stat import S_ISDIR

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('ip_address_remote_machine', username='username', password='password', banner_timeout=60)
sftp = client.open_sftp()

        defsftpwalk(dl):
            remotepath = dl
            files = []
            folders = []
            for f in sftp.listdir_attr(remotepath):
                if S_ISDIR(f.st_mode):
                    folders.append(f.filename)
                    #print(dl+f.filename)
                    sftpwalk(dl+f.filename+"/")
                else:
                    # if
                    files.append(f.filename)
            # print (path,folders,files)print( remotepath,folders,files)
    
    dl= '/home/generic/Nizam/'
    sftpwalk(dl)
    client.close

This can go to remote path passed, list out all directories, and files. Further enhancement can still be tried.

Under Nizam , I have dir1, dir2, dir3 and dir1 has dir11, dir12 with some files.

Output of this is:

(u'/home/generic/Nizam/dir2/', [], [])
(u'/home/generic/Nizam/dir1/dir12/', [], [])
(u'/home/generic/Nizam/dir1/dir11/', [], [u'11.txt'])
(u'/home/generic/Nizam/dir1/', [u'dir12', u'dir11'], [u'2.txt', u'1.txt', u'3.txt'])
(u'/home/generic/Nizam/dir3/', [], [])
('/home/generic/Nizam/', [u'dir2', u'dir1', u'dir3'], [])

Post a Comment for "Os.walk Remote Linux Server"