Search code examples
pythonparamiko

Paramiko how to check if current path is directory


I'm encountering an issue while working with the paramiko library, specifically regarding the SFTPClient module. I'm attempting to recursively download files from a directory, including all subdirectories and their contents. However, I'm facing difficulty determining whether a given path is a directory or not within the SFTPClient.

I'm using the latest version of paramiko (version 3.4.0). Below is the relevant portion of my Python code:

def download_files(self, local_dir):
    if self.sftp_instance:
        current_dir = self.sftp_instance.getcwd()
        local_path = os.path.join(local_dir, os.path.basename(current_dir))
        os.makedirs(local_path, exist_ok=True)

        files = self.get_list_of_files_in_current_dir()
        for item in files:
            remote_path = os.path.join(current_dir, item)
            item_local_path = os.path.join(local_path, item)
            print("Remote path:", remote_path)
            print("cwd", self.sftp_instance.getcwd())
            print("Is directory:", self.sftp_instance.stat(item).st_isdir())  # This line raises an AttributeError
            if self.sftp_instance.stat(remote_path).isdir():  # This is where I'm experiencing issues
                if not self.sftp_instance.listdir(remote_path):
                    print(f"Skipped empty directory: {item}")
                else:
                    self.sftp_instance.chdir(remote_path)
                    self.download_files(local_path)
                    self.sftp_instance.chdir("..")
            else:
                try:
                    self.sftp_instance.get(remote_path, item_local_path)
                    print(f"Downloaded file: {item}")
                except IOError as e:
                    print(f"Error downloading file: {item}")
                    print(f"Error message: {str(e)}")
                    print(f"Error details:")
                    print(f"  errno: {e.errno}")
                    print(f"  strerror: {e.strerror}")
                    print(f"  filename: {e.filename}")
                except Exception as e:
                    print(f"Error downloading file: {item}. {str(e)}")
    else:
        print("SFTP connection not established. Please connect first.")

The specific line causing trouble is:

print("Is directory:", self.sftp_instance.stat(item).st_isdir())

This line raises the following error:

AttributeError: 'SFTPAttributes' object has no attribute 'st_isdir'

I've also attempted to use the isdir() method directly on the SFTPAttributes object returned by self.sftp_instance.stat(remote_path), but it appears that this method is not available.

Is there a different approach or method provided by the paramiko library that I should be using to determine whether a given path is a directory? Any insights or alternatives would be greatly appreciated. Thank you.


Solution

  • For the stat() function call, return value is an object whose attributes correspond to the attributes of Python’s stat structure as returned by os.stat.

    You can use the stat.S_ISDIR function to decide to whether the mode(st_mode) is a directory or not.

    import stat
    print("Is directory:", stat.S_ISDIR(self.sftp_instance.stat(item).st_mode))