Kon*_*n V 22 powershell upload sftp automation
我们被要求设置从我们的一个服务器到SFTP站点的自动上传.每周一早上都会有一个文件从数据库导出到文件管理器,他们希望在星期二将文件上传到SFTP.我们使用的当前身份验证方法是用户名和密码(我相信有一个选项可以使用密钥文件,但选择了用户名/密码选项).
我想象的方法是让一个脚本坐在服务器上,由Windows任务调度程序触发,以便在特定时间(星期二)运行,该文件将获取有问题的文件,将其上传到SFTP,然后将其移动到用于备份目的的不同位置.
例如:
本地目录: C:\FileDump
SFTP目录: /Outbox/
备份目录: C:\Backup
我在这方面尝试了一些东西,WinSCP就是其中之一,以及SFTP PowerShell Snap-In,但到目前为止我没有任何工作.
这将在Windows Server 2012R2上运行.
当我运行Get-Host我的控制台主机版本是4.0.
谢谢.
Mar*_*ryl 56
您没有告诉我们您对WinSCP有什么特别的问题,所以我真的只能重复WinSCP文档中的内容.
WinSCP-5.15.7-Automation.zip;.zip沿着你的脚本档案;使用这样的代码(基于官方的PowerShell上传示例):
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Sftp
HostName = "example.com"
UserName = "user"
Password = "mypassword"
SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...="
}
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
# Upload
$session.PutFiles("C:\FileDump\export.txt", "/Outbox/").Check()
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
Run Code Online (Sandbox Code Playgroud)您可以让WinSCP为您上传生成PowerShell脚本:
您将获得上述代码,并填写所有会话和传输设置.
(我是WinSCP的作者)
小智 23
目前没有用于执行SFTP部分的内置PowerShell方法.你必须使用像psftp.exe或像Posh-SSH这样的PowerShell模块.
以下是使用Posh-SSH的示例:
# Set the credentials
$Password = ConvertTo-SecureString 'Password1' -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ('root', $Password)
# Set local file path, SFTP path, and the backup location path which I assume is an SMB path
$FilePath = "C:\FileDump\test.txt"
$SftpPath = '/Outbox'
$SmbPath = '\\filer01\Backup'
# Set the IP of the SFTP server
$SftpIp = '10.209.26.105'
# Load the Posh-SSH module
Import-Module C:\Temp\Posh-SSH
# Establish the SFTP connection
$ThisSession = New-SFTPSession -ComputerName $SftpIp -Credential $Credential
# Upload the file to the SFTP path
Set-SFTPFile -SessionId ($ThisSession).SessionId -LocalFile $FilePath -RemotePath $SftpPath
#Disconnect all SFTP Sessions
Get-SFTPSession | % { Remove-SFTPSession -SessionId ($_.SessionId) }
# Copy the file to the SMB location
Copy-Item -Path $FilePath -Destination $SmbPath
Run Code Online (Sandbox Code Playgroud)
一些额外的说明:
这应该给你一个不错的起点.
小智 9
我可以使用 PowerShell 进行 sftp,如下所示:
PS C:\Users\user\Desktop> sftp user@aa.bb.cc.dd
user@aa.bb.cc.dd's password:
Connected to user@aa.bb.cc.dd.
sftp> ls
testFolder
sftp> cd testFolder
sftp> ls
taj_mahal.jpeg
sftp> put taj_mahal_1.jpeg
Uploading taj_mahal_1.jpeg to /home/user/testFolder/taj_mahal_1.jpeg
taj_mahal_1.jpeg 100% 11KB 35.6KB/s 00:00
sftp> ls
taj_mahal.jpeg taj_mahal_1.jpeg
sftp>
Run Code Online (Sandbox Code Playgroud)
我没有安装 Posh-SSH 或类似的东西。我正在使用 Windows 10 专业版 PowerShell。没有安装额外的模块。
使用PuTTY的pscp.exe(我在$env:path目录中):
pscp -sftp -pw passwd c:\filedump\* user@host:/Outbox/
mv c:\filedump\* c:\backup\*
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
73548 次 |
| 最近记录: |