【问题标题】:How to check if file exists on remote linux?如何检查远程linux上是否存在文件?
【发布时间】:2020-07-16 08:09:30
【问题描述】:

我正在尝试检查文件是否存在于 Python / Linux 中。

我的本​​地机器(我通过 ssh 使用)是:Red Hat Enterprise Linux Server。
目标机器(我 ssh 到)是:Amazon Linux、centos rhel fedora。

我尝试过以下 CMD:

ssh -qnx [host] "test /path/to/file.txt && echo 'Exists' || echo 'Not'" 

但它总是返回“Exists”,在不存在的文件上也是如此。

这个 CMD 也总是返回存在:

ssh host test -f "/path/to/file.txt" && echo found || echo not found

还有这个:

if ssh [host] test -e "/path/to/file.txt" ; then echo found ; else echo not found ; fi

我也试过了:

ssh -q [host] [[ -f /path/to/file.txt ]] && echo "File exists" || echo "File does not exist";

但它说:zsh: bad pattern: [[

我需要一个简单的 CMD,稍后我可以在 python 中使用os.system(cmd),并收到是或否的答案。

我错过了什么?

谢谢

【问题讨论】:

  • "test /path/to/file.txt && echo 'Exists' || echo 'Not'" 不应该是test -f 吗?修复后它对我有用。
  • 它还为我返回不存在的文件的“找到”。我怀疑我的本地机器的行为与普通 linux 不同。
  • ssh -qnx user@host "test -e /path/to/file && echo exists || echo not"。您在test 命令中缺少-e-f
  • 或者,ssh -qnx user@host "test -e /path/to/file" && echo exists || echo not
  • ssh -qnx user@host "test -e /path/to/file && echo exists || echo not" - 如果你想添加它作为答案,我会接受它。 :-)

标签: linux ssh filesystems remote-access


【解决方案1】:
#!/bin/bash
USE_IP='-o StrictHostKeyChecking=no remote-machine-username@remote-machine-host/IP'

FILE_NAME=/home/user/file.txt

SSH_PASS='sshpass -p remote-machine-password here...'

if $SSH_PASS ssh $USE_IP stat $FILE_NAME \> /dev/null 2\>\&1
        then
                echo "File exists on remote machine"
        else
                echo "File does not exist on remote machine"

fi

在您的机器上安装sshpass 以使其工作。

【讨论】:

  • 我正在寻找一个 CMD,以后可以在带有 os.system 的 python 代码中使用它,这太复杂了
猜你喜欢
  • 1970-01-01
  • 2018-06-19
  • 2011-05-07
  • 1970-01-01
  • 1970-01-01
  • 2010-11-02
  • 1970-01-01
  • 2012-06-13
相关资源
最近更新 更多