zl程序教程

您现在的位置是:首页 >  后端

当前栏目

powershell下ssh客户端套件实现

ssh客户端 实现 PowerShell 套件
2023-09-14 08:56:56 时间

有时会需要和Linux机器进行交互。所以这时就需要在Powershell中使用SSH

 

 

 

 

 

0x01 查找Powershell中的SSH功能模块

 

如图,显示没有find-module的命令,需要安装PackageManagement

 

 

下载地址:https://www.microsoft.com/en-us/download/details.aspx?id=51451

 

 

 

 

 

 

 

 

0x02 安装、使用SSH模块

A) Posh-SSH

Install-Module -Name Posh-SSH  安装Posh-SSH

 

 

 

可以通过下面的命令,查看安装的模块包含什么命令:

get-command -Module posh-ssh 

 

 

 

 

PowerShell中使用SSH

添加SSH会话命令:

New-SSHSession -ComputerName "192.168.190.148" -Credential (Get-Credential root)

 

 

 

 

获取SSH会话命令:

Get-SSHSession

 

 

 

删除SSH会话命令:

Remove-SSHSession -Index 0 -Verbose

 

 

 

 

执行SSH命令:

Invoke-SSHCommand -Index 0 -Command“uname -a”

 

 

 

 

添加SFTP会话命令:

New-SFTPSession -ComputerName 192.168.190.148 -Credential(Get-Credential root)

 

获取SFTP会话命令:

GET-SFTPSession

 

获取当前目录命令:

Get-SFTPCurrentDirectory -Index 0

 

切换到其他目录命令:

Set-SFTPDirectoryPath -Index 0 -Path / usr / bin

 

也可以一起写到脚本执行,比如我执行uname -adf -k两个命令

 

$username = "root" $password = "123456" $secure = $password | ConvertTo-SecureString -AsPlainText -Force $cred = New-Object System.Management.Automation.PSCredential($username,$secure)

 

New-SSHSession -ComputerName 192.168.190.148 -Credential $cred -AcceptKey

 

Invoke-SSHCommand -SessionId 0 -Command "uname -a" 

Invoke-SSHCommand -SessionId 0 -Command "df -k" 

 

执行脚本 注意替换脚本里的主机地址、账号、密码。

 

 

 

 

 

 

 

 

 

B)SSHSessions

 

Install-module -Name SSHSessions 安装SSHSessions

 

 

 

get-command -Module sshsessions  查看命令

 

 

 

 

建立一个新的ssh会话
New-SshSession -ComputerName 192.168.190.148 -Username root -Password 123456

Enter-SshSession -ComputerName 192.168.190.148 进入交互模式

 

 

 

 

 

 

也可以使用invoke-sshcommand的模式实现命令
Invoke-SshCommand -ComputerName 192.168.190.148 -Command "ifconfig"

 

大家还可以安装一下其他的ssh模块,实现在Powershell中的ssh功能。

 

 

 

 

 

 

 

 

 

 

0x03 删除SSH模块

 

例如删除posh-ssh模块

 

 

remove-module -name posh-ssh -Force -Verbose -Debug

 

 

 

 

同样还需要删除模块的目录

 

C:\Program Files\WindowsPowerShell\Modules 目录下为powershell安装的模块目录

 

 

 

 

删除即可

 

 

其他删除模块的方法也是一样的。