Search code examples
pythonsshparamiko

How to check if the created file using Paramiko exec_command exists


I'm trying to open a file which got created as part of the Paramiko exec_command. The file gets created, but when I check if the file exists, it always returns false. How do I check if the file exists and then open the file for reading?

The code written is:

ip = '10.30.2.104'
username = 'root'
password = 'docker'
def checkSSH(ip, username, password, retries=1):
    ssh = SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.load_system_host_keys()
    for x in range(retries):
        try:
            ssh.connect(ip, username=username, password=password, timeout=10)
            return ssh
        except (
        paramiko.BadHostKeyException, paramiko.AuthenticationException, paramiko.SSHException, socket.error) as e:
            print('Exception occured.. {0}'.format(e))
            return False

hdl = checkSSH(ip, username, password)
cmd = 'ls > test.log'
hdl.exec_command(cmd)
a = os.path.exists('/root/test.log')
print(a) >>> if the file exists, this returns true as per the documentation but in this case, it always returns false.

Solution

  • First, you are not waiting for the command to complete.

    For that see:
    Execute command and wait for it to finish with Python Paramiko

    Once the command completes, you can retrieve its exit code using Channel.recv_exit_status():
    How can you get the SSH return code using Paramiko?

    If it returns 0, you know that everything went fine and no additional check is needed.


    Anyway, if you want to check, use SFTP (SFTPClient.stat):

    sftp = hdl.open_sftp()
    try:
        sftp.stat('/root/test.log')
        print("exists")
    except Exception as e:
        print("something is wrong: " + e)
    

    Though the execution of ls command seems strange to me.

    If you want to retrieve the directory listing, use SFTP: SFTPClient.listdir_attr