Search code examples
pythonbashpython-3.xparamikols

paramiko ls with several files output truncated


I've used paramiko's exec_command with ls succesfully until I tried it with a list of files as an argument. My function is:

def jz_orion_ssh_sout_list(cmd):
    with paramiko.SSHClient() as ssh:
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(orion['host'], username=orion['username'], password=orion['password'])
        ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd)
        sout = ssh_stdout.readlines()
        serr = ssh_stderr.readlines()
        return sout

When cmd='ls -l /my/path/file.txt' it works fine, but when cmd='ls -l /my/path/file1.txt file2.txt file3.txt', it only returns file1.txt. The latter cmd run directly on the target server returns all 3 files.

How to make it work in paramiko?

PS. I've found another syntax which works in paramiko: cmd='ls -l /my/path/{file1.txt,file2.txt,file3.txt}' but still I'd like to know what causes the failure with beforementioned one.


Solution

  • It is your cmd issue: For instance, I have 3 files under example folder:

    ➜ ls example
    file1 file2 file4
    

    file2 is not found:

    ➜ ls -l example/file1 file2
    ls: file2: No such file or directory
    -rw-r--r--  1 haifzhan  staff  391 28 Nov 10:23 example/file1
    

    ls -l example/file1 file2 is telling ls file2 is under current directory other than under folder example.

    If we run the command just for file1 and file2

    ➜ ls -l example/file[1-2]
    -rw-r--r--  1 haifzhan  staff  391 28 Nov 10:23 example/file1
    -rw-r--r--  1 haifzhan  staff   81 28 Nov 10:26 example/file2
    

    Alternatively:

    ls -l example/file1 example/file2
    -rw-r--r--  1 haifzhan  staff  391 28 Nov 10:23 example/file1
    -rw-r--r--  1 haifzhan  staff   81 28 Nov 10:26 example/file2
    

    In your case ls -l /my/path/{file1.txt,file2.txt,file3.txt} works is that you are telling ls that all your files are under /my/path