Search code examples
pythonpython-3.xsftpparamiko

Upload all files from local folder with specific extension to SFTP server using Paramiko


I am using paramiko to upload files to SFTP server. I want to transfer all files in folder. The names of files are in a manner one.txt, two.txt.... . I want the files to be sent sequentially like one.txt then two.txt then three.txt.....the below code for transfer of one file runs fine, but the last code which I have tried to transfer all files is not working....

import paramiko

source = r'/home/netcs/b/one.txt'
dest = r'/home/tein/c/pickle.txt'
hostname = '10.10.10.9'
port = 22 # default port for SSH
username = 'tein'
password = 'po'

try:
    t = paramiko.Transport((hostname, port))
    t.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(t)
    sftp.put(source, dest)
finally:
    t.close()

Transfer all files (not working):

import paramiko

source = r'/home/netcs/b/'
dest = r'/home/tein/c/'
hostname = '10.10.10.9'
port = 22 # default port for SSH
username = 'tein'
password = 'po'
for file in source:
    if file.endswith('.txt'):
       try:
          t = paramiko.Transport((hostname, port))
          t.connect(username=username, password=password)
          sftp = paramiko.SFTPClient.from_transport(t)
          sftp.put(source, dest)
       finally:
          t.close()
       break
    else:
        print('No txt file found')

I have files in b/: enter image description here

But the script's output is:

no txt file found
no txt file found
no txt file found

Solution

  • Your code never reads the local directory. Your for loop iterates characters in the '/home/netcs/b/' string, not files in the /home/netcs/b/ folder.

    • For listing files in a folder, use os.listdir:
      How do I list all files of a directory?

      Also the os.listdir returns filenames only, so you have to combine them with the source when calling SFTPClient.put.

    • Similarly the remotepath argument of SFTPClient.put must also be a full file path.

    • You do not want to break after the first found file

    • Other issue is that the print('No txt file found') is misplaced. You will print that for every file that does not have .txt extension.

    files = os.listdir(source)
    for file in files:
        if file.endswith('.txt'):
           try:
              t = paramiko.Transport((hostname, port))
              t.connect(username=username, password=password)
              sftp = paramiko.SFTPClient.from_transport(t)
              sftp.put(os.path.join(source, file), dest + "/" + file)
           finally:
              t.close()
    

    For a recursive upload, see:
    Python pysftp put_r does not work on Windows