Home > Back-end >  Check if files exist in a FTP remote directory outside our domain
Check if files exist in a FTP remote directory outside our domain

Time:11-25

We have been asked to check if files exists in a SFTP remote directory, on a server outside our organisation, and send an email if it does exist.

I have the IP address, an account, and a password.

I found this powershell script https://www.tech2tech.fr/powershell-surveiller-des-fichiers-avec-envoi-de-mail/ , but... How can i make it work on a remote directory, using credential to access it?

I also try using ftp command, but can't find a way to check if many files exist, and not only one.

Does anyone have a solution or a way to help me?

Thanks in advance !

CodePudding user response:

You need to start from here:

$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

Than you can add a condition and send mail:

Send-MailMessage -To “<recipient’s email>” -From “<sender’s email>”  -Subject 
“message subject” -Body “Some text!” -Credential (Get-Credential) -SmtpServer 
“<smtp server>” -Port 587

CodePudding user response:

Try using the Posh-SSH module. You can store your password as a plain string in your script, but it would be better to use Import-Clixml to securely store credentials. Check out online documentation of both modules.

# 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 
  • Related