使用Python检查远程SSH服务器上的文件是否存在

Teo*_*Wei 7 python file-io file-exists

我有两个服务器A和B.我想发送一个图像文件,从服务器A发送到另一个服务器B.但是在服务器A可以发送文件之前,我想检查服务器中是否存在类似的文件B.我尝试使用os.path.exists()并且它不起作用.

print os.path.exists('ubuntu@serverB.com:b.jpeg')
Run Code Online (Sandbox Code Playgroud)

即使我在服务器B上放了一个确切的文件,结果也会返回false.我不确定这是我的语法错误还是有更好的解决方案来解决这个问题.谢谢

Die*_*Epp 17

这些os.path功能仅适用于同一台计算机上的文件.它们在路径上运行,而ubuntu@serverB.com:b.jpeg不是路径.

为了实现此目的,您需要远程执行脚本.这样的东西通常会起作用:

def exists_remote(host, path):
    """Test if a file exists at path on a host accessible with SSH."""
    status = subprocess.call(
        ['ssh', host, 'test -f {}'.format(pipes.quote(path))])
    if status == 0:
        return True
    if status == 1:
        return False
    raise Exception('SSH failed')
Run Code Online (Sandbox Code Playgroud)

因此,如果文件存在于另一台服务器上,您可以获得:

if exists_remote('ubuntu@serverB.com', 'b.jpeg'):
    # it exists...
Run Code Online (Sandbox Code Playgroud)

请注意,这可能会非常慢,甚至可能超过100毫秒.

  • `return subprocess.call(['ssh',host,'test -e'+ pipes.quote(path)])== 0` (4认同)