Saturday, January 6, 2018

WAN IP address from Ubiquiti EdgeRouter ER-X

I got myself a new router, an Ubiquiti EdgeRouter ER-X , and when I tried to apply my old methods from the WNR2000v5 I discovered that the web pages returned were full of javascript. I could not find any WAN values in the files.

And that was just as well, the edge router features a full OS, with python pre installed! I set it up with eth4 as the WAN port.

The only caveat was the

show interfaces ethernet eth4 brief

did not work in a script. The command

/opt/vyatta/bin/vyatta-op-cmd-wrapper show interfaces ethernet eth4 brief

has to be used for it to work.

So after setting it up to run via crontab with the command

sudo -e crontab
the script were up and running.

The working python script:

#!/usr/bin/python

import re, os, ftplib, pickle, StringIO

def touch(fname, times=None):
        with open(fname, 'a'):
                        os.utime(fname, times)

cmd_path = '/opt/vyatta/bin/vyatta-op-cmd-wrapper'
cmd_res = os.popen(cmd_path+ ' show interfaces ethernet eth4 brief')
data = cmd_res.read()
cmd_res.close()

# Edgeos show interface command returns
# eth4        xxx.xxx.xxx.xxx
p = re.compile('eth4(\s*)(\d*).(\d*).(\d*).(\d*)')
m = p.search(data)

#m.groups()[0] is white space
if (m and len(m.groups()) == 5):
        current_ip = (m.groups()[1], m.groups()[2], m.groups()[3], m.groups()[4])
        try:
                last_ip = pickle.load(open('/home/user/myip/lastip', "rb" ))
        except IOError:
                last_ip = (1,2,3,4)

        if current_ip != last_ip:
                pickle.dump(current_ip,open('/home/user/myip/lastip', "wb" ))
                data ='<html><head><title>My IP</title></head><b>My IP:\
%d//%d//%d//%d</b></font></p></body></html>\
'%(int(m.groups()[1]),int(m.groups()[2]),int(m.groups()[3]),int(m.groups()[4]))
                output = StringIO.StringIO(data)
                ftp = ftplib.FTP('ftp.server.org', 'username','password')
                ftp.cwd('pub')
                ftp.storlines('STOR index.html', output)
                ftp.close()
        else:
                touch('/home/user/myip/lastip')

No comments:

Post a Comment