I have successfully run this script on development, but on production the file structure is slightly difference and I am getting the 'FileNotFoundError: Errno 2 error No such file' error code.
When I use the root login, I believe I land on this directory:
/root
The directory I need to work from is:
/BackupStorage/Test/Here
I believe I'm getting the error because my session is trying to run from the /root
directory. How do I change directory to /BackupStorage/Test/Here
? Or am I completely wrong?
local_path = r'C:\Data\Scripts\Trial\Test\Here'
remote_path = f'/BackupStorage/Test/Here'
hostname = 'hostname1'
password = 'password123'
username = 'root'
port = 22
print(f'Connecting to {hostname} ...')
session = paramiko.Transport((hostname, 22))
session.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(session)
print(f'Connected to {hostname} - Remote Session Opened')
latest_time = -1
latest = None
# Below for loop finds latest sub-directory
for file_attr in sftp.listdir_attr(path=remote_path):
if stat.S_ISDIR(file_attr.st_mode) and file_attr.st_mtime > latest_time:
latest_time = file_attr.st_mtime
latest = file_attr.filename
# Below for loop finds the .zip file within latest sub-directory
for file_attr in sftp.listdir_attr(path=f'{remote_path}/{latest}'):
if file_attr.filename.endswith('.zip'):
sftp.get(
f'{remote_path}/{latest}/{file_attr.filename}',
f'{local_path}\{file_attr.filename}'
)
print(f'Most recent {branch_name} file successfully retrieved.')
session.close
print('Remote Session Closed.')
Use SFTPClient.chdir
:
sftp.chdir(path)
Or simply use absolute paths or correct relative paths to the home with other methods.