bangnaga

Mikrotik Autologin Python

Nov 23rd, 2015
215
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python
  2. from httplib2 import Http
  3. from md5 import md5
  4. import re
  5. from urllib import urlencode
  6.  
  7. URL = 'http://192.168.88.1/login'
  8. output = '/tmp/login.html'
  9. salt_pattern = '\\\\\d*'
  10. h = Http()
  11.  
  12. def truncate_file(file):
  13.     f = open(file, 'w+')
  14.     for line in f.readlines():
  15.         line = line.replace(line, '')
  16.         f.writelines(line)
  17.         f.flush()
  18.     print 'file: "%s" truncated' % f.name
  19.  
  20. def extract_salt(file):
  21.     f = open(file, 'r')
  22.     li = ''
  23.     for line in f.readlines():
  24.         if line.find('hexMD5') != -1:
  25.             li = line
  26.             break
  27.     r = re.compile("\\\\\d*")
  28.     salt = r.findall(li)
  29.     if not salt:
  30.         print 'seems to be already logged in'
  31.         exit()
  32.     x = chr(int(salt[0][1:], 8))
  33.     rest = salt[1:]
  34.     y = ''.join(chr(int(d[1:], 8)) for d in rest)
  35.     return x, y
  36.  
  37. def login(username, password):
  38.     data = {'username':username, 'password':password, 'dst':'', 'popup':'true'}
  39.     payload = urlencode(data)
  40.     headers = {}
  41.     headers.update({'Content-Type':'application/x-www-form-urlencoded'})
  42.     response, _ = h.request(URL, method='POST', body=payload, headers=headers)
  43.     assert(response.status==200)
  44.     try:
  45.         response['set-cookie']
  46.         response['set-cookie']
  47.     except KeyError:
  48.         raise Exception('Login Failed')
  49.  
  50. def main():
  51.     import sys
  52.     argz = sys.argv[1:]
  53.     try:
  54.         username = argz[0]
  55.         password = argz[1]
  56.     except Exception:
  57.         print 'could not parse arguments\nusage: python main.py username password'
  58.         exit()
  59.     response, content = h.request(URL)
  60.     assert(response.status==200)
  61.     truncate_file(output)
  62.     f = open(output, 'w')
  63.     f.write(content)
  64.     f.flush()
  65.     x, y = extract_salt(output)
  66.     salted = x + password + y
  67. #    print 'salted password: %s' % salted
  68.     hashed_password = md5(salted)
  69.     hex_hash_password = hashed_password.hexdigest()
  70.     print 'hashed password: %s' % hex_hash_password
  71.     login(username, hex_hash_password)
  72.     print 'Successfully logged in ;)'
  73.  
  74. if __name__ == '__main__':
  75.     main()
RAW Paste Data