重新连接Netgear DGN2200v4的Python脚本

时间:2016-05-11 16:45:08

标签: python python-2.7

我需要一个Netgear DGN2200v4的脚本,让我每x秒更换一次ip​​。在线搜索我找到了这段代码:

    #!/usr/bin/env python2.7

import re
import urllib2
from base64 import b64encode
from time import sleep

BASE_URL = 'http://192.168.0.1/'
USERNAME = 'admin'
PASSWORD = 'admin'

id_regex = re.compile('setup.cgi\?id=(\w+)"')

auth = "Basic %s" % b64encode("%s:%s" % (USERNAME, PASSWORD))

def load_html(url, data = None):
    request = urllib2.Request(BASE_URL + url, data,
                              {"Authorization": auth})
    result = urllib2.urlopen(request)
    return result.read()

# Evito eccezione Unauthorized
try:
    load_html('')
except urllib2.HTTPError:
    pass

# Chiamo la schermata di riepilogo
html = load_html('setup.cgi?next_file=RST_st_poe.htm')
ID = id_regex.search(html).group(1)

# Lancio la disconnessione
load_html('setup.cgi?id=' + ID,
          'todo=disconnect&this_file=RST_st_poe.htm&next_file=RST_st_poe.htm&SID=')

# Attendo 3 secondi
sleep(3)

# Chiamo la schermata di riepilogo
html = load_html('setup.cgi?next_file=RST_st_poe.htm')
ID = id_regex.search(html).group(1)

# Lancio la riconnessione
load_html('setup.cgi?id=' + ID,
          'todo=connect&this_file=RST_st_poe.htm&next_file=RST_st_poe.htm&SID=')

# Attendo 7 secondi
sleep(7)

# Logout
load_html('setup.cgi?todo=logout')

Source

但它在我的电脑上不起作用。 我使用我的凭证和设置的PPPOE协议登记了'USERNAME'和'PASSWORD',这就是日志。

Traceback (most recent call last):
  File "C:\Users\x\Documents\dgnd3700.py", line 31, in <module>
    html = load_html('setup.cgi?next_file=RST_st_poe.htm')
  File "C:\Users\x\Documents\dgnd3700.py", line 19, in load_html
    result = urllib2.urlopen(request)
  File "C:\Python27\lib\urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "C:\Python27\lib\urllib2.py", line 397, in open
    response = meth(req, response)
  File "C:\Python27\lib\urllib2.py", line 510, in http_response
    'http', request, response, code, msg, hdrs)
  File "C:\Python27\lib\urllib2.py", line 435, in error
    return self._call_chain(*args)
  File "C:\Python27\lib\urllib2.py", line 369, in _call_chain
    result = func(*args)
  File "C:\Python27\lib\urllib2.py", line 518, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
HTTPError: HTTP Error 404: Not Found

我该如何解决?谢谢你的建议

1 个答案:

答案 0 :(得分:0)

从回溯看起来好像连接和授权是成功的,但是

中指定的路径
html = load_html('setup.cgi?next_file=RST_st_poe.htm')

不正确,因此出现404错误。

也许安装wireshark或fiddler,启动跟踪,然后手动(使用Web浏览器)运行这些步骤,并查看所请求的路径。然后,您可以修改load_html函数的条目以反映您找到的正确路径。