예제 #1
0
    def POST(self):
        global error_msg

        if not been_through_subconfig:
            self.logger.info('tried Net POST....back to /su')
            raise web.seeother('/su')

        self.logger.debug('in Net POST')
        save_last_get('Net POST')
        form = web.input()
        error_msg = ''
        outdata = []

        for f in ['Static IP', 'Netmask', 'Gateway', 'DNS Nameservers', 'SSID', 'Password', 'Hidden SSID', 'UPnP Refresh Rate', 'Station Name', 'Station Port', 'External Station Port', 'Remote Substation Access Port', 'Extender SSID', 'Extender Password']:
            if f in form:
                form[f] = form[f].strip()

        # use hidden SSID if provided
        using_hidden_ssid = False
        if 'Hidden SSID' in form and form['Hidden SSID'] != '':
            using_hidden_ssid = True
            form['SSID'] = form['Hidden SSID']
            self.logger.info('using Hidden SSID')

        use_eth0 = 'SSID' not in form or form['SSID'] == 'ethernet'

        if gv.sd['remote_radio_substation']:
            form['SSID'] = 'using radio'
            net = 'radio'
        elif not use_eth0:
            net = 'wlan0'
        else:
            form['SSID'] = 'using eth0'
            net = 'eth0'

        self.logger.debug('in Net POST: ' + form['SSID'])
        gv.sd['light_ip'] = 1
        try:
            if form['DNS Nameservers'][0:1] == 'X' and \
                   (len(form['DNS Nameservers']) == 1 or form['DNS Nameservers'][1:2] == ' '):
                gv.sd['light_ip'] = 0 # hack to disable blinking led on startup with leading X in nameservers
                form['DNS Nameservers'] = form['DNS Nameservers'][1:].strip()
        except:
            pass

        if not gv.sd['remote_radio_substation'] and 'Use DHCP' in form:
            for d in ['DNS Search', 'DNS Nameservers']:
                if d in form and form[d] != '':
                    error_msg = 'Error:  "' + d + '" must be blank with "Use DHCP".'
                    raise web.seeother('/cn') # back to form

        pass_len = 0 if 'Extender Password' not in form else len(form['Extender Password'])
        if 'Extender SSID' in form and form['Extender SSID'] != '':
            if pass_len < 8 or pass_len > 63:
                error_msg = 'Error:  "Extender Password" must be between 8 and 63 characters.'
                raise web.seeother('/cn') # back to form
        else: # force data to be present and safe
            form['Extender SSID'] = ''
            form['Extender Password'] = ''

        pass_len = 0 if 'Password' not in form else len(form['Password'])
        if not gv.sd['remote_radio_substation'] and not using_eth0 and (pass_len < 8 or pass_len > 63):
            error_msg = 'Error:  "Password" must be between 8 and 63 characters.'
            raise web.seeother('/cn') # back to form

        if 'Station Name' in form:
            sn = validate_fqdn(form['Station Name'])
            if sn == 'Irricloud': # error condition
                error_msg = 'Error:  "Station Name" must have only letter and numbers.'
                raise web.seeother('/cn') # back to form
            elif len(sn) > 50 or len(sn) < 1:
                error_msg = 'Error:  "Station Name" must be at most 50 characters.'
                raise web.seeother('/cn') # back to form
            form['Station Name'] = sn

        for portn in ['Station Port', 'External Station Port', 'Remote Substation Access Port', 'UPnP Refresh Rate']:
            if portn in form:
                try:
                    port = int(form[portn])
                except:
                    error_msg = 'Error:  "' + portn + '" must be integer.'
                    raise web.seeother('/cn') # back to form
                if port < 0 or port > 65535:
                    error_msg = 'Error:  "' + portn + '" must be between 0 and 65535.'
                    raise web.seeother('/cn') # back to form
                if portn == 'Station Port' and port == 9080: # specially reserved for proxy
                    error_msg = 'Error:  "' + portn + '" cannot be 9080.'
                    raise web.seeother('/cn') # back to form

        try:
            drop = 0
            with open('/etc/network/interfaces','r') as infile:
                iface = infile.readlines()
            for line in iface:
                if 'dns-nameservers' in line:
                    continue # delete any old dns stuff
                did_iface_wlan0 = False
                if drop > 0:
                    drop -= 1
                    continue
                if 'iface ' + net + ' inet' in line:
                    if net == 'wlan0':
                        did_iface_wlan0 = True
                    if 'Use DHCP' in form:
                        self.logger.info('Using dhcp: ' + form['SSID'])
                        if 'static' in line:
                            drop = 3
                            line = 'iface ' + net + ' inet manual\n'
                    else:
                        self.logger.info('Using static ip: ' + form['Static IP'] + ' ' + form['Netmask'] + ' ' + form['Gateway'])
                        if 'static' in line:
                            drop = 3
                        outdata.append('iface ' + net + ' inet static\n')
                        outdata.append('        address ' + form['Static IP'] + '\n')
                        outdata.append('        netmask ' + form['Netmask'] + '\n')
                        line = '        gateway ' + form['Gateway'] +'\n'
                        outdata.append(line)
                        if 'DNS Nameservers' in form and form['DNS Nameservers'] != '':
                            line = '        dns-nameservers ' + form['DNS Nameservers'] +'\n'
                        else: # use gateway
                            line = '        dns-nameservers ' + form['Gateway'] +'\n'
                elif 'iface ' + 'wlan0' + ' inet' in line: # using eth0 or radio only, but need to clean up 10.0.0.1 entry
                    if 'static' in line:
                        drop = 3
                        line = 'iface ' + 'wlan0' + ' inet manual\n'
                        did_iface_wlan0 = True

                outdata.append(line)
                if did_iface_wlan0:
                    outdata.append('        wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf\n')

        except Exception as ex:
            self.logger.exception('Unexpected exception trying to configure network: ' + str(ex))
            raise web.seeother('/cn')

        if len(outdata) == 0:
            self.logger.error('Expected data in /etc/network/interfaces')
            raise web.seeother('/cn')

        self.logger.info('stopping daemons before updating network interfaces')
        stop_daemons()

        try:
            with open('/etc/network/interfaces','w') as outfile:
                outfile.writelines(outdata)

            # Do not let dhcpcd get a dhcp address (and dns info?) if we are using a static config
            if 'Use DHCP' in form:
                shutil.copy2('/etc/dhcpcd.conf.yeswlan0', '/etc/dhcpcd.conf')
            else:
                shutil.copy2('/etc/dhcpcd.conf.nowlan0', '/etc/dhcpcd.conf')

            # if we are going to broadcast our own ssid to extend reach, save ssid and password
            broad_wpa_info = wpa_passphrase(form['Extender SSID'], form['Extender Password'])
            if len(broad_wpa_info['ssid']) > 2 and broad_wpa_info['ssid'][0] == '"': # strip off quotes for hostapd.conf
                broad_wpa_info['ssid'] = broad_wpa_info['ssid'][1:len(broad_wpa_info['ssid'])-1]
            gv.sd['extender_ssid'] = broad_wpa_info['ssid']
            gv.sd['extender_psk'] = broad_wpa_info['psk']

            if not gv.sd['remote_radio_substation'] and not use_eth0:
                wpa_supp_lines = ['ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\n']
                wpa_supp_lines.append('update_config=1\n\n')
                if form['SSID'] != '' and form['Password'] != '':
                    wpa_info = wpa_passphrase(form['SSID'], form['Password'])
                    wpa_supp_lines.append('network={\n')
                    wpa_supp_lines.append('\tssid=' + wpa_info['ssid'] + '\n')
                    if using_hidden_ssid:
                        wpa_supp_lines.append('\tscan_ssid=1\n')
                    wpa_supp_lines.append('\tpsk=' + wpa_info['psk'] + '\n')
                    wpa_supp_lines.append('}\n')
                else:
                    self.logger.warning('missing ssid or password')

                with open('/etc/wpa_supplicant/wpa_supplicant.conf', 'w') as outfile:
                    outfile.writelines(wpa_supp_lines)

                # check if network connection was made
#                self.logger.debug('wpa_action stopping wlan0')
#                rc = subprocess.call(['wpa_action', 'wlan0', 'stop'])
#                self.logger.debug( 'wpa_action wlan0 stop return: ' + str(rc))
#                time.sleep(1)
#                self.logger.debug('ifup wlan0')
#                rc = subprocess.call(['ifup', 'wlan0'])
#                self.logger.debug( 'ifup return: ' + str(rc))
#                time.sleep(1)
#                rc = subprocess.call(['wpa_action', 'wlan0', 'reload'])
#                self.logger.debug( 'wpa_action wlan0 reload return: ' + str(rc))
#                time.sleep(1)
#                reset_networking()

            if True or 'Do not validate network connection' in form or network_up(net, self.logger):
                #successful network connection.   Finalize
                # copy the current versions to the save version
                cur_ip = get_ip(net)
                self.logger.info('success...cur_ip: ' + cur_ip)
                if gv.sd['enable_upnp']: # was enabled?  Then cleanup.  If network still points to 10.0.0.1 network cant cleanup!
                    deletes = []
                    if gv.sd['external_htp'] != 0:
                        deletes.append(gv.sd['external_htp'])
                    if gv.sd['remote_support_port'] != 0:
                        deletes.append(gv.sd['remote_support_port'])
                    if gv.sd['external_proxy_port'] != 0:
                        deletes.append(gv.sd['external_proxy_port'])
                    update_upnp(cur_ip, self.logger, deletes)
                gv.sd['enable_upnp'] = 1 if 'Enable UPnP' in form else 0
                if gv.sd['enable_upnp']:
                    if 'UPnP Refresh Rate' in form:
                        gv.sd['upnp_refresh_rate'] = int(form['UPnP Refresh Rate'])
                if 'Station Name' in form:
                    gv.sd['name'] = form['Station Name']
                    update_hostname(gv.sd['name'])
                if 'Station Port' in form:
                    gv.sd['htp'] = int(form['Station Port'])
                if gv.sd['master']:
                    gv.sd['master_ip'] = 'localhost' # update local master_port 
                    gv.sd['master_port'] == gv.sd['htp']
                else:
                    gv.sd['master_port'] = 0
                gv.sd['external_htp'] = int(form['External Station Port']) if 'External Station Port' in form else 0
                gv.sd['external_proxy_port'] = int(form['Remote Substation Access Port']) if 'Remote Substation Access Port' in form else 0
                jsave(gv.sd, 'sd')
                self.logger.info('success....copying back interfaces and wpa')
                try:
                    os.remove('/etc/resolv.conf')
                except:
                    pass
                shutil.copy('/etc/network/interfaces', '/etc/network/interfaces.save')
                shutil.copy('/etc/wpa_supplicant/wpa_supplicant.conf', '/etc/wpa_supplicant/wpa_supplicant.conf.save')
#                self.logger.info('success....enabling sip')
#                subprocess.call(['systemctl', 'enable', 'sip.service'])
##                subprocess.call(['update-rc.d', 'sip', 'enable'])
##                subprocess.call(['update-rc.d', 'sip', 'defaults'])
##                self.logger.info('disabling sip_net_finish')
#                subprocess.call(['systemctl', 'disable', 'sip_net_finish.service'])
##                subprocess.call(['update-rc.d', '-f', 'sip_net_finish', 'remove'])
#                light_ip(cur_ip)
                self.logger.info('rebooting')
                subprocess.call(['reboot', '-h'])
                exit(0)
            else:
                raise Exception('Network Inaccessible')

        except Exception as ex:
            self.logger.exception('failed: ' + str(ex))
            # restore saved /etc/network/interfaces and wpa_suplicant.conf
            self.logger.info('restore network files and exit.  Exception: ' + str(ex))
            shutil.move('/etc/network/interfaces.save', '/etc/network/interfaces')
            shutil.move('/etc/wpa_supplicant/wpa_supplicant.conf.save', '/etc/wpa_supplicant/wpa_supplicant.conf')
            exit(1)

        self.logger.error('sip_net_config: should have exited above.  sip_monitor will restart')
        raise web.seeother('/cn')
예제 #2
0
    def GET(self):
        qdict = web.input()
        try:
            ddict = json.loads(qdict['data'])
        except:
            raise web.unauthorized()

        force_reboot = False
        info = {}
        for l in ['wlog', 'elog', 'slog', 'evlog']:
            if l in ddict and ddict[l]:
                end = ddict['end_date']
                days = ddict['days_before']
                start_after = ddict['start_after']
                prefix = ''
                try:
                    if l in ['slog', 'evlog']:
                        prefix = 'sensors/' + gv.plugin_data['ld'][int(ddict['ldi'])]['name'] + '/logs/'
                except:
                    pass
                records = read_log(prefix+l, end, days, start_after)
                info[l] = records

        for dlog in ['dlogirricloud', 'dlogirricloud_monitor', 'dlogirricloud_net_config']:
            if dlog in ddict and ddict[dlog]:
                records = []
                try:
                    with gv.log_lock:
                        with open('./logs/' + dlog[4:] + '.out', 'r') as file:
                            records = file.readlines()
                except:
                    pass
                info[dlog] = []
                for r in records:
                    info[dlog].append(r)

        if 'lrun' in ddict and ddict['lrun']:
            info['lrun'] = gv.lrun

        if 'programs' in ddict:
            if ddict['programs'] == 1:
                info['programs'] = gv.pd
            else:
                gv.pd = ddict['programs']
                jsave(gv.pd, 'programs')
                info['programs'] = 1

        if 'ps' in ddict and ddict['ps']:
            info['ps'] = gv.ps

        if 'sbits' in ddict and ddict['sbits']:
            info['sbits'] = gv.sbits

        if 'srvals' in ddict and ddict['srvals']:
            info['srvals'] = gv.srvals

        if 'sensors' in ddict and 'ld' in gv.plugin_data:
            if ddict['sensors'] == 1:
                info['sensors'] = []
                try:
                    if 'ldi' not in ddict or int(ddict['ldi']) == -1:
                        info['sensors'] = gv.plugin_data['ld']
                    else:
                        info['sensors'] = gv.plugin_data['ld'][int(ddict['ldi'])]
                except:
                    pass
                info['sensboards'] = i2c.get_vsb_boards().keys()
                info['remotesensboards'] = get_remote_sensor_boards()
            else:
                try:
                    if 'ldi' not in ddict or int(ddict['ldi']) == -1:
                        gv.plugin_data['ld'] = ddict['sensors']
                    else:
                        gv.plugin_data['ld'][int(ddict['ldi'])] = ddict['sensors']
                except:
                    gv.plugin_data['ld'] = ddict['sensors']
                jsave(gv.plugin_data['ld'], 'sensors')
                info['sensors'] = 1

        if 'camera' in ddict and 'ca' in gv.plugin_data:
            if ddict['camera'] == 1:
                info['camera'] = gv.plugin_data['ca']
                if 'cai' in ddict and ddict['cai']:
                    info['cai'] = ''
                    if gv.plugin_data['ca']['enable_camera'] == 'on':
                        try:
                            with open('./static/images/camera.jpg', mode='rb') as file: # b is important -> binary
                                info['cai'] = base64.b64encode(file.read())
                        except:
                            pass
            else:
                gv.plugin_data['ca'] = ddict['camera']
                jsave(gv.plugin_data['ca'], 'camera')
                info['camera'] = 1

        if 'sd' in ddict:
            if ddict['sd'] == 1:
                sd = gv.sd.copy()
                del sd['substation_network']
                del sd['salt']
                del sd['password']
                del sd['pwd']
                del sd['enable_upnp'] # stuff from base configuration stays as was
                del sd['subnet_only_substations']
                del sd['external_proxy_port']
                kill_keys = []
                for k,v in sd.iteritems():
                    if len(k) > 2 and (k[0:2] == 'te' or k[0:2] == 'et'):
                        kill_keys.append(k)
                for k in kill_keys:
                    del sd[k] # dont send textemail or et_weather stuff
                info['sd'] = sd
            else:
                for field in ddict['sd']:
                    gv.sd[field] = ddict['sd'][field]
                update_hostname(gv.sd['name'])
                update_tza(gv.sd['tza'])
                jsave(gv.sd, 'sd')
                info['sd'] = 1
                force_reboot = True

        if 'snames' in ddict:
            if ddict['snames'] == 1:
                info['snames'] = gv.snames
            else:
                gv.snames = ddict['snames']
                jsave(gv.snames, 'snames')
                info['snames'] = 1

        if 'snotes' in ddict:
            if ddict['snotes'] == 1:
                info['snotes'] = gv.snotes
            else:
                gv.snotes = ddict['snotes']
                jsave(gv.snotes, 'snotes')
                info['snotes'] = 1

        if 'update_status' in ddict and ddict['update_status']:
            updatechecker.update_rev_data()
            info['update_status'] = updatechecker.status

        web.header('Content-Type', 'application/json')
        ret_str = json.dumps(info)
        if force_reboot:
            reboot(5)  # give a few seconds to reply
        return ret_str
예제 #3
0
    def POST(self):
        global error_msg

        if not been_through_subconfig:
            self.logger.info('tried Net POST....back to /su')
            raise web.seeother('/su')

        self.logger.debug('in Net POST')
        save_last_get('Net POST')
        form = web.input()
        error_msg = ''
        outdata = []

        for f in [
                'Static IP', 'Netmask', 'Gateway', 'DNS Nameservers', 'SSID',
                'Password', 'Hidden SSID', 'UPnP Refresh Rate', 'Station Name',
                'Station Port', 'External Station Port',
                'Remote Substation Access Port'
        ]:
            if f in form:
                form[f] = form[f].strip()

        # use hidden SSID if provided
        using_hidden_ssid = False
        if 'Hidden SSID' in form and form['Hidden SSID'] != '':
            using_hidden_ssid = True
            form['SSID'] = form['Hidden SSID']
            self.logger.info('using Hidden SSID')

        use_eth0 = 'SSID' not in form or form['SSID'] == 'ethernet'

        if not use_eth0:
            net = 'wlan0'
        else:
            form['SSID'] = 'using eth0'
            net = 'eth0'

        self.logger.debug('in Net POST: ' + form['SSID'])
        gv.sd['light_ip'] = 1
        try:
            if form['DNS Nameservers'][0:1] == 'X' and \
                   (len(form['DNS Nameservers']) == 1 or form['DNS Nameservers'][1:2] == ' '):
                gv.sd[
                    'light_ip'] = 0  # hack to disable blinking led on startup with leading X in nameservers
                form['DNS Nameservers'] = form['DNS Nameservers'][1:].strip()
        except:
            pass

        if 'Use DHCP' in form:
            for d in ['DNS Search', 'DNS Nameservers']:
                if d in form and form[d] != '':
                    error_msg = 'Error:  "' + d + '" must be blank with "Use DHCP".'
                    raise web.seeother('/cn')  # back to form

        if 'Station Name' in form:
            sn = validate_fqdn(form['Station Name'])
            if sn == 'Irricloud':  # error condition
                error_msg = 'Error:  "Station Name" must have only letter and numbers.'
                raise web.seeother('/cn')  # back to form
            elif len(sn) > 50 or len(sn) < 1:
                error_msg = 'Error:  "Station Name" must be at most 50 characters.'
                raise web.seeother('/cn')  # back to form
            form['Station Name'] = sn

        try:
            drop = 0
            with open('/etc/network/interfaces', 'r') as infile:
                iface = infile.readlines()
            for line in iface:
                if 'dns-nameservers' in line:
                    continue  # delete any old dns stuff
                did_iface_wlan0 = False
                if drop > 0:
                    drop -= 1
                    continue
                if 'iface ' + net + ' inet' in line:
                    if net == 'wlan0':
                        did_iface_wlan0 = True
                    if 'Use DHCP' in form:
                        self.logger.info('Using dhcp: ' + form['SSID'])
                        if 'static' in line:
                            drop = 3
                            line = 'iface ' + net + ' inet manual\n'
                    else:
                        self.logger.info('Using static ip: ' +
                                         form['Static IP'] + ' ' +
                                         form['Netmask'] + ' ' +
                                         form['Gateway'])
                        if 'static' in line:
                            drop = 3
                        outdata.append('iface ' + net + ' inet static\n')
                        outdata.append('        address ' + form['Static IP'] +
                                       '\n')
                        outdata.append('        netmask ' + form['Netmask'] +
                                       '\n')
                        line = '        gateway ' + form['Gateway'] + '\n'
                        outdata.append(line)
                        if 'DNS Nameservers' in form and form[
                                'DNS Nameservers'] != '':
                            line = '        dns-nameservers ' + form[
                                'DNS Nameservers'] + '\n'
                        else:  # use gateway
                            line = '        dns-nameservers ' + form[
                                'Gateway'] + '\n'
                elif 'iface ' + 'wlan0' + ' inet' in line:  # using eth0 but need to clean up 10.0.0.1 entry
                    if 'static' in line:
                        drop = 3
                        line = 'iface ' + 'wlan0' + ' inet manual\n'
                        did_iface_wlan0 = True

                outdata.append(line)
                if did_iface_wlan0:
                    outdata.append(
                        '        wpa-conf /etc/wpa_supplicant/wpa_supplicant.conf\n'
                    )

        except Exception as ex:
            self.logger.exception(
                'Unexpected exception trying to configure network: ' + str(ex))
            raise web.seeother('/cn')

        if len(outdata) == 0:
            self.logger.error('Expected data in /etc/network/interfaces')
            raise web.seeother('/cn')

        for portn in [
                'Station Port', 'External Station Port',
                'Remote Substation Access Port', 'UPnP Refresh Rate'
        ]:
            if portn in form:
                try:
                    port = int(form[portn])
                except:
                    error_msg = 'Error:  "' + portn + '" must be integer.'
                    raise web.seeother('/cn')  # back to form
                if port < 0 or port > 65535:
                    error_msg = 'Error:  "' + portn + '" must be between 0 and 65535.'
                    raise web.seeother('/cn')  # back to form
                if portn == 'Station Port' and port == 9080:  # specially reserved for proxy
                    error_msg = 'Error:  "' + portn + '" cannot be 9080.'
                    raise web.seeother('/cn')  # back to form

        self.logger.info('stopping daemons before updating network interfaces')
        if not use_eth0:
            stop_daemons()
        else:
            stop_daemons()

        try:
            with open('/etc/network/interfaces', 'w') as outfile:
                outfile.writelines(outdata)

            # Do not let dhcpcd get a dhcp address (and dns info?) if we are using a static config
            if 'Use DHCP' in form:
                shutil.copy2('/etc/dhcpcd.conf.yeswlan0', '/etc/dhcpcd.conf')
            else:
                shutil.copy2('/etc/dhcpcd.conf.nowlan0', '/etc/dhcpcd.conf')

            if not use_eth0:
                wpa_supp_lines = [
                    'ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\n'
                ]
                wpa_supp_lines.append('update_config=1\n\n')
                if form['SSID'] != '' and form['Password'] != '':
                    # wpa_passphrase cannot handle blanks so quote strings
                    ssid = form['SSID'].replace('"', '\"')
                    passw = form['Password'].replace('"', '\"')
                    cmd = '/usr/bin/wpa_passphrase "' + ssid + '" "' + passw + '" > passphrase'
                    subprocess.call(cmd, shell=True)
                    with open('passphrase', 'r') as f:
                        pl = f.readlines()
                        for line in pl:
                            if '#psk=' in line:  # drop cleartext password
                                continue
                            wpa_supp_lines.append(line)
                            if using_hidden_ssid and 'ssid' in line:
                                wpa_supp_lines.append('\tscan_ssid=1\n')
                    subprocess.call(['rm', 'passphrase'])
                else:
                    self.logger.warning('missing ssid or password')

                with open('/etc/wpa_supplicant/wpa_supplicant.conf',
                          'w') as outfile:
                    outfile.writelines(wpa_supp_lines)

                # check if network connection was made


#                self.logger.debug('wpa_action stopping wlan0')
#                rc = subprocess.call(['wpa_action', 'wlan0', 'stop'])
#                self.logger.debug( 'wpa_action wlan0 stop return: ' + str(rc))
#                time.sleep(1)
#                self.logger.debug('ifup wlan0')
#                rc = subprocess.call(['ifup', 'wlan0'])
#                self.logger.debug( 'ifup return: ' + str(rc))
#                time.sleep(1)
#                rc = subprocess.call(['wpa_action', 'wlan0', 'reload'])
#                self.logger.debug( 'wpa_action wlan0 reload return: ' + str(rc))
#                time.sleep(1)
#                reset_networking()

            if True or 'Do not validate network connection' in form or network_up(
                    net, self.logger):
                #successful network connection.   Finalize
                # copy the current versions to the save version
                cur_ip = get_ip(net)
                self.logger.info('success...cur_ip: ' + cur_ip)
                if gv.sd[
                        'enable_upnp']:  # was enabled?  Then cleanup.  If network still points to 10.0.0.1 network cant cleanup!
                    deletes = []
                    if gv.sd['external_htp'] != 0:
                        deletes.append(gv.sd['external_htp'])
                    if gv.sd['remote_support_port'] != 0:
                        deletes.append(gv.sd['remote_support_port'])
                    if gv.sd['external_proxy_port'] != 0:
                        deletes.append(gv.sd['external_proxy_port'])
                    update_upnp(cur_ip, self.logger, deletes)
                gv.sd['enable_upnp'] = 1 if 'Enable UPnP' in form else 0
                if gv.sd['enable_upnp']:
                    if 'UPnP Refresh Rate' in form:
                        gv.sd['upnp_refresh_rate'] = int(
                            form['UPnP Refresh Rate'])
                if 'Station Name' in form:
                    gv.sd['name'] = form['Station Name']
                    update_hostname(gv.sd['name'])
                if 'Station Port' in form:
                    gv.sd['htp'] = int(form['Station Port'])
                if gv.sd['master']:
                    gv.sd[
                        'master_ip'] = 'localhost'  # update local master_port
                    gv.sd['master_port'] == gv.sd['htp']
                else:
                    gv.sd['master_port'] = 0
                gv.sd['external_htp'] = int(
                    form['External Station Port']
                ) if 'External Station Port' in form else 0
                gv.sd['external_proxy_port'] = int(
                    form['Remote Substation Access Port']
                ) if 'Remote Substation Access Port' in form else 0
                jsave(gv.sd, 'sd')
                self.logger.info('success....copying back interfaces and wpa')
                try:
                    os.remove('/etc/resolv.conf')
                except:
                    pass
                shutil.copy('/etc/network/interfaces',
                            '/etc/network/interfaces.save')
                shutil.copy('/etc/wpa_supplicant/wpa_supplicant.conf',
                            '/etc/wpa_supplicant/wpa_supplicant.conf.save')
                #                self.logger.info('success....enabling sip')
                #                subprocess.call(['systemctl', 'enable', 'sip.service'])
                ##                subprocess.call(['update-rc.d', 'sip', 'enable'])
                ##                subprocess.call(['update-rc.d', 'sip', 'defaults'])
                ##                self.logger.info('disabling sip_net_finish')
                #                subprocess.call(['systemctl', 'disable', 'sip_net_finish.service'])
                ##                subprocess.call(['update-rc.d', '-f', 'sip_net_finish', 'remove'])
                #                light_ip(cur_ip)
                self.logger.info('rebooting')
                subprocess.call(['reboot', '-h'])
                exit(0)
            else:
                raise Exception('Network Inaccessible')

        except Exception as ex:
            self.logger.exception('failed: ' + str(ex))
            # restore saved /etc/network/interfaces and wpa_suplicant.conf
            self.logger.info('restore network files and exit.  Exception: ' +
                             str(ex))
            shutil.move('/etc/network/interfaces.save',
                        '/etc/network/interfaces')
            shutil.move('/etc/wpa_supplicant/wpa_supplicant.conf.save',
                        '/etc/wpa_supplicant/wpa_supplicant.conf')
            exit(1)

        self.logger.error(
            'sip_net_config: should have exited above.  sip_monitor will restart'
        )
        raise web.seeother('/cn')
예제 #4
0
    def GET(self):
        qdict = web.input()
        try:
            ddict = json.loads(qdict['data'])
        except:
            raise web.unauthorized()

        force_reboot = False
        info = {}
        for l in ['wlog', 'elog', 'slog', 'evlog']:
            if l in ddict and ddict[l]:
                end = ddict['end_date']
                days = ddict['days_before']
                prefix = ''
                try:
                    if l in ['slog', 'evlog']:
                        prefix = 'sensors/' + gv.plugin_data['ld'][int(ddict['ldi'])]['name'] + '/logs/'
                except:
                    pass
                records = read_log(prefix+l, end, days)
                info[l] = records

        for dlog in ['dlogirricloud', 'dlogirricloud_monitor', 'dlogirricloud_net_config']:
            if dlog in ddict and ddict[dlog]:
                records = []
                try:
                    with open('./logs/' + dlog[4:] + '.out', 'r') as file:
                        records = file.readlines()
                except:
                    pass
                info[dlog] = []
                for r in records:
                    info[dlog].append(r)

        if 'lrun' in ddict and ddict['lrun']:
            info['lrun'] = gv.lrun

        if 'programs' in ddict:
            if ddict['programs'] == 1:
                info['programs'] = gv.pd
            else:
                gv.pd = ddict['programs']
                jsave(gv.pd, 'programs')
                info['programs'] = 1

        if 'ps' in ddict and ddict['ps']:
            info['ps'] = gv.ps

        if 'sbits' in ddict and ddict['sbits']:
            info['sbits'] = gv.sbits

        if 'srvals' in ddict and ddict['srvals']:
            info['srvals'] = gv.srvals

        if 'sensors' in ddict and 'ld' in gv.plugin_data:
            if ddict['sensors'] == 1:
                info['sensors'] = []
                try:
                    if 'ldi' not in ddict or int(ddict['ldi']) == -1:
                        info['sensors'] = gv.plugin_data['ld']
                    else:
                        info['sensors'] = gv.plugin_data['ld'][int(ddict['ldi'])]
                except:
                    pass
                info['sensboards'] = i2c.get_vsb_boards().keys()
                info['remotesensboards'] = get_remote_sensor_boards()
            else:
                try:
                    if 'ldi' not in ddict or int(ddict['ldi']) == -1:
                        gv.plugin_data['ld'] = ddict['sensors']
                    else:
                        gv.plugin_data['ld'][int(ddict['ldi'])] = ddict['sensors']
                except:
                    gv.plugin_data['ld'] = ddict['sensors']
                jsave(gv.plugin_data['ld'], 'sensors')
                info['sensors'] = 1

        if 'camera' in ddict and 'ca' in gv.plugin_data:
            if ddict['camera'] == 1:
                info['camera'] = gv.plugin_data['ca']
                if 'cai' in ddict and ddict['cai']:
                    info['cai'] = ''
                    if gv.plugin_data['ca']['enable_camera'] == 'on':
                        try:
                            with open('./static/images/camera.jpg', mode='rb') as file: # b is important -> binary
                                info['cai'] = base64.b64encode(file.read())
                        except:
                            pass
            else:
                gv.plugin_data['ca'] = ddict['camera']
                jsave(gv.plugin_data['ca'], 'camera')
                info['camera'] = 1

        if 'sd' in ddict:
            if ddict['sd'] == 1:
                sd = gv.sd.copy()
                del sd['substation_network']
                del sd['salt']
                del sd['password']
                del sd['pwd']
                del sd['enable_upnp'] # stuff from base configuration stays as was
                del sd['subnet_only_substations']
                del sd['external_proxy_port']
                kill_keys = []
                for k,v in sd.iteritems():
                    if len(k) > 2 and (k[0:2] == 'te' or k[0:2] == 'et'):
                        kill_keys.append(k)
                for k in kill_keys:
                    del sd[k] # dont send textemail or et_weather stuff
                info['sd'] = sd
            else:
                for field in ddict['sd']:
                    gv.sd[field] = ddict['sd'][field]
                update_hostname(gv.sd['name'])
                update_tza(gv.sd['tza'])
                jsave(gv.sd, 'sd')
                info['sd'] = 1
                force_reboot = True

        if 'snames' in ddict:
            if ddict['snames'] == 1:
                info['snames'] = gv.snames
            else:
                gv.snames = ddict['snames']
                jsave(gv.snames, 'snames')
                info['snames'] = 1

        if 'snotes' in ddict:
            if ddict['snotes'] == 1:
                info['snotes'] = gv.snotes
            else:
                gv.snotes = ddict['snotes']
                jsave(gv.snotes, 'snotes')
                info['snotes'] = 1

        if 'update_status' in ddict and ddict['update_status']:
            updatechecker.update_rev_data()
            info['update_status'] = updatechecker.status

        web.header('Content-Type', 'application/json')
        ret_str = json.dumps(info)
        if force_reboot:
            reboot(5)  # give a few seconds to reply
        return ret_str