Search code examples
pythonbashtestingsshpexpect

Verify a file exists over ssh


I am trying to test if a file exists over SSH using pexpect. I have got most of the code working but I need to catch the value so I can assert whether the file exists. The code I have done is below:

def VersionID():

        ssh_newkey = 'Are you sure you want to continue connecting'
        # my ssh command line
        p=pexpect.spawn('ssh [email protected]')

        i=p.expect([ssh_newkey,'password:',pexpect.EOF])
        if i==0:
            p.sendline('yes')
            i=p.expect([ssh_newkey,'password:',pexpect.EOF])
        if i==1:
            p.sendline("word")
            i=p.expect('service@main-:')
            p.sendline("cd /opt/ad/bin")
            i=p.expect('service@main-:')
            p.sendline('[ -f email_tidyup.sh ] && echo "File exists" || echo "File does not exists"')
            i=p.expect('File Exists')
            i=p.expect('service@main-:')
            assert True
        elif i==2:
            print "I either got key or connection timeout"
            assert False

        results = p.before # print out the result

VersionID()

Thanks for any help.


Solution

  • If the server accepts sftp sessions, I wouldn't bother with pexpect, but instead use the paramiko SSH2 module for Python:

    import paramiko
    transport=paramiko.Transport("10.10.0.0")
    transport.connect(username="service",password="word")
    sftp=paramiko.SFTPClient.from_transport(transport)
    filestat=sftp.stat("/opt/ad/bin/email_tidyup.sh")
    

    The code opens an SFTPClient connection to the server, on which you can use stat() to check for the existance of files and directories.

    sftp.stat will raise an IOError ('No such file') when the file doesn't exist.

    If the server doesn't support sftp, this would work:

    import paramiko
    client=paramiko.SSHClient()
    client.load_system_host_keys()
    client.connect("10.10.0.0",username="service",password="word")
    _,stdout,_=client.exec_command("[ -f /opt/ad/bin/email_tidyup.sh ] && echo OK")
    assert stdout.read()
    

    SSHClient.exec_command returns a triple (stdin,stdout,stderr). Here we just check for the presence of any output. You might instead vary the command or check stderr for any error messages instead.