57 lines
1.7 KiB
Python
57 lines
1.7 KiB
Python
import subprocess
|
|
import common.color_log as color_log
|
|
import shutil
|
|
import os
|
|
import shlex
|
|
|
|
|
|
class SSHHandler:
|
|
def __init__(self):
|
|
pass
|
|
|
|
|
|
def _get_remote_command(self, instance, cmd):
|
|
"""Generate SSH command for remote execution."""
|
|
host = instance["host"]
|
|
ssh_settings = instance.get("ssh", {})
|
|
ssh_user = ssh_settings.get("user", "root")
|
|
ssh_key_path = ssh_settings.get("key_path")
|
|
|
|
local_host = host in ["localhost", "127.0.0.1"]
|
|
|
|
if not local_host:
|
|
if not ssh_key_path:
|
|
return f"ssh -t {ssh_user}@{host} 'sudo -s bash -c \"{cmd}\"'"
|
|
else:
|
|
return f"ssh -i {ssh_key_path} {ssh_user}@{host} 'sudo -s bash -c \"{cmd}\"'"
|
|
return cmd
|
|
|
|
def _execute_command(self, cmd, instance_name):
|
|
"""Execute a shell command and handle errors."""
|
|
try:
|
|
color_log.Show("INFO", f"Executing command: {cmd}")
|
|
result = subprocess.run(
|
|
cmd, shell=True, check=True, capture_output=True, text=True
|
|
)
|
|
|
|
# Print the output if there is any
|
|
if result.stdout:
|
|
print(result.stdout.strip())
|
|
if result.stderr:
|
|
print(result.stderr.strip())
|
|
|
|
color_log.Show("OK", f"Command executed successfully for {instance_name}")
|
|
return result.stdout
|
|
except subprocess.CalledProcessError as e:
|
|
# Print the error output
|
|
if e.stdout:
|
|
print(e.stdout.strip())
|
|
if e.stderr:
|
|
print(e.stderr.strip())
|
|
|
|
color_log.Show(
|
|
"FAILED",
|
|
f"Error performing git operation for {instance_name}: {e}",
|
|
)
|
|
raise
|