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

2020-08-24 18:18发布

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!

2楼-- · 2020-08-24 18:29
from fabric.contrib.files import exists

def foo():
    if exists('/path/to/remote/file', use_sudo=True):
3楼-- · 2020-08-24 18:29

Run a command like test in Linux to figure out whether a directory exists or not. The output of fabric.sudo is a multline-string, that can be parsed for the return status.

4楼-- · 2020-08-24 18:43

Maybe not the simplest way, but out of my head, I would suggest

ssh user@server 'bash -c "if [ -e /path/to/remote/file ] ; then true ; fi"'
登录 后发表回答