Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking a file existence on a remote SSH server using Python

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('[email protected]: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

like image 415
Teo Jie Wei Avatar asked Jan 18 '13 04:01

Teo Jie Wei


People also ask

How do you check if a file is present in a remote server?

You first need to enable key-based SSH authentication to the remote host, so that your script can access a remote host in non-interactive batch mode. You also need to make sure that SSH login has read permission on the file to check.

How do I view a file in SSH?

SSH provides two different commands, which can be used to accomplish this. In order to search for a file location, you can use the find command. Find is a very powerful tool and accepts various arguments allowing you to specify the exact search term (i.e search by name, by type or even by modified time).


1 Answers

The os.path functions only work on files on the same computer. They operate on paths, and [email protected]: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('[email protected]', 'b.jpeg'):
    # it exists...

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

like image 117
Dietrich Epp Avatar answered Sep 26 '22 04:09

Dietrich Epp