文章目錄
- abstract
- 為什么考慮命令行連接
- 討論主題
- powershell遠程控制
- 使用PowerShell遠程管理
- 前提條件:
- 步驟:
- 1. 啟用WinRM服務
- 2. 配置信任主機
- 3. 測試連接
- 4. 創建遠程會話
- 5. 運行遠程命令
- 6. 關閉會話
- 例子
- 小結
- SSH方案
- 基礎連接
- 免密自動登錄
- 修改配置文件
- 在ssh server端創建支持免密登錄的公鑰文件
- 重啟服務
- 嘗試免密登錄
- 配置默認shell
abstract
- 對于兩臺windows設備,統一網絡下經常用遠程桌面來控制(mstsc)
- 而用命令行來控制也是可以的,雖然windows主打可視化操作而非命令行,但是命令行也可以執行很多基礎操作
- 命令行下,可以執行比如文件管理,資源下載,軟件安裝不在話下,也可以利用vscode等代碼編輯器借助Remote-SSH遠程編輯代碼
為什么考慮命令行連接
-
命令行連接的一個好處在于資源消耗小,連接快捷,體驗一致性好
-
另外,現在windows命令行中也可以做到以管理員方式運行命令行
-
windows 11 24h2開始開發者模式中支持sudo運行
-
而windows10也可以安裝一些命令行工具比如
scoop
,然后下載諸如gsudo
等工具實現類似效果 -
PS> scoop search sudo Results from local buckets...Name Version Source Binaries ---- ------- ------ -------- gsudo 2.4.4 main psutils 0.2023.06.28 main sudo.ps1 sudo 0.2020.01.26 main nsudo 8.2 extras
-
討論主題
- 假設局域網內我有兩臺windows設備,如何在設備A用命令行控制另一臺設備B?
- 也就是說,把設備B作為server,設備A作為Client
powershell遠程控制
在局域網內,你可以通過多種方法在設備A上使用命令行控制設備B。下面介紹一種常見的方法,即使用PowerShell和Windows遠程管理(WinRM)。
使用PowerShell遠程管理
前提條件:
- 啟用WinRM服務:WinRM服務需要在兩臺設備上啟用。
- 配置信任主機:設備A需要信任設備B。
- 用戶權限:確保你有足夠的權限來執行遠程命令。
步驟:
1. 啟用WinRM服務
在設備A和設備B上,都需要啟用WinRM服務。打開PowerShell并運行以下命令:
Enable-PSRemoting -Force
2. 配置信任主機
在設備A上,配置信任主機,使其可以與設備B進行通信。假設設備B的IP地址是$ip=192.168.1.198
:
$ip=192.168.1.198 #根據自己的情況修改
配置設備B為信任設備
Set-Item WSMan:\localhost\Client\TrustedHosts -Value "$ip"
你可以用逗號分隔多個IP地址。如果你想信任所有主機,可以使用通配符*
,但這可能會有安全風險:
Set-Item WSMan:\localhost\Client\TrustedHosts -Value "*"
3. 測試連接
在設備A上,使用以下命令測試與設備B的連接:
Test-WsMan -ComputerName $ip
如果一切正常,你應該看到一個成功的響應。
例如
PS C:\repos\scripts> Test-WsMan -ComputerName $ipwsmid : http://schemas.dmtf.org/wbem/wsman/identity/1/wsmanidentity.xsd
ProtocolVersion : http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd
ProductVendor : Microsoft Corporation
ProductVersion : OS: 0.0.0 SP: 0.0 Stack: 3.0
4. 創建遠程會話
在設備A上,創建一個到設備B的遠程會話:
$s = New-PSSession -ComputerName $ip -Credential (Get-Credential)
此命令會提示你輸入設備B的用戶名和密碼。
5. 運行遠程命令
現在,你可以在設備A上運行命令來控制設備B。例如,查看設備B上的進程:
Invoke-Command -Session $s -ScriptBlock { Get-Process }
6. 關閉會話
完成操作后,記得關閉遠程會話:
Remove-PSSession -Session $s
例子
假設你想在設備A上獲取設備B的主機名。你可以運行以下命令:
Invoke-Command -Session $s -ScriptBlock { hostname}
PS C:\Users\cxxu> Invoke-Command -Session $s -ScriptBlock { hostname}
RedmiBookPC
而查看目錄可能不會得到正確的結果
PS C:\repos\scripts> invoke-command -Session $s -ScriptBlock {ls C:\share}Directory: C:\shareMode LastWriteTime Length Name PSComputerName
---- ------------- ------ ---- --------------192.168.1.198192.168.1.198192.168.1.198192.168.1.198
通過以上步驟,你就可以在設備A上通過命令行控制設備B了。如果在過程中遇到任何問題,請檢查防火墻設置或用戶權限。
小結
- 這種方式不是很優雅,連貫性和便利性不足
SSH方案
windows上需要手動安裝ssh server軟件(拓展模塊),并且配置防火墻和服務自啟動等設置
Get started with OpenSSH for Windows | Microsoft Learn
此外,官方文檔還介紹了更多連接以及可以自定義配置的方案
Key-based authentication in OpenSSH for Windows | Microsoft Learn
OpenSSH Server configuration for Windows | Microsoft Learn
中文文檔:
適用于 Windows 的 OpenSSH 服務器配置 | Microsoft Learn
基礎連接
-
在server端安裝必要的ssh服務軟件
-
管理員方式運行powershell執行以下內容:
# Install the OpenSSH Server Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
-
詳情另見它文(防火墻配置等)
-
-
Client連接Server
-
一般的連接命令行格式
ssh user@server
-
如果兩個設備都開啟了網絡發現,那么可以用以下格式連接:``ssh user@serverName`
-
對于小型網絡通常不用關心域,完整格式其實是
ssh domain\username@servername
,而經常省略掉domain\
這部分內容 -
PS C:\Users\cxxu> ssh cxxu@redmibookpc #如果是初次連接,會有一段安全詢問,通常輸入yes即可 cxxu@redmibookpc's password: Microsoft Windows [版本 10.0.19045.4529] (c) Microsoft Corporation。保留所有權利。cxxu@REDMIBOOKPC C:\Users\cxxu>
-
-
否則用
ssh user@serverIp
來連接-
PS> ssh cxxu@192.168.1.198 #如果是初次連接,會有一段安全詢問,通常輸入yes即可(這里演示第一次連接的詢問) The authenticity of host '192.168.1.198 (192.168.1.198)' can't be established. ED25519 key fingerprint is SHA256:+iQOIn71iEoPaKOzM8PXC7vyqCY3QC8yGolnxdN2ncs. This host key is known by the following other names/addresses:C:\Users\cxxu/.ssh/known_hosts:13: redmibookpc Are you sure you want to continue connecting (yes/no/[fingerprint])? yes Warning: Permanently added '192.168.1.198' (ED25519) to the list of known hosts. cxxu@192.168.1.198's password: Microsoft Windows [版本 10.0.19045.4529] (c) Microsoft Corporation。保留所有權利。cxxu@REDMIBOOKPC C:\Users\cxxu>
-
-
免密自動登錄
- 和linux server類似,但是windows 中需要修改的
ssh
服務器端的配置文件位置和linux不同(畢竟文件系統不同) - 一般在
C:\ProgramData\ssh
目錄下面的sshd_config
文件中 - 這里給出簡單的過程,完善的文檔參考前面列出的參考文檔鏈接
修改配置文件
-
您可以嘗試用
type C:\ProgramData\ssh\sshd_config
命令行來查看配置文件中的內容 -
默認情況下的配置文件無法直接免密登錄,您需要修改部分內容(其實默認文件中大多都是注釋語句,有些需要我們解開注釋,有些需要我們轉為注釋)
- 參考:在Windows Server 之間配置SSH 免密登錄 - LearningAlbum - 博客園 (cnblogs.com)
-
這里直接給出我已經修改過的一個可以免密登錄ssh的配置文件(sshd_config)
# This is the sshd server system-wide configuration file. See # sshd_config(5) for more information.# The strategy used for options in the default sshd_config shipped with # OpenSSH is to specify options with their default value where # possible, but leave them commented. Uncommented options override the # default value.#Port 22 #AddressFamily any #ListenAddress 0.0.0.0 #ListenAddress ::#HostKey __PROGRAMDATA__/ssh/ssh_host_rsa_key #HostKey __PROGRAMDATA__/ssh/ssh_host_dsa_key #HostKey __PROGRAMDATA__/ssh/ssh_host_ecdsa_key #HostKey __PROGRAMDATA__/ssh/ssh_host_ed25519_key# Ciphers and keying #RekeyLimit default none# Logging #SyslogFacility AUTH #LogLevel INFO# Authentication:#LoginGraceTime 2m #PermitRootLogin prohibit-password #StrictModes yes #MaxAuthTries 6 #MaxSessions 10PubkeyAuthentication yes# The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2 # but this is overridden so installations will only check .ssh/authorized_keys AuthorizedKeysFile .ssh/authorized_keys#AuthorizedPrincipalsFile none# For this to work you will also need host keys in %programData%/ssh/ssh_known_hosts #HostbasedAuthentication no # Change to yes if you don't trust ~/.ssh/known_hosts for # HostbasedAuthentication #IgnoreUserKnownHosts no # Don't read the user's ~/.rhosts and ~/.shosts files #IgnoreRhosts yes# To disable tunneled clear text passwords, change to no here! #PasswordAuthentication yes #PermitEmptyPasswords no# GSSAPI options #GSSAPIAuthentication no#AllowAgentForwarding yes #AllowTcpForwarding yes #GatewayPorts no #PermitTTY yes #PrintMotd yes #PrintLastLog yes #TCPKeepAlive yes #UseLogin no #PermitUserEnvironment no #ClientAliveInterval 0 #ClientAliveCountMax 3 #UseDNS no #PidFile /var/run/sshd.pid #MaxStartups 10:30:100 #PermitTunnel no #ChrootDirectory none #VersionAddendum none# no default banner path #Banner none# override default of no subsystems Subsystem sftp sftp-server.exe# Example of overriding settings on a per-user basis #Match User anoncvs # AllowTcpForwarding no # PermitTTY no # ForceCommand cvs server# Match Group administrators # AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys
其實總得就保留了三條配置,其余都是注釋掉:(不同版本的openssh server可能有所不同)
PubkeyAuthentication yes AuthorizedKeysFile .ssh/authorized_keys Subsystem sftp sftp-server.exe
在ssh server端創建支持免密登錄的公鑰文件
-
默認情況下,這個文件為
~/.ssh/authorized_keys
-
方式有多種,以下方案提供的命令行直接在ssh client的命令行中執行(powershell)
-
首先確定Client端的公鑰文件位置
-
$pubkey="$home\.ssh\id_*pub"
-
其中
id_*pub
可能需要您補全(比如id_ed25519.pub
),特別是您創建了多個不同的ssh key時,如果創建過一個,那么通常可以不修改直接執行
-
-
可以從而ssh client端上傳到server
-
# $server='redmibookpc' #局域網內啟用網絡發現的話可以直接用計算機名 $server='192.168.1.198' #更通用的是使用server的ip地址 scp $pubkey $user_name@${Server}:~/.ssh/authorized_keys
-
-
也可以復制公鑰到剪切板,然后登錄到server中創建相應文件
-
查看公鑰
type $pubkey #該值同上述指定
-
復制輸出的內容,在Server端創建文件
~/.ssh/authorized_keys
,并插入復制的內容
-
重啟服務
Restart-Service sshd
嘗試免密登錄
PS> ssh cxxu@redmibookpc
Microsoft Windows [版本 10.0.19045.4529]
(c) Microsoft Corporation。保留所有權利。
如果順利的話,就可以登錄到遠程windows server (ssh),默認命令行shell是cmd
輸入powershell
或pwsh
可以切換shell
配置默認shell
-
適用于 Windows 的 OpenSSH 服務器配置 | Microsoft Learn
-
windows ssh server默認的shell是cmd,這是一個過時的shell
-
我們可以更改為powershell或其他shell
-
首先查看openssh是否安裝在默認路徑:
PS> $env:path -split ';'|sls sshC:\WINDOWS\System32\OpenSSH\
-
然后需要修改注冊表,并且可以通過一個一句就可以實現修改
-
首先登錄到windows ssh server,確保shell處于管理員模式
-
然后選擇以下一個語句進行執行
-
修改為自帶的powershell版本
New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -PropertyType String -Force
-
修改為powershell7
New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\Program Files\powershell\7\pwsh.exe" - PropertyType String -Force
-
-
示例:修改為powershell7
PS> New-ItemProperty -Path "HKLM:\SOFTWARE\OpenSSH" -Name DefaultShell -Value "C:\Program Files\powershell\7\pwsh.exe" - PropertyType String -ForceDefaultShell : C:\Program Files\powershell\7\pwsh.exe PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\OpenSSH PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE PSChildName : OpenSSH PSDrive : HKLM PSProvider : Microsoft.PowerShell.Core\Registry
從ssh Client 建立ssh連接,可以看到,默認shell為powershell7
PS> ssh cxxu@redmibookpc PowerShell 7.4.3 PS C:\Users\cxxu>