在 Python/Bash 中通过 SSH/Sudo 测试文件/目录是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17916144/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Test if File/Dir exists over SSH/Sudo in Python/Bash
提问by mh00h
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.
我正在远程服务器上安装证书,并希望在覆盖它们之前检查它们是否存在。服务器只允许通过 ssh 公钥进行非 root 访问。我可以sudo -s
在 shell 中 root 一次。需要 root,因为 /etc/ssl 不能被其他人读取。这是在 中开发的python fabric
,因此任何可以在 shell 命令中运行的命令sudo
都可以使用。在这种情况下,我不介意在提示时输入密码。
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).
TL;DR:我需要一个sh
命令来告诉我的 python 程序在运行时是否存在远程文件(或目录)if fabric.sudo(sh_command) == True:
(或类似的东西)。
Thank you!
谢谢!
回答by Yuichiro
from fabric.contrib.files import exists
def foo():
if exists('/path/to/remote/file', use_sudo=True):
#command
回答by Eric Fournie
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"'