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.

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

Output:
$ python is_dir_exists.py
directory is not exists!

Privacy Policy  |  Copyright@2017 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^