bug fix: use paramiko for ssh operations

This commit is contained in:
usmannasir
2024-02-11 14:42:16 +05:00
parent 9de6243c26
commit 670e46c309
6 changed files with 63 additions and 21 deletions

View File

@@ -1,6 +1,9 @@
#!/usr/local/CyberCP/bin/python
import os.path
import sys
import paramiko
sys.path.append('/usr/local/CyberCP')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "CyberCP.settings")
import django
@@ -509,6 +512,7 @@ class IncScheduler(multi.Thread):
destinationConfig = json.loads(backupjob.owner.config)
currentTime = time.strftime("%m.%d.%Y_%H-%M-%S")
print(destinationConfig['type'])
if destinationConfig['type'] == 'local':
@@ -620,18 +624,51 @@ Automatic backup failed for %s on %s.
backupjob.config = json.dumps(jobConfig)
backupjob.save()
else:
if jobConfig[IncScheduler.frequency] == type:
import subprocess
import shlex
print(jobConfig[IncScheduler.frequency])
finalPath = '%s/%s' % (destinationConfig['path'].rstrip('/'), currentTime)
command = "ssh -o StrictHostKeyChecking=no -p " + destinationConfig[
'port'] + " -i /root/.ssh/cyberpanel " + destinationConfig['username'] + "@" + \
destinationConfig[
'ip'] + " mkdir -p %s" % (finalPath)
subprocess.call(shlex.split(command))
# import subprocess
# import shlex
# command = "ssh -o StrictHostKeyChecking=no -p " + destinationConfig[
# 'port'] + " -i /root/.ssh/cyberpanel " + destinationConfig['username'] + "@" + \
# destinationConfig[
# 'ip'] + " mkdir -p %s" % (finalPath)
# subprocess.call(shlex.split(command))
### improved paramiko code
private_key_path = '/root/.ssh/cyberpanel'
# Create an SSH client
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# Load the private key
private_key = paramiko.RSAKey.from_private_key_file(private_key_path)
# Connect to the server using the private key
try:
ssh.connect(destinationConfig['ip'], port=int(destinationConfig['port']), username=destinationConfig['username'], pkey=private_key)
except BaseException as msg:
NormalBackupJobLogs(owner=backupjob, status=backupSchedule.INFO,
message=f'Failed to make sftp connection {str(msg)}').save()
print(str(msg))
continue
# Execute the command to create the remote directory
command = f'mkdir -p {finalPath}'
stdin, stdout, stderr = ssh.exec_command(command)
# Wait for the command to finish and check for any errors
stdout.channel.recv_exit_status()
error_message = stderr.read().decode('utf-8')
print(error_message)
if error_message:
NormalBackupJobLogs(owner=backupjob, status=backupSchedule.INFO,
message=f'Error while creating directory on remote server {error_message.strip()}').save()
continue
else:
pass
### Check if an old job prematurely killed, then start from there.
# try:
@@ -1550,5 +1587,6 @@ def main():
ib.join()
if __name__ == "__main__":
main()