AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / computer / Perguntas / 1620822
Accepted
Ξένη Γήινος
Ξένη Γήινος
Asked: 2021-01-26 22:33:18 +0800 CST2021-01-26 22:33:18 +0800 CST 2021-01-26 22:33:18 +0800 CST

Como usar o PowerShell e/ou Python para reiniciar o roteador?

  • 772

Como usar o PowerShell para reiniciar o roteador?

Meu computador está conectado ao roteador usando um cabo de rede, o roteador funciona como um modem, ele se conecta ao ISP através de PPPoE, meu computador está atrás do NAT.

O modelo do meu roteador: Huawei HS8545M, endereço LAN: 192.168.1.1, login do administrador da página da Web: CMCAdmin, senha do administrador da página da Web: aDm8H%MdA.

Eu tenho que fazer o seguinte para reiniciar o roteador (7 cliques no total, o navegador lembra o login e a senha):

insira a descrição da imagem aqui

insira a descrição da imagem aqui

Passos demais.

Eu tentei usar este método:

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

Mas depois de um tempo a conexão é perdida, .Documentfica vazia, tentar atualizar resulta neste erro:

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

Estou usando o Windows 10 20H2 e desabilitei a Área de Trabalho Remota, Assistência Remota, Registro Remoto, Gerenciamento Remoto do Windows e muitas outras coisas, desabilitei coisas remotas porque representam ameaças à segurança, acho que são relevantes para isso; A propósito, o RPCserviço está em execução.

Alguém pode me ajudar?


Código fonte da primeira página: page1.html

Código fonte da segunda página: page2.html

Isso deve ser simples de fazer, faça login em 192.168.1.1, crie um cookie e use o cookie para entrar em 192.168.1.1/index.asp, envie Restart_button, job done, porém não estou muito familiarizado com comandos que lidam com redes ...


Atualmente estou procurando o caminho do Python, estou usando o Python 3.9.1 amd64, coloquei no PATH há muito tempo, instalei o Selenium e o Twill via pip. e baixei e extraí o GeckoDriver.exe para a pasta de instalação do Python;

Conheço selênio, sarja, urllib, urllib2, cookielib e webbot, todos são capazes de fazer isso, atualmente estou tentando descobrir como fazê-lo da melhor maneira.


Consegui fazer login no roteador em Python via sarja, porém não sei o que fazer a seguir:

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")

insira a descrição da imagem aqui

O botão:

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

Está localizado em:

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

Além disso, o inputfieldsda primeira 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

Eu tenho o código-fonte da página de redefinição:

<!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>

Está localizado no endereço:

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

Também não sei se Submit('btnSubmit')me loguei ou não, não tenho certeza...

E embora isso funcione, o Firefox inicializa muito lentamente.


Eu finalmente descobri como fazer isso da maneira telnet:

telnet 192.168.1.1
root
adminHW
reset

Como posso torná-lo um script que insere comandos automaticamente?

windows-10 networking
  • 4 4 respostas
  • 1673 Views

4 respostas

  • Voted
  1. Sasha
    2021-01-27T00:16:07+08:002021-01-27T00:16:07+08:00

    A maneira SSH

    Se o seu roteador suporta acesso SSH (você provavelmente precisa habilitá-lo nas configurações do roteador), você pode tentar emitir um comando via SSH para reiniciá-lo.

    Pode ser algo como ssh USERNAME@ROUTER_ADDRESS rebootou ssh USERNAME@ROUTER_ADDRESS "sudo reboot".

    1. Primeiro, você precisa habilitar o acesso SSH. Certifique-se de que funciona digitando smth like ssh USERNAME@ROUTER_ADDRESS(se funcionar, será solicitada a senha e, após digitar a senha correta, entre no prompt de comando do roteador).
    2. Em seguida, determine qual comando você precisa digitar no prompt de comando do roteador para reiniciá-lo. Pode ser apenas reboot. Mas você também pode precisar especificar o caminho exato como /sbin/reboot, /usr/sbin/rebootou etc. E/ou também pode precisar elevar os privilégios como sudo COMMANDou su -c 'COMMAND' root.
    3. Se as duas etapas anteriores forem passadas, você pode combinar o login no SSH ( ssh USERNAME@ROUTER_ADDRESS) e a emissão de um comando de reinicialização (por exemplo sudo reboot) em um único comando (como ssh USERNAME@ROUTER_ADDRESS "sudo reboot"). Você ainda será solicitado a digitar a senha todas as vezes, mas isso pode ser evitado (por favor, me envie um ping nos comentários se você chegou a esta etapa e deseja evitar digitar senhas).

    A maneira HTTP

    Open Network Monitor in your browser (e.g. in Firefox that's Shift+Ctrl+E) and try to determine which exactly web request is issued when you confirm restart (e.g. in Firefox you can see the whole data of the request).

    • 2
  2. Cpt.Whale
    2021-01-27T08:25:27+08:002021-01-27T08:25:27+08:00

    According to user Ligeti here, for a similar model: https://jalalsela.com/accessing-hg8245q-shell/

    • SSH/Telnet to the device
    • Log in as root
    • You can list available commands with /?

    From here you can try and find a command like reboot to restart, or shell to give access to more bash commands, maybe shutdown -r or help/? from there. If it says you don't have permission for something, he includes steps to super-admin yourself, but I don't think it would be necessary.

    • 1
  3. Ξένη Γήινος
    2021-01-27T22:21:55+08:002021-01-27T22:21:55+08:00

    Finally I have done it, and I found it to be very easy.

    I used Python 3.9.1, Internet Explorer , Selenium and IEDriverServer.exe (32-bit).

    The code:

        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()
    

    I saved it as RebootModem.py, it works well, just it doesn't close the Window automatically after the router rebooted, and the code execution just hangs at ie.switch_to.alert.accept() and won't quit, requiring me to manually close the IE window...

    I tried the code in console, and I have found that the console won't accept commands until the router has finished rebooting...

    I am currently trying to find the webbot, urllib(2), cookielib and twill way to do this, I don't think relying on a browser is very efficient.


    I have made it automatically close the IE window and script by:

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

    Save as RebootModem.ps1, at the same directory as RebootModem.py, run RebootModem.ps1 to start execution of RebootModem.py and it will automatically close the IE window and Python.exe (its name is changed to IEDriverServer.exe) after 15 seconds...


    To generalize the code, just replace the elementids with the elementids of your router's webpage, you can get them by Ctrl+Shift+I, and replace the addresses with the addresses you found (though you probably don't need to change 192.168.1.1), I got the address of the page used to reboot modem by "View Frame Source".


    P.S. the full code I used to reset all network settings:

    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>"
    
    • 1
  4. Best Answer
    Ξένη Γήινος
    2021-01-28T03:54:25+08:002021-01-28T03:54:25+08:00

    I have done it...again!

    The PowerShell + VBScript + Telnet way to do this:

    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}")
    

    Save as RebootModem.vbs

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

    Save as RebootModem.ps1

    Run RebootModem.ps1 to restart the modem via Telnet and automatically close Telnet.exe after 6 seconds.


    Método puro do 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
    

    Ele faz o trabalho em menos de 3 segundos. Eu determinei que esta é realmente a maneira mais eficiente de fazer isso.

    • 0

relate perguntas

  • O serviço de arbitragem USB da estação de trabalho VMware não inicia automaticamente

  • Como ativar o sensor de impressão digital no domínio e no diretório ativo do Linux

  • atalho do shell da área de trabalho no painel lateral do explorer

  • Por que não consigo enviar arquivos do Android para o Windows 10?

  • Abrir com em vários arquivos?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Como posso reduzir o consumo do processo `vmmem`?

    • 11 respostas
  • Marko Smith

    Baixar vídeo do Microsoft Stream

    • 4 respostas
  • Marko Smith

    O Google Chrome DevTools falhou ao analisar o SourceMap: chrome-extension

    • 6 respostas
  • Marko Smith

    O visualizador de fotos do Windows não pode ser executado porque não há memória suficiente?

    • 5 respostas
  • Marko Smith

    Como faço para ativar o WindowsXP agora que o suporte acabou?

    • 6 respostas
  • Marko Smith

    Área de trabalho remota congelando intermitentemente

    • 7 respostas
  • Marko Smith

    O que significa ter uma máscara de sub-rede /32?

    • 6 respostas
  • Marko Smith

    Ponteiro do mouse movendo-se nas teclas de seta pressionadas no Windows?

    • 1 respostas
  • Marko Smith

    O VirtualBox falha ao iniciar com VERR_NEM_VM_CREATE_FAILED

    • 8 respostas
  • Marko Smith

    Os aplicativos não aparecem nas configurações de privacidade da câmera e do microfone no MacBook

    • 5 respostas
  • Martin Hope
    Saaru Lindestøkke Por que os arquivos tar.xz são 15x menores ao usar a biblioteca tar do Python em comparação com o tar do macOS? 2021-03-14 09:37:48 +0800 CST
  • Martin Hope
    CiaranWelsh Como posso reduzir o consumo do processo `vmmem`? 2020-06-10 02:06:58 +0800 CST
  • Martin Hope
    Jim Pesquisa do Windows 10 não está carregando, mostrando janela em branco 2020-02-06 03:28:26 +0800 CST
  • Martin Hope
    v15 Por que uma conexão de Internet gigabit/s via cabo (coaxial) não oferece velocidades simétricas como fibra? 2020-01-25 08:53:31 +0800 CST
  • Martin Hope
    andre_ss6 Área de trabalho remota congelando intermitentemente 2019-09-11 12:56:40 +0800 CST
  • Martin Hope
    Riley Carney Por que colocar um ponto após o URL remove as informações de login? 2019-08-06 10:59:24 +0800 CST
  • Martin Hope
    zdimension Ponteiro do mouse movendo-se nas teclas de seta pressionadas no Windows? 2019-08-04 06:39:57 +0800 CST
  • Martin Hope
    jonsca Todos os meus complementos do Firefox foram desativados repentinamente, como posso reativá-los? 2019-05-04 17:58:52 +0800 CST
  • Martin Hope
    MCK É possível criar um código QR usando texto? 2019-04-02 06:32:14 +0800 CST
  • Martin Hope
    SoniEx2 Altere o nome da ramificação padrão do git init 2019-04-01 06:16:56 +0800 CST

Hot tag

windows-10 linux windows microsoft-excel networking ubuntu worksheet-function bash command-line hard-drive

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve