Commit e6244479 authored by Alban Bruder's avatar Alban Bruder

Update reset-ws cmd

parent 3c276634
......@@ -4,6 +4,26 @@ import subprocess
import json
import fcntl
import struct
from lib import confirm_prompt
import log
import os
logger = log.get_logger()
logger.setLevel(log.INFO)
UBUNTU_ISO = "https://releases.ubuntu.com/20.04/ubuntu-20.04.1-live-server-amd64.iso"
NOCLOUD_SOURCE = "https://git.webis.de/code-generic/code-kickstart-config/-/raw/master/ubuntu-20.04/"
GRUB_TEMPLATE = """#!/bin/sh
menuentry "Install Ubuntu 20.04" {{
search --no-floppy --fs-uuid --set=root {uuid}
set isofile="/root/ubuntu.iso"
loopback loop $isofile
linux (loop)/casper/vmlinuz boot=casper iso-scan/filename=$isofile noprompt noeject --- autoinstall ds=nocloud-net;s={nocloud} {parameters}
initrd (loop)/casper/initrd
}}
"""
def salt(target, command):
......@@ -43,13 +63,7 @@ def get_mac(ifname):
return ''.join(['%02x:' % char for char in info[18:24]])[:-1]
@click.group()
def reset_ws():
"""Commands to reset a workstation."""
@reset_ws.command(short_help='Print info')
def info():
def get_info():
data = dict()
data["hostname"] = socket.getfqdn()
data["address"] = socket.gethostbyname(data["hostname"])
......@@ -60,14 +74,118 @@ def info():
data["address"] = get_ip_address(interface)
data["mac"] = get_mac(interface)
return data
def get_uuid(path):
process = subprocess.Popen("blkid -s UUID -o value $(df {path} | sed 1d | cut -d' ' -f1)".format(
path="/root"), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
return stdout.decode('utf8').strip()
click.echo(json.dumps(data))
def get_password(username):
process = subprocess.Popen(
"cat /etc/shadow | grep '{}' | cut -d':' -f2".format(username), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
return stdout.decode('utf8').strip() or None
def stringify_parameters(parameters, seperator='=', prefix=''):
filtered = {k: v for (k, v) in parameters.items() if v != False}
return ' '.join([prefix + seperator.join(x) for x in filtered.items()])
@click.group()
def reset_ws():
"""Commands to reset a workstation."""
@reset_ws.command(short_help='Print info')
def info():
click.echo(json.dumps(get_info()))
@reset_ws.command(short_help='Reset a workstation local')
@click.option('-f', '--force', is_flag=True, default=False, help='Always yes.')
def local(force):
click.echo("Running locally")
@click.option('--report', help='reporting endpoint')
@click.option('--username', default="webis")
@click.option('--password')
@click.option('--hostname')
@click.option('--address')
@click.option('--gateway')
@click.option('--interface')
@click.option('--mac')
def local(force, report, username, password, hostname, address, gateway, interface, mac):
global UBUNTU_ISO
# ensure script has root permissions
""" if os.getuid() != 0:
logger.error("Command must run as root.")
return """
# try to extract the password
if not password:
password = get_password(username)
# exit if extraction failed
if not password:
logger.error(
"Could not extract password for user '{}'.".format(username))
return
info = get_info()
if not hostname:
hostname = info["hostname"]
if not address:
address = info["address"]
if not gateway:
gateway = info["gateway"]
if not interface:
interface = info["interface"]
if not mac:
mac = info["mac"]
if report:
parameters['report'] = report
logger.info("Ubuntu will be reinstalled with the following settings:")
click.echo("Hostname: {}".format(hostname))
click.echo("IP address: {}".format(address))
click.echo("Gateway: {}".format(gateway))
click.echo("Interface: {}".format(interface))
click.echo("MAC: {}".format(mac))
click.echo("Username: {}".format(username))
if not force and not confirm_prompt("Are you sure you want to reset this workstation?"):
logger.error("Aborted.")
return
logger.info("Downloading Ubuntu image. Please wait...")
subprocess.Popen(
"wget --output-document /root/ubuntu.iso {}".format(UBUNTU_ISO), shell=True).wait()
logger.info("Download complete.")
logger.info("Updating bootloader...")
uuid = get_uuid("/root")
parameters = {
"username": username,
"password": password,
"hostname": hostname,
"address": address,
"interface": interface,
"gateway": gateway,
"mac": mac
}
click.echo(GRUB_TEMPLATE.format(
nocloud=NOCLOUD_SOURCE, uuid=uuid, parameters=stringify_parameters(parameters)))
@reset_ws.command(short_help='Reset a workstation remotly')
......@@ -75,6 +193,13 @@ def local(force):
@click.option('-f', '--force', is_flag=True, default=False, help='Always yes.')
def remote(target, force):
click.echo("Running on " + target)
minions = json.loads(salt_cmd_run(target, "webis reset-ws info"))
print(minions)
minions = {minion: json.loads(data) for (minion, data) in json.loads(salt_cmd_run(
target, "export LC_ALL=C.UTF-8;export LANG=C.UTF-8;webis ut reset-ws info")).items()}
if not force:
print(minions)
if not confirm_prompt("Continue?"):
return
return
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment