Remote directory exists or not in python

How to check whether remote directory is exists or not in python program?

Below command returns the directory if exists, otherwise raises the error.

ls -d <directory>

Using paramiko module, create SSH client object and execute the above command to check whether directory exists or not.

Raises error if directory is not exists, otherwise directory is exists.

import paramiko                                                                 
def directory_exists(directory):  
    # change to required host ip address.                                              
    host_ip = ''                                                  
    client = paramiko.SSHClient()                                               
    client.connect(host_ip, username='root')                                    
    is_directory_exists = False                                                 
    cmd = 'ls -d ' + directory                                                  
    stdin, stdout, stderr = client.exec_command(cmd)                            
    if not str(                                                  
        is_directory_exists = True                                              
    return is_directory_exists                                                  
if __name__ == '__main__':                                                      
    directory = "test"                                                         
    dir_exists = directory_exists(directory)                                    
    if dir_exists:                                                              
        print("directory exists!")                                              
        print("directory is not exists!")                                                                                 

$ python
directory is not exists!

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter