我们被要求检查文件是否存在于SFTP远程目录中,在我们组织外的服务器上,如果确实存在,则发送电子邮件。
我有IP地址,账号和密码。
我找到了这个powershell脚本https://www.tech2tech.fr/powershell-surveiller-des-fichiers-avec-envoi-de-mail/,但是…如何使用凭据访问远程目录,使其在远程目录上工作?
我也尝试使用ftp命令,但无法找到检查是否存在多个文件的方法,而不是只有一个。
有没有人有解决方案或方法来帮助我?
提前感谢!
你需要从这里开始:
$cred = Get-StoredCredential -Target creds;
$SFTPSession = New-SFTPSession -ComputerName sftp.server.org -Credential $cred
Test-SFTPPath $SFTPSession "/path/filename.txt" # check if file exist
Remove-SFTPSession -SessionID 0 -Verbose
Get-SFTPSession # ensure the session is closed
您可以添加条件并发送邮件:
Send-MailMessage -To “<recipient’s email>” -From “<sender’s email>” -Subject
“message subject” -Body “Some text!” -Credential (Get-Credential) -SmtpServer
“<smtp server>” -Port 587
尝试使用ssh模块。您可以将密码作为纯字符串存储在脚本中,但是最好使用Import-Clixml来安全地存储凭据。查看这两个模块的在线文档。
# Install and import module
Install-Module Posh-SSH
Import-Module Posh-SSH
$host = <sftp-location>
$port = <port>
#Set Credentials
$user = <username>
$pass = ConvertTo-SecureString <password> -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ($user, $pass)
$path = <location to check>
# Initiate SFTP session
$session = New-SFTPSession -ComputerName $host -Credential $Credential -Port $port -AcceptKey:$true
# Check if files exist on specified location
Test-SFTPPath -SFTPSession $session -Path $path
# Check if more than one file
$items = Get-SFTPChildItem -SFTPSession $session -Path $path
if($items -gt 1) {
<your code>
}
# close session
Remove-SFTPSession -SFTPSession $session
下面是我使用的:
Install and import module
Install-Module Posh-SSH
Import-Module Posh-SSH
$SFTPhost = "My_SFTP_Server"
$port = "22"
#Set Credentials
$user = "test_sftp"
$pass = ConvertTo-SecureString -String "******" -AsPlainText -Force
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $user, $pass
$path = "/Prod/saved"
# Initiate SFTP session
$session = New-SFTPSession -ComputerName $SFTPhost -Credential $Credential -Port $port -AcceptKey:$true
# Check if files exist on specified location
Test-SFTPPath -SFTPSession $session -Path $path
# Check if more than one file
$items = (Get-SFTPChildItem -SFTPSession $session -Path $path | measure-object).count
if($items_path -gt 1) {
Send-MailMessage -To 'toto <toto@MyDomain.com>' -From 'No Reply Check <no_reply_CheckFiles@MyDomain.com>' -Subject 'Files on server' -Body 'There is files in PROD repertory' -SmtpServer “My_SMTP_server_Address”
}
# close session
Remove-SFTPSession -SFTPSession $session