Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know current working directory in sftp from python

I had connected to sftp with some details to fetch some files with paramiko from python and code is below

import paramiko
import os
import ftplib

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy( paramiko.AutoAddPolicy() )
ssh.connect('sftp.example.com', username='user', password='pass')
ftp = ssh.open_sftp()
files = ftp.listdir()
print files,"----< Total files"
print ftp.cwd(),"---< Current working diectory"

for feedFile in files:
    if feedFile == 'LifeBridge':
        ftp.chdir(feedFile)

Result

['Emerson', 'Lehighvalley', 'LifeBridge', 'stmaryct'] ----< Total files

File "test_sftp.py", line 11, in <module>
    print ftp.cwd()   ---< Current working diectory
AttributeError: 'SFTPClient' object has no attribute 'cwd'

here what i am doing is

  1. Trying to find the current working directory of sftp

  2. There is a list of files above which i got as a result for printing files, i am trying to check whether they are folders or files, If they are folders i want to enter in to LifeBridge folder

Finally can anyone let me know the following

  1. how to check the current working directory of sftp
  2. how to check whether result from the above list is a file or a folder
like image 593
Shiva Krishna Bavandla Avatar asked Jan 16 '23 13:01

Shiva Krishna Bavandla


1 Answers

You are looking for the .getcwd() method instead:

Return the "current working directory" for this SFTP session, as emulated by paramiko. If no directory has been set with chdir, this method will return None.

So at the start of your session, if you need the current working dir, try a .chdir('.') (change to current directory) first.

The .listdir() method only returns names of items in the directory. If you need more information about those files, you'd need to use the .listdir_attr() method instead, it returns a list of SFTPAttributes instances.

An SFTPAttributes instance tells you what mode the file has, through the .st_mode attribute. Use the stat.S_ISDIR(mode) function to test if the file is a directory.

like image 113
Martijn Pieters Avatar answered Jan 25 '23 23:01

Martijn Pieters