59 lines
2.2 KiB
Python
59 lines
2.2 KiB
Python
import paramiko
|
|
from rest_framework.response import Response
|
|
from rest_framework.decorators import api_view
|
|
from app.models import Ssh
|
|
|
|
#=============================================================================
|
|
def executecmd(host, port, username, password, path, cmd):
|
|
ssh_client = paramiko.SSHClient()
|
|
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
|
ssh_client.connect(hostname=host, username=username, password=password, port=port)
|
|
command = cmd if path==None else "cd {} ; {}".format(path, cmd)
|
|
try:
|
|
stdin,stdout,stderr=ssh_client.exec_command(command, get_pty=True)
|
|
output = stdout.readlines()
|
|
ssh_client.close()
|
|
return {'success': True, 'output': output}
|
|
except Exception as e:
|
|
print(e)
|
|
ssh_client.close()
|
|
return {'success': False, 'output': e}
|
|
|
|
#=============================================================================
|
|
def container_info(result):
|
|
rows = []
|
|
for i, val in enumerate(result):
|
|
if i>0:
|
|
arr = val.split(' ')
|
|
arr = [o for o in arr if o != '']
|
|
row = {'container': arr[0], 'image': arr[1], 'command': arr[2], 'created': arr[3], 'status': arr[4], 'port': arr[5], 'name': arr[6]}
|
|
rows.append(row)
|
|
return rows
|
|
|
|
#=============================================================================
|
|
def disk_info(result):
|
|
rows = []
|
|
for i, val in enumerate(result):
|
|
if i>0:
|
|
arr = val.split(' ')
|
|
arr = [o for o in arr if o != '']
|
|
percentage = int(arr[4].replace('%', '')) / 100
|
|
row = {'file': arr[0], 'size': arr[1], 'used': arr[2], 'avail': arr[3], 'use%': arr[4], 'use': percentage, 'mounted': arr[5]}
|
|
rows.append(row)
|
|
return rows
|
|
|
|
#=============================================================================
|
|
@api_view(['POST'])
|
|
def execute_command(request):
|
|
data = request.data
|
|
ssh = Ssh.objects.get(pk=data['ssh'])
|
|
path = data['path'] if 'path' in data else None
|
|
cmd = data['cmd']
|
|
format = data['format'] if 'format' in data else None
|
|
result = executecmd(ssh.host, ssh.port, ssh.username, ssh.password, path, cmd)
|
|
output = None
|
|
if format == 'diskinfo':
|
|
output = disk_info(result['output'])
|
|
elif format == 'containerinfo':
|
|
output = container_info(result['output'])
|
|
return Response(output or result) |