PowerShell や Python を使用してルーターを再起動するにはどうすればよいですか?

PowerShell や Python を使用してルーターを再起動するにはどうすればよいですか?

PowerShell を使用してルーターを再起動する方法は?

私のコンピュータはネットワーク ケーブルを使用してルーターに接続されており、ルーターはモデムとして機能し、PPPoE を介して ISP に接続し、私のコンピュータは NAT の背後にあります。

ルーターのモデル: Huawei HS8545M、LAN アドレス: 192.168.1.1、Web ページ管理者ログイン: CMCCAdmin、Web ページ管理者パスワード: aDm8H%MdA。

ルーターを再起動するには、次の手順を実行する必要があります (合計 7 回のクリック、ブラウザはログインとパスワードを記憶します)。

ここに画像の説明を入力してください

ここに画像の説明を入力してください

ステップが多すぎます。

私はこの方法を試してみました:

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

しかし、しばらくすると接続が失われ、.Document空になり、更新しようとすると次のエラーが発生します。

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

私は Windows 10 20H2 を使用しており、リモート デスクトップ、リモート アシスタンス、リモート レジストリ、Windows リモート管理、その他多くのものを無効にしています。リモート関連のものはセキュリティ上の脅威となるため無効にしましたが、これに関連していると思います。ちなみに、RPCサービスは実行中です。

誰か助けてくれませんか?


最初のページのソースコード:ページ1

2ページ目のソースコード:ページ2.html

これは簡単に実行できるはずです。192.168.1.1 にログインし、Cookie を作成し、その Cookie を使用して 192.168.1.1/index.asp にアクセスし、Restart_button を送信すれば完了です。ただし、ネットワークを扱うコマンドにはあまり詳しくありません...


現在、Python の方法を探しています。Python 3.9.1 amd64 を使用しており、ずっと前に PATH に追加し、pip 経由で Selenium と Twill をインストールしました。GeckoDriver.exe をダウンロードして Python インストール フォルダーに解凍しました。

Selenium、Twill、urllib、urllib2、cookielib、および webbot はすべてこれを実行できることはわかっていますが、現在、最善の方法でそれを実行する方法を模索しています。


twill 経由で Python のルーターにログインできましたが、次に何をすればよいかわかりません。

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

ここに画像の説明を入力してください

ボタン:

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

所在地は次のとおりです。

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

また、inputfields最初のページの(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

リセット ページのソース コードを入手しました:

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

住所:

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

Submit('btnSubmit')また、ログインできたかどうかも本当にわかりません。よくわかりません...

これは機能しますが、Firefox の初期化は非常に遅くなります。


ついに、telnet 方式でそれを実行する方法がわかりました。

telnet 192.168.1.1
root
adminHW
reset

コマンドを自動入力するスクリプトにするにはどうすればいいでしょうか?

答え1

SSH の方法

ルータが SSH アクセスをサポートしている場合 (ルータの設定で有効にする必要がある可能性があります)、SSH 経由でコマンドを発行してルータを再起動してみてください。

ssh USERNAME@ROUTER_ADDRESS rebootまたは のような感じになりますssh USERNAME@ROUTER_ADDRESS "sudo reboot"

  1. まず、SSH アクセスを有効にする必要があります。次のように入力して、SSH アクセスが機能することを確認しますssh USERNAME@ROUTER_ADDRESS(機能する場合は、パスワードの入力を求められます。正しいパスワードを入力すると、ルーターのコマンド プロンプトが表示されます)。
  2. 次に、ルーターを再起動するためにルーターのコマンド プロンプトに入力する必要があるコマンドを決定します。 だけの場合もありますが、 、 などrebootの正確なパスを指定する必要がある場合もあります。また、や などの権限を昇格する必要がある場合もあります。/sbin/reboot/usr/sbin/rebootsudo COMMANDsu -c 'COMMAND' root
  3. 前の 2 つの手順に合格すると、SSH () へのログインssh USERNAME@ROUTER_ADDRESSと再起動コマンドの発行 (例sudo reboot) を 1 つのコマンド (などssh USERNAME@ROUTER_ADDRESS "sudo reboot") に組み合わせることができます。毎回パスワードを求められますが、回避できます (この手順に到達し、パスワードの入力を避けたい場合は、コメントで私に知らせてください)。

HTTP の方法

ブラウザでネットワーク モニターを開き (たとえば、Firefox の場合はShift+ Ctrl+ E)、再起動を確認したときに発行された Web 要求を正確に特定します (たとえば、Firefox では、要求のデータ全体を確認できます)。

答え2

ここのユーザー Ligeti によると、同様のモデルは次のようになります。https://jalalsela.com/accessing-hg8245q-shell/

  • デバイスへのSSH/Telnet
  • ログインroot
  • 利用可能なコマンドを一覧表示するには/?

rebootここから、再起動などのコマンドを探したり、そこから / などの他の bash コマンドへのアクセス権を付与したりできます。何かshellに対する権限がないと表示された場合は、スーパー管理者になる手順が記載されていますが、必要ないと思います。shutdown -rhelp?

答え3

ついにそれをやってみましたが、とても簡単だとわかりました。

Python 3.9.1、Internet Explorer、Selenium、IEDriverServer.exe (32 ビット) を使用しました。

コード:

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

として保存しましたがRebootModem.py、うまく動作しますが、ルーターを再起動した後、ウィンドウが自動的に閉じられず、コードの実行が でハングしてie.switch_to.alert.accept()終了しないため、IE ウィンドウを手動で閉じる必要があります...

コンソールでコードを試してみたところ、ルーターの再起動が完了するまでコンソールはコマンドを受け入れないことがわかりました...

私は現在、webbot、urllib(2)、cookielib、twill を使ってこれを実行しようとしていますが、ブラウザに頼るのはあまり効率的ではないと思います。


次の方法で IE ウィンドウとスクリプトを自動的に閉じるようにしました。

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

を として保存しRebootModem.ps1、を実行して の実行を開始するRebootModem.pyと、15 秒後に IE ウィンドウと Python.exe (名前が IEDriverServer.exe に変更されます) が自動的に閉じられます...RebootModem.ps1RebootModem.py


コードを一般化するには、要素 ID をルーターの Web ページの要素 ID に置き換えるだけです。要素 ID はCtrl+ Shift+で取得できますI。アドレスは、見つけたアドレスに置き換えます (ただし、192.168.1.1 を変更する必要はおそらくありません)。モデムを再起動するために使用されるページのアドレスは、「フレーム ソースの表示」で取得しました。


PS すべてのネットワーク設定をリセットするために使用した完全なコード:

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

答え4

やってしまった…また!

PowerShell + VBScript + Telnet でこれを行う方法:

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

名前を付けて保存RebootModem.vbs

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

名前を付けて保存RebootModem.ps1

実行するRebootModem.ps1と、Telnet 経由でモデムが再起動し、6 秒後に Telnet.exe が自動的に閉じられます。


純粋な 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

3 秒以内に作業が完了します。これが最も効率的な方法だと私は判断しました。

関連情報