¿Cómo utilizar PowerShell y/o Python para reiniciar el enrutador?

¿Cómo utilizar PowerShell y/o Python para reiniciar el enrutador?

¿Cómo utilizar PowerShell para reiniciar el enrutador?

Mi computadora está conectada al enrutador mediante un cable de red, el enrutador actúa como un módem, se conecta al ISP a través de PPPoE, mi computadora está detrás de NAT.

El modelo de mi enrutador: Huawei HS8545M, dirección LAN: 192.168.1.1, inicio de sesión del administrador de la página web: CMCCAdmin, contraseña del administrador de la página web: aDm8H%MdA.

Tengo que hacer lo siguiente para reiniciar el enrutador (7 clics en total, el navegador recuerda el nombre de usuario y la contraseña):

ingrese la descripción de la imagen aquí

ingrese la descripción de la imagen aquí

Demasiados pasos.

He intentado utilizar este método:

$ie = New-Object -ComObject 'internetExplorer.Application'
$ie.Navigate "https://192.168.1.1"

Pero después de un momento la conexión se pierde, .Documentestá vacía, al intentar actualizar se produce este error:

OperationStopped: The RPC server is unavailable. (0x800706BA)

Estoy usando Windows 10 20H2 y deshabilité el Escritorio remoto, la Asistencia remota, el Registro remoto, la Administración remota de Windows y muchas otras cosas, deshabilité las cosas remotas porque representan amenazas a la seguridad, creo que son relevantes para esto; Por cierto, RPCel servicio está funcionando.

¿Alguien puede ayudarme?


Código fuente de la primera página:página1.html

Código fuente de la segunda página:página2.html

Esto debería ser sencillo de hacer: inicie sesión en 192.168.1.1, cree una cookie y use la cookie para ingresar a 192.168.1.1/index.asp, envíe Restart_button, trabajo realizado; sin embargo, no estoy muy familiarizado con los comandos que tratan con redes. ...


Actualmente estoy buscando la forma Python, estoy usando Python 3.9.1 amd64, lo puse en PATH hace mucho tiempo, instalé Selenium y Twill a través de pip. y descargué y extraí GeckoDriver.exe en la carpeta de instalación de Python;

Conozco selenium, twill, urllib, urllib2, cookielib y webbot, todos son capaces de hacer esto, actualmente estoy tratando de descubrir cómo hacerlo de la mejor manera.


Logré iniciar sesión en el enrutador en Python a través de twill, sin embargo, no sé qué hacer a continuación:

from twill.commands import *
go('http://192.168.1.1')
showforms()
fv("1","txt_Username","CMCCAdmin")
fv("1","txt_Password","aDm8H%MdA")
showforms()
submit('btnSubmit')
go("http://192.168.1.1/index.asp")

ingrese la descripción de la imagen aquí

El botón:

<input type="button" name="Restart_button" id="Restart_button" class="submit" style="width:98px" onclick="Reboot()" value="重启">

Está localizado en:

html.body.#container.#center.#content.table.tbody.tr.td.#frameContent.html.body.div.#Restart_button

Además, el inputfieldsde la primera página (http://192.168.1.1):

PS C:\Windows\System32> $html.inputfields

outerHTML : <input name="txt_Username" type="text" id="txt_Username" style="float:left;padding:0;width:218px;height:38px;line-height:38px;text-indent:0.5em;border:0 solid green;background-color:transparent;" maxlength="31"/>
tagName   : INPUT
name      : txt_Username
type      : text
id        : txt_Username
style     : float:left;padding:0;width:218px;height:38px;line-height:38px;text-indent:0.5em;border:0 solid green;background-color:transparent;
maxlength : 31

outerHTML : <input name="txt_Password" type="password" id="txt_Password" maxlength="127" style="float:left;padding:0;width:218px;height:38px;line-height:38px;text-indent:0.5em;border:0 solid green;background-color:transparent;"
            maxlength="31"/>
tagName   : INPUT
name      : txt_Password
type      : password
id        : txt_Password
maxlength : 31
style     : float:left;padding:0;width:218px;height:38px;line-height:38px;text-indent:0.5em;border:0 solid green;background-color:transparent;

outerHTML : <input type="button" id="btnSubmit" name="btnSubmit" value="确定" onclick="SubmitForm();" class="button_css"/>
tagName   : INPUT
type      : button
id        : btnSubmit
name      : btnSubmit
value     : 确定
onclick   : SubmitForm();
class     : button_css

outerHTML : <input type="reset" name="Submit2" value="取消" onclick="canceltext();" class="button_css"/>
tagName   : INPUT
type      : reset
name      : Submit2
value     : 取消
onclick   : canceltext();
class     : button_css

Tengo el código fuente de la página de reinicio:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Pragma" content="no-cache" />
<link rel="stylesheet"  href='../../../../Cuscss/frame.css?2020070716413845-1425773353' type='text/css'>
<script language="JavaScript" src="../../../resource/common/util.js?2020070716413845-1425773353"></script>
<script language="JavaScript" type="text/javascript">

function LoadFrame()
{
}


function Reboot()
{
if(ConfirmEx("确定要重启设备吗?"))
{
setDisable('Restart_button',   1);
setDisable('Restore_button',    1);
setDisable('btnRestoreDftCfg', 1);
var Form = new webSubmitForm();

Form.setAction('set.cgi?x=' + 'InternetGatewayDevice.X_HW_DEBUG.SMP.DM.ResetBoard'
 + '&RequestFile=html/ssmp/devmanage/cmccdevicereset.asp');
Form.addParameter('x.X_HW_Token', getValue('onttoken'));
Form.submit();
}
}

</script>
</head>
<body class="mainbody" onLoad="LoadFrame();">

<div class="func_spread"></div>
<div class="title_with_desc">
<label id="Title_reboot_lable">设备重启</label>
</div>
<div class="title_01" style="padding-left:10px;" width="100%">
<label id="Title_reboot_tips_lable">点击如下按钮重启路由器。</label>
</div>
<div class="button_spread"></div>
<div align="right">
<input type="hidden" name="onttoken" id="hwonttoken" value="de0f5f98c4d4a77239ccb981cd5c4bf3">
<input type='button' name="Restart_button" id="Restart_button" class="submit" style="width:98px" onClick='Reboot()' value="重启">
</div>
</body>
</html>

Se encuentra ubicado en la dirección:

http://192.168.1.1/html/ssmp/devmanage/cmccdevicereset.asp

Además, no sé realmente si Submit('btnSubmit')inicié sesión o no, no estoy totalmente seguro...

Y aunque esto funciona, Firefox se inicializa muy lentamente.


Finalmente descubrí cómo hacerlo mediante telnet:

telnet 192.168.1.1
root
adminHW
reset

¿Cómo puedo convertirlo en un script que ingrese comandos automáticamente?

Respuesta1

La forma SSH

Si su enrutador admite acceso SSH (probablemente necesite habilitarlo en la configuración del enrutador), puede intentar emitir un comando a través de SSH para reiniciarlo.

Podría ser algo como ssh USERNAME@ROUTER_ADDRESS rebooto ssh USERNAME@ROUTER_ADDRESS "sudo reboot".

  1. Primero, debes habilitar el acceso SSH. Asegúrese de que funcione escribiendo algo como ssh USERNAME@ROUTER_ADDRESS(si lo hace, se le pedirá la contraseña y, después de ingresar la contraseña correcta, accederá al símbolo del sistema del enrutador).
  2. Luego determine qué comando necesita escribir en el símbolo del sistema del enrutador para reiniciarlo. Podría ser simplemente reboot. Pero es posible que también deba especificar la ruta exacta como /sbin/reboot, /usr/sbin/rebooto etc. Y/o también puede que necesite elevar los privilegios como sudo COMMANDo su -c 'COMMAND' root.
  3. Si se pasan los dos pasos anteriores, puede combinar el inicio de sesión en SSH ( ssh USERNAME@ROUTER_ADDRESS) y emitir un comando de reinicio (por ejemplo, sudo reboot) en un solo comando (como ssh USERNAME@ROUTER_ADDRESS "sudo reboot"). Se le seguirá pidiendo la contraseña cada vez, pero se puede evitar (envíeme un mensaje en los comentarios si llegó a este paso y desea evitar escribir contraseñas).

La forma HTTP

Abra Network Monitor en su navegador (por ejemplo, en Firefox, que es Shift+ Ctrl+ E) e intente determinar qué solicitud web exactamente se emite cuando confirma el reinicio (por ejemplo, en Firefox puede ver todos los datos de la solicitud).

Respuesta2

Según el usuario Ligeti aquí, para un modelo similar:https://jalalsela.com/accessing-hg8245q-shell/

  • SSH/Telnet al dispositivo
  • Iniciar sesión comoroot
  • Puede enumerar los comandos disponibles con/?

Desde aquí puede intentar encontrar un comando como rebootreiniciar o shelldar acceso a más comandos bash, tal vez shutdown -ro help/ ?desde allí. Si dice que no tienes permiso para algo, incluye pasos para superadministrarte, pero no creo que sea necesario.

Respuesta3

Finalmente lo he hecho y me ha parecido muy fácil.

Utilicé Python 3.9.1, Internet Explorer, Selenium e IEDriverServer.exe (32 bits).

El código:

    import selenium
    from selenium import webdriver
    ie = webdriver.Ie()
    ie.get('http://192.168.1.1')
    ie.find_element_by_id('txt_Username').send_keys("CMCCAdmin")
    ie.find_element_by_id('txt_Password').send_keys("aDm8H%MdA")
    ie.find_element_by_id('btnSubmit').click()
    ie.get('http://192.168.1.1/html/ssmp/devmanage/cmccdevicereset.asp')
    ie.find_element_by_id('Restart_button').click()
    ie.switch_to.alert.accept()

Lo guardé como RebootModem.py, funciona bien, solo que no cierra la ventana automáticamente después de que se reinicia el enrutador, y la ejecución del código simplemente se bloquea ie.switch_to.alert.accept()y no se cierra, lo que me obliga a cerrar manualmente la ventana de IE...

Probé el código en la consola y descubrí que la consola no acepta comandos hasta que el enrutador haya terminado de reiniciarse...

Actualmente estoy tratando de encontrar la forma webbot, urllib(2), cookielib y twill de hacer esto, no creo que depender de un navegador sea muy eficiente.


He hecho que cierre automáticamente la ventana y el script de IE mediante:

    start-process -filepath python -argumentlist $PSScriptRoot\RebootModem.py
    start-sleep -seconds 15
    get-process -name iexplore | stop-process
    get-process -name IEDriverServer| stop-process

Guarde como RebootModem.ps1, en el mismo directorio que RebootModem.py, ejecute RebootModem.ps1para iniciar la ejecución RebootModem.pyy cerrará automáticamente la ventana de IE y Python.exe (su nombre se cambia a IEDriverServer.exe) después de 15 segundos...


Para generalizar el código, simplemente reemplace los elementids con los elementids de la página web de su enrutador, puede obtenerlos mediante Ctrl+ Shift+ Iy reemplace las direcciones con las direcciones que encontró (aunque probablemente no necesite cambiar 192.168.1.1). Obtuve la dirección de la página utilizada para reiniciar el módem mediante "View Frame Source".


PD: el código completo que utilicé para restablecer todas las configuraciones de red:

devcon disable *dev_8168*
devcon enable *dev_8168*
start-sleep -seconds 3
netsh winsock reset
netsh winhttp reset proxy
netsh http flush log buffer
net start dot3svc
netsh lan reconnect
net stop dot3svc
start-sleep -seconds 3
netsh int ip reset
netsh int ipv4 reset
netsh int ipv6 reset
netsh int httpstunnel reset
netsh int portproxy reset
netsh int tcp reset
start-sleep -seconds 3
ipconfig /release
ipconfig /all
ipconfig /flushdns
ipconfig /registerdns
ipconfig /renew

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") 
RunDll32.exe InetCpl.cpl,ResetIEtoDefaults
Start-Sleep -Seconds 1
[System.Windows.Forms.SendKeys]::SendWait("{Tab}")
[System.Windows.Forms.SendKeys]::SendWait(" ")
[System.Windows.Forms.SendKeys]::SendWait("R")
Start-Sleep -Seconds 2
[System.Windows.Forms.SendKeys]::SendWait("C")

start-process -filepath python -argumentlist $PSScriptRoot\RebootModem.py
start-sleep -seconds 15
get-process -name iexplore | stop-process
get-process -name IEDriverServer| stop-process

Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" -Name "ProxyEnable" -Type DWord -Value 1
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings" -Name "ProxyOverride" -Type String -Value "login.live.com;account.live.com;clientconfig.passport.net;wustat.windows.com;*.windowsupdate.com;*.wns.windows.com;*.hotmail.com;*.outlook.com;*.microsoft.com;*.msftncsi.com;<local>"

Respuesta4

Lo he hecho... ¡otra vez!

La forma PowerShell + VBScript + Telnet de hacer esto:

set router = CreateObject ("WScript.Shell")
router.run("Telnet")
WScript.Sleep 750
router.sendkeys("Open 192.168.1.1")
router.sendkeys("{Enter}")
WScript.Sleep 750
router.sendkeys("root")
router.sendkeys("{Enter}")
WScript.Sleep 750
router.sendkeys("adminHW")
router.sendkeys("{Enter}")
WScript.Sleep 750
router.sendkeys("reset")
router.sendkeys("{Enter}")

Guardar comoRebootModem.vbs

Start-Process -Filepath cscript.exe -Argumentlist $PSScriptRoot\RebootModem.vbs
Start-Sleep -Seconds 6
Get-Process -Name Telnet | Stop-Process

Guardar comoRebootModem.ps1

Ejecute RebootModem.ps1para reiniciar el módem a través de Telnet y cierre automáticamente Telnet.exe después de 6 segundos.


Método puro de PowerShell:

    [void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
    Start-Process -Filepath Telnet.exe -Argumentlist 192.168.1.1
    Start-Sleep -Seconds 1
    [System.Windows.Forms.SendKeys]::SendWait("root")
    [System.Windows.Forms.SendKeys]::SendWait("{Enter}")
    [System.Windows.Forms.SendKeys]::SendWait("adminHW")
    [System.Windows.Forms.SendKeys]::SendWait("{Enter}")
    [System.Windows.Forms.SendKeys]::SendWait("reset")
    [System.Windows.Forms.SendKeys]::SendWait("{Enter}")
    Get-Process -Name Telnet | Stop-Process

Hace el trabajo en menos de 3 segundos. He determinado que esta es de hecho la forma más eficiente de hacerlo.

información relacionada