2
\$\begingroup\$

I made a Flask app that consists of 3 pages.

  • Index: Indexes to the 2 pages
  • SubnetOverview: SSH's into the server and executes ifconfig, then returns the output to a webpage.
  • AddSubnet: Has a HTML form where the administrator can fill in the desired VLAN id and subnet. This gets added to the netplan file and netplan apply gets executed to apply the changes.

    #Flask app that interacts with a router running on a virtual machine, enbales administrator to list current network interfaces and make a new subinterface via SSH.

from flask import Flask, render_template, request, redirect import paramiko import ssl app = Flask(__name__) context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) context.load_cert_chain('certificates/cert.pem', 'certificates/key.pem') SERVER_IP = "192.168.0.80" SERVER_USERNAME = "root" SERVER_PASSWORD = "secret123" SERVER_PORT = 22 SERVER_IFCONFIG = "/sbin/ifconfig" @app.route('/') def index(): return render_template('index.html') @app.route('/SubnetOverview') def SubnetOverview(): #Try to SSH into the server and execute the command client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(SERVER_IP, port=SERVER_PORT, username=SERVER_USERNAME, password=SERVER_PASSWORD) stdin, stdout, stderr = client.exec_command(SERVER_IFCONFIG, get_pty=True) output = stdout.readlines() output = ''.join(output) output = output.replace("\r\n", "<br />") client.close() return render_template('SubnetOverview.html', ssh_output=output) @app.route('/AddSubnet', methods = ['POST', 'GET']) def AddSubnet(): if request.method == 'POST': #Getting the data from the HTML form formdata = request.form.to_dict() vlanid = formdata.get('vlanid') address = formdata.get('address') command = " vlan" + vlanid + ":\n id: " + vlanid + "\n link: eth0\n addresses: [ \"" + address + "\" ]\n" #Opening an SFTP connection transport = paramiko.Transport((SERVER_IP, SERVER_PORT)) transport.connect(username=SERVER_USERNAME, password=SERVER_PASSWORD) sftp = paramiko.SFTPClient.from_transport(transport) file=sftp.file('/etc/netplan/01-network-manager-all.yaml', "a", -1) file.write(command) file.flush() SERVER_COMMAND = "sudo netplan apply" sftp.close() transport.close() #Opening SSH connection to send a command that apply's the config client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(SERVER_IP, port=SERVER_PORT, username=SERVER_USERNAME, password=SERVER_PASSWORD) stdin, stdout, stderr = client.exec_command(SERVER_COMMAND, get_pty=True) client.close() return redirect("/SubnetOverview") return render_template('AddSubnet.html') if __name__ == "__main__": app.run(host='0.0.0.0', port=443, ssl_context=context)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.