ssh同步两台电脑之间的blog
date: 2024/6/21
使用powershell中的posh-ssh来同步两台windows之间的blog文件。
该库中使用与FTP协议实现的命令时对路径识别不友好
remote: /path
local: /path
在使用下载文件的命令Get-SFTPItem时,这样能识别成功,会默认为系统盘c盘中去找相对应的路径,比如c:\path。如要指定d:/path或者/d/path或者d:\path反正该试的都试了都识别不了路径。在使用其他命令时正常。
$remoteMDFolder = "/D:/ruanjian/yx-tools/blog"
$localMDFolder = "D:\blog"
最后发现本地路径正常设置,远程路径设置如上就使用ftp协议实现的相关命令
对于ssh协议实现的命令在windows中直接只用c:\path就能行,无论local或者remote。所以最后考虑使用ssh协议的相关命令进行文件传输,ftp相关的命令对文件进行其他操作等。
https://github.com/darkoperator/Posh-SSH/blob/master/docs
核心代码入下:
# 建立 SSH 连接
$privateKey = New-Object System.Management.Automation.PSCredential $username, (New-Object System.Security.SecureString)
$session = New-SFTPSession -ComputerName $server -Credential $privateKey -KeyFile $keyFilePath -AcceptKey
# 读取私钥内容
$privateKeyContent = Get-Content $keyFilePath -Raw
# 创建一个空密码的 PSCredential 对象
$securePassword = ConvertTo-SecureString -String " " -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $securePassword
if ($session -eq $null) {
Write-Host "SSH 连接失败" -ForegroundColor Red
exit
}
# 设置远程文件内容
Set-SFTPContent -SessionId $SessionId -Path $MarkdownFilePath -Value $UpdatedContent -Verbose:$false | Out-Null
# 移动远程文件
Move-SFTPItem -SessionId $SessionId -Path $MarkdownFilePath -Destination $NewMarkdownFilePath -Verbose:$false | Out-Null
# 下载远程文件
Get-SCPItem -ComputerName $server -Credential $credential -KeyString $privateKeyContent -Path "$remoteFilePath" -PathType File -Destination "$local_path_dir" -Force
# 上传本地文件
Set-SCPItem -ComputerName $server -Credential $credential -KeyString $privateKeyContent -Path "$local_path" -Destination "$remoteFileFolder" -Force
# 创建远程目录
New-SFTPItem -SessionId $SessionId -Path $remote_path -ItemType Directory -Verbose:$false | Out-Null
# 获取远程文件夹下的子文件
$items = Get-SFTPChildItem -SessionId $SessionId -Path $Path