cmvr-wms/scripts/deploy/server_transport.py

51 lines
2.2 KiB
Python
Raw Normal View History

"""Interactive SSH/SFTP transport restricted to the authorized deployment host.
The password is requested without echo. Commands and artifact paths are supplied
one at a time as JSON on stdin; there is no password stored in this file.
"""
import getpass
import json
import os
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / '.codex-tmp' / 'deploy-python'))
import paramiko
client = paramiko.SSHClient()
client.load_host_keys(str(Path.home() / '.ssh' / 'known_hosts'))
client.set_missing_host_key_policy(paramiko.RejectPolicy())
client.connect('192.168.28.10', username='lxl', password=getpass.getpass('Server password: '),
look_for_keys=False, allow_agent=False, timeout=15)
print(json.dumps({'connected': 'lxl@192.168.28.10'}), flush=True)
try:
for line in sys.stdin:
try:
request = json.loads(line)
action = request['action']
if action == 'exit':
break
if action == 'run':
stdin, stdout, stderr = client.exec_command(request['command'], timeout=request.get('timeout', 60))
stdin.close()
result = {'stdout': stdout.read().decode('utf-8', 'replace'),
'stderr': stderr.read().decode('utf-8', 'replace'),
'exit': stdout.channel.recv_exit_status()}
elif action == 'upload':
with client.open_sftp() as sftp:
sftp.put(request['local'], request['remote'])
if 'mode' in request:
sftp.chmod(request['remote'], int(request['mode'], 8))
result = {'uploaded': request['remote']}
elif action == 'download':
with client.open_sftp() as sftp:
sftp.get(request['remote'], request['local'])
result = {'downloaded': request['local']}
else:
raise ValueError('Unsupported action')
print(json.dumps(result, ensure_ascii=False), flush=True)
except Exception as error:
print(json.dumps({'error': str(error)}, ensure_ascii=False), flush=True)
finally:
client.close()