27
27
import socket
28
28
from websiteFunctions .models import NormalBackupJobs , NormalBackupJobLogs
29
29
from boto3 .s3 .transfer import TransferConfig
30
+ import traceback
30
31
31
32
try :
32
33
from s3Backups .models import BackupPlan , BackupLogs
@@ -1396,6 +1397,7 @@ def SendTORemote(FileName, RemoteBackupID):
1396
1397
RemoteBackupOBJ = RemoteBackupConfig .objects .get (pk = RemoteBackupID )
1397
1398
config = json .loads (RemoteBackupOBJ .config )
1398
1399
HostName = config ['Hostname' ]
1400
+ Port = config .get ('Port' , 22 )
1399
1401
Username = config ['Username' ]
1400
1402
Password = config ['Password' ]
1401
1403
Path = config ['Path' ]
@@ -1405,14 +1407,28 @@ def SendTORemote(FileName, RemoteBackupID):
1405
1407
ssh .set_missing_host_key_policy (paramiko .AutoAddPolicy ())
1406
1408
1407
1409
# Connect to the server using the private key
1408
- ssh .connect (HostName , username = Username , password = Password )
1410
+ ssh .connect (HostName , port = Port , username = Username , password = Password )
1411
+
1412
+ # Create directory and wait for the command to complete
1413
+ stdin , stdout , stderr = ssh .exec_command (f'mkdir -p { Path } ' )
1414
+ stdout .read () # Wait for command completion
1415
+
1409
1416
sftp = ssh .open_sftp ()
1410
- ssh .exec_command (f'mkdir -p { Path } ' )
1411
1417
1412
1418
if os .path .exists (ProcessUtilities .debugPath ):
1413
- logging .writeToFile (f"Filename: { FileName } , Path { Path } /{ FileName .split ('/' )[- 1 ]} . [SendTORemote]" )
1419
+ logging .writeToFile (f"Filename: { FileName } , Path { Path } /{ FileName .split ('/' )[- 1 ]} [SendTORemote]" )
1414
1420
1415
- sftp .put (FileName , f"{ Path } /{ FileName .split ('/' )[- 1 ]} " )
1421
+ try :
1422
+ sftp .put (FileName , f"{ Path } /{ FileName .split ('/' )[- 1 ]} " )
1423
+ except FileNotFoundError :
1424
+ # Double check if directory exists by explicitly creating it via SFTP
1425
+ try :
1426
+ sftp .mkdir (Path )
1427
+ except IOError :
1428
+ # Directory may already exist, which would cause an error
1429
+ pass
1430
+ # Try the transfer again
1431
+ sftp .put (FileName , f"{ Path } /{ FileName .split ('/' )[- 1 ]} " )
1416
1432
1417
1433
# sftp.get(str(remotepath), str(loaclpath),
1418
1434
# callback=self.UpdateDownloadStatus)
@@ -1432,11 +1448,13 @@ def SendTORemote(FileName, RemoteBackupID):
1432
1448
# with sftp.cd(Path):
1433
1449
# sftp.put(FileName)
1434
1450
1435
-
1451
+ # Close connections
1452
+ sftp .close ()
1453
+ ssh .close ()
1436
1454
1437
1455
except BaseException as msg :
1438
- print ('%s. [SendTORemote]' % (str ( msg )))
1439
- logging .writeToFile ('%s. [SendTORemote]' % (str ( msg )))
1456
+ print ('%s. [SendTORemote]' % (traceback . format_exc ( )))
1457
+ logging .writeToFile ('%s. [SendTORemote]' % (traceback . format_exc ( )))
1440
1458
1441
1459
@staticmethod
1442
1460
def SendToS3Cloud (FileName , RemoteBackupCofigID , backupID , scheduleID ):
0 commit comments