使用Python检查远程SSH服务器上的文件是否存在 [英] Checking a file existence on a remote SSH server using Python

查看:2164
本文介绍了使用Python检查远程SSH服务器上的文件是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个服务器A和B.我想发送一个图像文件,从服务器A发送到另一个服务器B.但在服务器A可以发送文件之前,我想检查是否有类似的文件存在于服务器B中。我尝试使用os.path.exists(),它不起作用。
$ b $ pre $ print $打印os.path。存在('ubuntu@serverB.com:b.jpeg')

结果返回假在服务器B上放了一个确切的文件。我不确定是否是我的语法错误,或者是否有更好的解决方案来解决这个问题。谢谢


解决方案

os.path中功能只对文件上工作同一台电脑。它们在路径上运行,而 ubuntu@serverB.com:b.jpeg 不是路径。



为了做到这一点,您将需要远程执行一个脚本。像这样的东西可以工作,通常:

$ $ p $ def exists_remote(host,path):
文件存在于可通过SSH访问的主机上的路径上。
status = subprocess.call(
['ssh',host,'test -f {}'。format(pipes.quote(path ))])
if status == 0:
return True
if status == 1:
return False
异常('SSH失败')

所以你可以得到一个文件是否存在于另一台服务器上:

 如果exists_remote('ubuntu@serverB.com','b.jpeg'):
#它存在...

请注意,这可能会很慢,甚至可能超过100毫秒。

$ b

I have two servers A and B. I'm suppose to send, let said an image file, from server A to another server B. But before server A could send the file over I would like to check if a similar file exist in server B. I try using os.path.exists() and it does not work.

print os.path.exists('ubuntu@serverB.com:b.jpeg')

The result return a false even I have put an exact file on server B. I'm not sure whether is it my syntax error or is there any better solution to this problem. Thank you

解决方案

The os.path functions only work on files on the same computer. They operate on paths, and ubuntu@serverB.com:b.jpeg is not a path.

In order to accomplish this, you will need to remotely execute a script. Something like this will work, usually:

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')

So you can get if a file exists on another server with:

if exists_remote('ubuntu@serverB.com', 'b.jpeg'):
    # it exists...

Note that this will probably be incredibly slow, likely even more than 100 ms.

这篇关于使用Python检查远程SSH服务器上的文件是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆