1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
from http.server import BaseHTTPRequestHandler, HTTPServer
from string import Template
import time
import psycopg2
import psycopg2.extras
import sys
import os
def main():
#
# Settings
#
settings = dict(
db = dict(
user = 'bootstrap',
password = 'asdf',
dbname = 'bootstrap',
host = 'localhost'
),
http = dict(
# host = 'localhost',
host = '10.0.30.131',
port = 8080
)
)
#
# Connect to DB
#
try:
connect_params = ("dbname='%s' user='%s' host='%s' password='%s'" % (settings['db']['dbname'], settings['db']['user'], settings['db']['host'], settings['db']['password']))
conn = psycopg2.connect(connect_params)
# cur = conn.cursor()
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
cur.execute("""SELECT * from switches""")
rows = cur.fetchall()
print ("\nSwitches in DB during server_http.py startup:")
for row in rows:
print (" --> %s, connected to %s port %s" % (row['hostname'], row['distro_name'], row['distro_phy_port']))
except (psycopg2.DatabaseError, psycopg2.OperationalError) as e:
print ('Error: %s' % e)
sys.exit(1)
except:
print(sys.exc_info()[0])
sys.exit(1)
def template_get(model):
return open('junos-bootstrap/httpd/' + model + '.template').read()
def template_parse(template_src, hostname):
cur.execute("SELECT * FROM switches WHERE hostname = '%s'" % hostname)
if(cur.rowcount == 1):
row = cur.fetchall()[0]
d={
'hostname': row['hostname'],
'distro_name': row['distro_name'],
'distro_phy_port': row['distro_phy_port'],
'mgmt_addr': row['mgmt_addr'],
'mgmt_cidr': row['mgmt_cidr'],
'mgmt_gw': row['mgmt_gw'],
'mgmt_vlan': row['mgmt_vlan']
}
return Template(template_src).safe_substitute(d)
else:
return False
class httpd(BaseHTTPRequestHandler):
def do_GET(self):
print('[%s] [%s] Incoming HTTP GET URI:%s ' % (self.client_address[0], time.asctime(), self.path))
# Client asks for the config file
if '/tg15-edge/' in self.path:
hostname = self.path.split('/tg15-edge/')[1]
if len(hostname) > 0:
print('[%s] --> Hostname "%s" accepted, fetching info from DB' % (self.client_address[0], hostname))
template_parsed = template_parse(template_get('ex2200'), hostname)
if template_parsed:
print('[%s] --> Template successfully populated' % self.client_address[0])
print('[%s] --> Sending response to client' % self.client_address[0])
self.send_response(200)
self.send_header("Content-type", "text/plain")
self.end_headers()
self.wfile.write(bytes(template_parsed, "utf-8"))
print('[%s] --> Success - %s bytes sent to client' % (self.client_address[0], len(template_parsed)))
else:
print('[%s] --> Error - template could not be populated' % self.client_address[0])
else:
print('[%s] --> Rejected due to missing hostname' % self.client_address[0])
# Client asks for a file download - most likely a JunOS file
elif '/files/' in self.path:
# It seems that "http.server" escapes nastiness from the URL - ("/files/../../../root_file" => "/files/root_file")
requested_file = self.path.split('/files/')[1]
files_dir = 'junos-bootstrap/httpd/files/'
print('[%s] --> File request for "%s" in "%s"' % (self.client_address[0], requested_file, files_dir))
if os.path.isfile(files_dir + requested_file):
print('[%s] --> File found' % self.client_address[0])
try:
f = open(files_dir + requested_file)
self.send_response(200)
self.send_header('Content-type', 'application/x-gzip') # correct content type for tar.gz
self.end_headers()
print('[%s] --> File transfer started' % self.client_address[0])
f = open(files_dir + requested_file, 'rb')
self.wfile.write(f.read())
f.close()
print('[%s] --> File transfer completed' % self.client_address[0])
return
except IOError:
self.send_error(404,'File Not Found: %s' % self.path)
print('[%s] --> ERROR 404 - File not found' % self.client_address[0])
pass
except:
print('[%s] --> Generic error during file reading' % self.client_address[0])
pass
else:
print('[%s] --> File request rejected due to nonexisting file' % self.client_address[0])
else:
print('[%s] --> rejected due to bad path' % self.client_address[0])
# silence stderr from BaseHTTPRequestHandler
# source: http://stackoverflow.com/questions/3389305/how-to-silent-quiet-httpserver-and-basichttprequesthandlers-stderr-output
def log_message(self, format, *args):
return
httpd_instance = HTTPServer((settings['http']['host'], settings['http']['port']), httpd)
print("\n[%s] Server Starts - %s:%s" % (time.asctime(), settings['http']['host'], settings['http']['port']))
try:
httpd_instance.serve_forever()
except KeyboardInterrupt:
pass
httpd_instance.server_close()
print("\n\n[%s] HTTP Server stopped\n" % time.asctime())
if __name__ == "__main__":
main()
|