我们被要求检查文件是否存在于SFTP远程目录中,是否存在于我们组织之外的服务器上,如果确实存在,则发送电子邮件。
我有IP地址,帐户和密码。
我找到了这个powershell脚本https://www.tech2tech.fr/powershell-surveiller-des-fichiers-avec-envoi-de-mail/但是..。如何使它在远程目录上工作,使用凭据访问它?
我还尝试使用ftp命令,但无法找到一种方法来检查是否存在多个文件,而不仅仅是一个。
有人有办法或方法帮我吗?
提前谢谢!
发布于 2022-11-25 10:57:48
你需要从这里开始:
$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
发布于 2022-11-25 10:59:17
尝试使用Posh-SSH模块。您可以在脚本中以普通字符串的形式存储密码,但最好使用Import来安全地存储凭据。查看这两个模块的在线文档。
# 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
发布于 2022-11-30 16:17:47
谢谢大家!
在你的帮助下,我完成了这项任务。
以下是我所用的:
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
https://stackoverflow.com/questions/74571281
复制相似问题