Implement lxc container ssh logic

os-repl
root 2022-11-26 22:24:31 +00:00
parent 18908d3f64
commit 6fe9fbfc3c
3 changed files with 21 additions and 9 deletions

View File

@ -5,16 +5,18 @@ import ipaddress
lxd_client = pylxd.client.Client()
def create_instance(container_name: str):
def create_instance(container_name: str, instance_password: str):
config = {'name': container_name, 'source':
{'type': 'image', "mode": "pull", "server": "https://cloud-images.ubuntu.com/daily", "protocol": "simplestreams",
'alias': 'lts/amd64'}, 'config': {'security.nesting': 'true'}}
instance = lxd_client.instances.create(config, wait=True)
instance.start(wait=True)
while type(ipaddress.ip_address(instance.state().network['eth0']['addresses'][0]['address'])) != ipaddress.IPv4Address:
time.sleep(0.1)
setup_ssh(container_name, instance_password)
return instance.state().network['eth0']['addresses'][0]
@ -26,8 +28,20 @@ def destroy_instance(container_name: str):
return True
def execute_command(container_name: str, command: str):
def execute_command(container_name: str, command: list, stdin_payload=None):
instance = lxd_client.instances.get(container_name)
result_tuple = instance.execute([command])
result_tuple = instance.execute(command, stdin_payload=stdin_payload)
return result_tuple
def setup_ssh(container_name: str, instance_password: str):
execute_command(container_name,
["sed", "-i", "s/PasswordAuthentication no/PasswordAuthentication yes/", "/etc/ssh/sshd_config"])
execute_command(container_name,
["sed", "-i", "s/#PermitRootLogin prohibit-password/PermitRootLogin yes/",
"/etc/ssh/sshd_config"])
execute_command(container_name, ["systemctl", "restart", "sshd"])
execute_command(container_name, ["passwd", "root"], stdin_payload=f"{instance_password}\n{instance_password}")
return True

View File

@ -1,6 +1,5 @@
import logging
import time
import paramiko
import sshim_patch as sshim
import lxd_interface

View File

@ -8,8 +8,7 @@ import lxd_interface
import threading
import logging
logging.basicConfig(level='DEBUG')
logger = logging.getLogger()
logger = logging.getLogger(__name__)
def expect(self, line, echo=True) -> str:
@ -68,7 +67,7 @@ def check_auth_none(self, username):
def check_auth_password(self, username, password):
print(os.environ["ssh-username"], os.environ["ssh-password"])
logger.debug(os.environ["ssh-username"])
if username == os.environ["ssh-username"] and password == os.environ["ssh-password"]:
return paramiko.AUTH_SUCCESSFUL
return paramiko.AUTH_FAILED
@ -89,7 +88,7 @@ class Runner(threading.Thread):
self.channel.settimeout(None)
def run(self) -> None:
vm_ip = lxd_interface.create_instance(self.instance_name)
vm_ip = lxd_interface.create_instance(self.instance_name, self.instance_password)
with paramiko.SSHClient() as ssh_client:
ssh_client.connect(vm_ip, username='root', passphrase=self.instance_password)