Check If Path Exists Using Fabric
Asked Answered
T

4

9

I am running this code to check whether this directory exists on remote machine or not but this code is checking for the directory on local machine. How can I verify directory on remote machine?

rom fabric.api import run, sudo, env
import os

env.hosts = ['remote_server']
env.user = 'ubuntu'
env.key_filename = '/home/ubuntu/ubuntu16-multi.pem'


def Directory_Check():
  DIR_1="/home/ubuntu/test-dir"
  if os.path.exists(DIR_1):
    print "Directory Exist!"
  else:
    print "Directory Does Not Exist!"
Toot answered 24/6, 2017 at 12:58 Comment(0)
M
13

You can use the files.exists function.

def check_exists(filename):
    from fabric.contrib import files
    if files.exists(filename):
        print('%s exists!' % filename)

And call it with execute.

def main():
    execute(check_exists, '/path/to/file/on/remote')
Matsu answered 1/7, 2017 at 17:12 Comment(1)
This is exact what I was looking for. Thanks.Toot
H
14

Although the accepted answer is valid for fabric ver 1, for whoever hits this thread while looking for the same thing but for fabric2:

exists method from fabric.contrib.files was moved to patchwork.files with a small signature change, so you can use it like this:

from fabric2 import Connection
from patchwork.files import exists

conn = Connection('host')
if exists(conn, SOME_REMOTE_DIR):
   do_something()
Hydropathy answered 30/1, 2019 at 12:5 Comment(0)
M
13

You can use the files.exists function.

def check_exists(filename):
    from fabric.contrib import files
    if files.exists(filename):
        print('%s exists!' % filename)

And call it with execute.

def main():
    execute(check_exists, '/path/to/file/on/remote')
Matsu answered 1/7, 2017 at 17:12 Comment(1)
This is exact what I was looking for. Thanks.Toot
G
9

why not just keep it simply stupid as:

from fabric.contrib.files import exists

def foo():
    if exists('/path/to/remote/file', use_sudo=True):
      # do something...
Grapevine answered 7/1, 2018 at 10:24 Comment(3)
is there a way to use it in local ?Flushing
@Flushing nope. It is aimed for using on remote hosts github.com/fabric/fabric/blob/master/fabric/contrib/…Grapevine
@andi: you're snippet won't connect to the OP's remote where the env is set at run time in code. If you set env in code, you have to wrap in an execute to pick up the changes to the env.Matsu
O
0

For newer versions of fabric:

def file_exists(connection, full_path):
    try:
        result = connection.run(f'ls -ls {full_path}', hide=True)
        return True
    except:
        return False

Example:

with connection('1.1.1.1', port=1111) as conn:
    result = file_exists(conn, '/home/user/.bashrc')
Osswald answered 20/10, 2023 at 9:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.