标签:ssh powershell
PS本身是基于.NET框架的脚本开发工具,要想直接在Linux上运行,那几乎是不可能的。
了解Ansible的同学应该都知道其原理,PS也一样可以实现其相同的功能,要想完全拷贝,还是要下一番功夫的,这里呢只是简单介绍通过PS远程连接到Linux服务器。
PS要连接Linux服务器,我们需要先下载SSH模块,请下载附件,成功下载后请将其进行注册(直接放到 C:\Windows\System32\WindowsPowerShell\v1.0\Modules),再通过命令验证是否成功
import-model posh-ssh
posh-ssh模块支持很多功能,这里只写两个,一个是SSH Command,一个是SSH SFTP。
SSH SESSION
# #使用SSH协议连接服务器 #return Object @session # function ssh-connection{ param( [string][alias(‘s‘)]$computer, [int][alias(‘p‘)]$port=22, [string][alias(‘u‘)]$user, [string][alias(‘pw‘)]$pwd ) # #检查是否有配置连接信息 # if($computer -eq $null -or $user -eq $null -or $pwd -eq $null){ Write-Warning "Useage: conn -s ComputerName|IPAddress [-p Port] -u Username -pw Password" exit 1 } # #检查机器名称是否规范 # $computer=check -s $computer #if(!($session=Get-SSHSession|?{$_.host -eq $computer})){ $password = ConvertTo-SecureString $pwd -AsPlainText -Force $Credential = New-Object System.Management.Automation.PSCredential($user,$password) $session= try{ New-SshSession -ComputerName $computer -Port $port -Credential $Credential -AcceptKey Write-Host "A new ssh session has created,user $user logon on $computer" -fore Green }catch{ Write-Error $Error[0] #Write-Error "Can‘t ssh connection this server $computer,pls check." exit 1 } #} return $session }
SFTP-SESSION
# #使用SFTP协议连接服务器 #return Object @session # function sftp-connection{ param( [string][alias(‘s‘)]$computer, [int][alias(‘p‘)]$port=22, [string][alias(‘u‘)]$user, [string][alias(‘pw‘)]$pwd ) # #检查是否有配置连接信息 # if($computer -eq $null -or $user -eq $null -or $pwd -eq $null){ Write-Warning "Useage: sftp-connection -s ComputerName|IPAddress [-p Port] -u Username -pw Password" exit 1 } # #检查机器名称是否规范 # $computer=check -s $computer #if(!($session=Get-SSHSession|?{$_.host -eq $computer})){ $password = ConvertTo-SecureString $pwd -AsPlainText -Force $Credential = New-Object System.Management.Automation.PSCredential($user,$password) $session= try{ New-SFTPSession -ComputerName $computer -Port $port -Credential $Credential -AcceptKey Write-Host "A new sftp session has connected,user $user logon on $computer!" -fore Green }catch{ Write-Error "Can‘t sftp connection this server $computer,pls check." exit 1 } #} return $session }
在使用过程中为了防止建立多个SESSION的情况,写了一个判断当前服务器是否存在SESSION的脚本,如下:
# #检查SSH连接是否存在,如不存在则创建会话 #return Object @session # function IsConnectionned{ switch($args[0]){ ‘ssh‘ { $session=Get-SSHSession|?{$_.host -eq $computer} if(! $session){ ssh-connection -s $computer -u $user -pw $passwd }else{ if($session.gettype().isarray){ #如果当前存在多个Session连接,则只保留其中一个 for($i=1;$i -lt $session.count;$i++){ try{ $sessionid=$session[$i].sessionid Remove-SSHSession -SessionId $sessionid Write-Host "A ssh session has removed,sessionID is $sessionid" -fore Green }catch{ writelog $error[0] } } $session=$session[0] } } return $session } ‘sftp‘ { $session=Get-SFTPSession|?{$_.host -eq $computer} if(! $session){ $session=sftp-connection -s $computer -u $user -pw $passwd }else{ if($session.gettype().isarray){ #如果当前存在多个Session连接,则只保留其中一个 for($i=1;$i -lt $session.count;$i++){ try{ $sessionid=$session[$i].sessionid Remove-SSHSession -SessionId $sessionid Write-Host "A ssh session has removed,sessionID is $sessionid" -fore Green }catch{ writelog $error[0] } } $session=$session[0] } } return $session } } }
IsConnectionned 接受两个参数,一个是ssh,一个为sftp,ssh可以直接运行shell命令,sftp则为上传/下载文件 调用方法 IsConnectionned ssh|sftp
在Linux中,获取到的任何信息都是字符串,如果要更好的理解内容,需要通过awk或sed等工具进行处理。
这里我从Linux中获取到的用户信息,进行了对象化处理。
function Shell{ param( $command ) $session=IsConnectionned ssh $r=Invoke-SSHCommand -SSHSession $session -Command $command $r=$r.Output -split "\n" #Remove-SSHSession -SSHSession $session|Out-Null #Write-Host "Return follow message:" -fore Yellow return $r } function Get-LinuxUser{ $session=IsConnectionned ssh $r=Invoke-SSHCommand -SSHSession $session -Command "cat /etc/passwd" #Remove-SSHSession -SSHSession $session|Out-Null #Write-Host "Return follow message:" -fore Yellow $r = ($r.Output -split "\n") $arr=New-Object System.Collections.ArrayList foreach($u in $r){ $u=$u -split ":" $psobject = New-Object psobject Add-Member -MemberType NoteProperty -Name Server -Value $computer -InputObject $psobject Add-Member -MemberType NoteProperty -Name UserName -Value $u[0] -InputObject $psobject Add-Member -MemberType NoteProperty -Name Password -Value $u[1] -InputObject $psobject Add-Member -MemberType NoteProperty -Name UserUID -Value $u[2] -InputObject $psobject Add-Member -MemberType NoteProperty -Name UserGID -Value $u[3] -InputObject $psobject Add-Member -MemberType NoteProperty -Name Comment -Value $u[4] -InputObject $psobject Add-Member -MemberType NoteProperty -Name HomeDirectory -Value $u[5] -InputObject $psobject Add-Member -MemberType NoteProperty -Name Shell -Value $u[6] -InputObject $psobject [void]$arr.add($psobject) } return $arr Remove-Variable $u Remove-Variable $psobject Remove-Variable $arr } function Get-LinuxFileInfo{ param($filename) if(-not([string]::IsNullOrEmpty($filename)) -and ($filename -notmatch "\\")){ $command="ls -l --full-time $filename|awk " + "‘" + ‘{print ‘ + ‘$1‘ + ‘,‘+ ‘$2‘+ ‘,‘ + ‘$3‘+ ‘,‘ + ‘$4‘+ ‘,‘ + ‘$5‘+ ‘,‘ + ‘$6‘+ ‘,‘ + ‘$7‘+ ‘,‘ + ‘$8‘+ ‘,‘ + ‘$9‘ +‘} ‘ + "‘" $result=shell $command $reArray=$result -split ‘\n‘ $fileInfoList=New-Object System.Collections.ArrayList foreach($re in $reArray){ if($re -eq ""){ break } $re=$re -split ‘ ‘ $re[6]=($re[6] -split ‘\.‘)[0] $psobject=New-Object psobject Add-Member -MemberType NoteProperty -Name 服务器 -Value $computer -InputObject $psobject Add-Member -MemberType NoteProperty -Name 权限 -Value $re[0] -InputObject $psobject Add-Member -MemberType NoteProperty -Name 文件数 -Value $re[1] -InputObject $psobject Add-Member -MemberType NoteProperty -Name 用户 -Value $re[2] -InputObject $psobject Add-Member -MemberType NoteProperty -Name 组 -Value $re[3] -InputObject $psobject Add-Member -MemberType NoteProperty -Name 大小 -Value $re[4] -InputObject $psobject Add-Member -MemberType NoteProperty -Name 日期 -Value $re[5] -InputObject $psobject Add-Member -MemberType NoteProperty -Name 时间 -Value $re[6] -InputObject $psobject Add-Member -MemberType NoteProperty -Name 时区 -Value $re[7] -InputObject $psobject Add-Member -MemberType NoteProperty -Name 文件名 -Value $re[8] -InputObject $psobject [void]$fileInfoList.add($psobject) } return $fileInfoList }else{ Write-Warning "格式不正确或未指定Linux地址" exit 1 } }
除了用户信息外,还可以扩展其他内容,以后通过Powershell查看Linux信息,也是如此easy。
上传文件到Linux服务器 function Upload-ToLinux{ param( [alias(‘local‘)]$localPath, [alias(‘remote‘)]$remotePath ) #targetPath格式检查 if($remotePath -notmatch "/$"){ Write-Warning "RemotePath 格式错误,请以/结尾" exit 1 } $sftpsession=IsConnectionned "sftp" $r=Test-SFTPPath -SFTPSession $sftpsession $remotePath if((Test-Path $localPath) -and $r){ if(isDirectory $localPath){ #sourcePath格式检查 if($localPath -notmatch "\\$"){ Write-Warning "sourcePath 格式错误,请以\结尾" exit 1 } $password = ConvertTo-SecureString $passwd -AsPlainText -Force $Credential = New-Object System.Management.Automation.PSCredential($user,$password) Set-SCPFolder -ComputerName $computer -Credential $Credential -LocalFolder $localPath -RemoteFolder $remotePath -AcceptKey } if(isFile $localPath){ Set-SFTPFile -SFTPSession $sftpsession -LocalFile $localPath* -RemotePath $remotePath -Overwrite } }else{ Write-Warning "[本地路径] 或 [远程路径] 不存在" exit 1 } #Remove-SFTPSession -SFTPSession $sftpsession|Out-Null }
从Linux上下载文件 function Download-FromLinux{ param( [alias(‘remote‘)]$remotePath, [alias(‘local‘)]$localPath ) if($remotePath -eq $null -or $localPath -eq $null){ Write-Warning "Usage: Download-FromLinx -remote RemotePath -local LocalPath" exit 1 } if(! (Test-Path $localPath)){ [void](mkdir $localPath) } $password = ConvertTo-SecureString $passwd -AsPlainText -Force $Credential = New-Object System.Management.Automation.PSCredential($user,$password) try{ $session = IsConnectionned sftp Get-SFTPFile -SFTPSession $session -RemoteFile $remotePath -LocalPath $localPath -Overwrite } catch{ if(($error[0] -match "not a regular file") -or ($error[0] -match "path is not a file")){ $ws = New-Object -ComObject WScript.Shell $flag=$ws.Popup("远程地址是一个目录,请确认是否下载","10","请您选择",1) if($flag -eq 1){ Get-SCPFolder -ComputerName $computer -Credential $Credential -LocalFolder $localPath -RemoteFolder $remotePath -AcceptKey -Verbose } } else{ Write-Error $error[0] } } }
本文出自 “bxing” 博客,请务必保留此出处http://bxing.blog.51cto.com/1677994/1877406
标签:ssh powershell
原文地址:http://bxing.blog.51cto.com/1677994/1877406