Test if File/Dir exists over SSH/Sudo in Python/Bash

mh00h picture mh00h · Jul 29, 2013 · Viewed 12.1k times · Source

I am installing certificates on a remote server and want to check whether they exist before I overwrite them. The server only allows non-root access via ssh public key. I can sudo -s to root once in a shell. Root is required because /etc/ssl is not readable by anyone else. This is being developed in python fabric, so any command that can be run in a shell command via sudo would work. I don't mind typing in passwords at prompts in this case.

TL;DR: I need an sh command that can tell my python program whether a remote file (or directory) exists when run as if fabric.sudo(sh_command) == True: (or something similar).

Thank you!

Answer

Yuichiro picture Yuichiro · Jul 29, 2013
from fabric.contrib.files import exists

def foo():
    if exists('/path/to/remote/file', use_sudo=True):
        #command