Checking a file existence on a remote SSH server using Python

三世轮回 提交于 2019-12-30 06:29:09

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/14392432/checking-a-file-existence-on-a-remote-ssh-server-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!