Automating backups for switch configs via ftp using psftp

This topic contains 4 replies, has 2 voices, and was last updated by Profile photo of Kerry Guillory Kerry Guillory 5 months, 3 weeks ago.

  • Author
    Posts
  • #55058
    Profile photo of Kerry Guillory
    Kerry Guillory
    Participant

    I downloaded the script below, and although it states the files are downloaded they do not. The problem seems to be with the passing of the credentials. I'm new to PowerShell, so I have no idea what to do. I really need to get this backup thing going.

    			
    The script
    
    Import-Module psftp
    #--------------------------------------------
    #---- Configurable variables ---------
    #--------------------------------------------
    
    $folderPath = "C:\switchConfigs"
    Write-Host "folderPath = $folderPath"
    $ftpServer = "10.0.0.238"
    Write-Host "ftpServer = $ftpServer"
    $ftpFolder = "/"
    Write-Host "ftpFolder = $ftpFolder"
    Write-Host "---------------------------------"
    
    #--------------------------------------------
    #---- empty folder $folderPath --------
    #--------------------------------------------
    Write-Host "Cleanning $folderPath"
    Remove-Tree $folderPath
    MkDir $folderPath 
    MkDir "$folderPath\Logs" 
    Invoke-Expression "explorer '/select,$folderPath'" 
    Write-Host "---------------------------------"
    Write-Host "Please check $folderPath exist"
    pause
    #--------------------------------------------
    #---- download files from ftp --------
    #--------------------------------------------
    Write-Host "Accesing FTP server"
    $ftp, $response, $stream, $reader = $null
    #Get ftp credentials.
    $ftp = [System.Net.FtpWebRequest]::Create("ftp://$ftpServer$ftpFolder")
    $ftp.Credentials = get-credential
    
    #Get a directory listing.
    Write-Host "Accesing FTP server - Get a directory listing."
    $ftp.Method = [System.Net.WebRequestMethods+Ftp]::ListDirectory
    $ftp.UseBinary = $true
    $ftp.UsePassive = $true
    $ftp.KeepAlive = $false
    $response = $ftp.GetResponse()
    $stream = $response.GetResponseStream()
    $reader = New-Object io.StreamReader($stream)
    $FTPFilereader = $reader.ReadToEnd()
    
    $ftpCredentials = New-Object System.Net.NetworkCredential
    Set-FTPConnection -Server $ftpServer -Credentials $ftp.Credentials -UseBinary -UsePassive
    #download all files
    Write-Host "Accesing FTP server - Downloading $folderPath..."
    
    $FTPFiles = $FTPFilereader.split([environment]::NewLine)
    foreach ($FTPFile in $FTPFiles ){
    if ($FTPFile){
    $FTPFilePath = "$ftpFolder$FTPFile"
    Write-Host "Downloading $FTPFilePath .. "
    Get-FTPItem -path $FTPFilePath -localpath $folderPath -Verbose
    Write-Host "-------------"
    }
    }
    Write-Host "Finished Downloading Files . .. "
    $FTPFilereader
    Write-Host "---------------------------------"
    Write-Host "---------------------------------"
    #--------------------------------------------
    #---- open downloaded folder --------
    #--------------------------------------------
    Invoke-Expression "explorer '/select,$folderPath'" 
    Write-Host "---------------------------------"
    Write-Host "Please check $folderPath has the files"
    pause
    Write-Host "---------------------------------"
    
    
    
    			The result
    
    PS H:\> c:
    
    PS C:\> \\admin-ds\users shared folders\XXXXXXX\MyScripts\ftpDownloadWithPotential.ps1
    folderPath = C:\switchConfigs
    ftpServer = 10.0.0.238
    ftpFolder = /
    ---------------------------------
    Cleanning C:\switchConfigs
    Remove-Tree : The term 'Remove-Tree' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the 
    spelling of the name, or if a path was included, verify that the path is correct and try again.
    At \\admin-ds\users shared folders\XXXXXXX\MyScripts\ftpDownloadWithPotential.ps1:18 char:1
    + Remove-Tree $folderPath
    + ~~~~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (Remove-Tree:String) [], CommandNotFoundException
        + FullyQualifiedErrorId : CommandNotFoundException
     
    MkDir : An item with the specified name C:\switchConfigs already exists.
    At \\admin-ds\users shared folders\XXXXXXX\MyScripts\ftpDownloadWithPotential.ps1:19 char:1
    + MkDir $folderPath
    + ~~~~~~~~~~~~~~~~~
        + CategoryInfo          : ResourceExists: (C:\switchConfigs:String) [New-Item], IOException
        + FullyQualifiedErrorId : DirectoryExist,Microsoft.PowerShell.Commands.NewItemCommand
     
    MkDir : An item with the specified name C:\switchConfigs\Logs already exists.
    At \\admin-ds\users shared folders\XXXXXXX\MyScripts\ftpDownloadWithPotential.ps1:20 char:1
    + MkDir "$folderPath\Logs"
    + ~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : ResourceExists: (C:\switchConfigs\Logs:String) [New-Item], IOException
        + FullyQualifiedErrorId : DirectoryExist,Microsoft.PowerShell.Commands.NewItemCommand
     
    ---------------------------------
    Please check C:\switchConfigs exist
    Press Enter to continue...: 
    Accesing FTP server
    cmdlet Get-Credential at command pipeline position 1
    Supply values for the following parameters:
    Accesing FTP server - Get a directory listing.
    Get-Credential : Cannot process argument transformation on parameter 'Credential'. userName
    At \\admin-ds\users shared folders\XXXXXXX\WindowsPowerShell\Modules\psftp\Set-FTPConnection.ps1:73 char:34
    +             $Credentials = Get-Credential $Credentials
    +                                           ~~~~~~~~~~~~
        + CategoryInfo          : InvalidData: (:) [Get-Credential], ParameterBindingArgumentTransformationException
        + FullyQualifiedErrorId : ParameterArgumentTransformationError,Microsoft.PowerShell.Commands.GetCredentialCommand
     
    
    
    ContentLength           : -1
    Headers                 : {}
    SupportsHeaders         : True
    ResponseUri             : ftp://10.0.0.238/
    StatusCode              : ClosingData
    StatusDescription       : 226 ASCII Transfer complete.
                              
    LastModified            : 1/1/0001 12:00:00 AM
    BannerMessage           : 220 FTP Server
                              
    WelcomeMessage          : 230 User admin logged in.
                              
    ExitMessage             : 221 Goodbye.
                              
    IsFromCache             : False
    IsMutuallyAuthenticated : False
    ContentType             : 
    
    Accesing FTP server - Downloading C:\switchConfigs...
    Downloading /9703595-2R1102HB.biz .. 
    VERBOSE: Performing the operation "Download item: 'ftp://10.0.0.238/9703595-2R1102HB.biz'" on target "".
    -------------
    Downloading /startup-config .. 
    VERBOSE: Performing the operation "Download item: 'ftp://10.0.0.238/startup-config'" on target "".
    -------------
    Downloading /startup-config.bak .. 
    VERBOSE: Performing the operation "Download item: 'ftp://10.0.0.238/startup-config.bak'" on target "".
    -------------
    Finished Downloading Files . .. 
    9703595-2R1102HB.biz
    startup-config
    startup-config.bak
    
    ---------------------------------
    ---------------------------------
    ---------------------------------
    Please check C:\switchConfigs has the files
    Press Enter to continue...: 
    ---------------------------------
    
    
    
    PS C:\> 
  • #55061
    Profile photo of Don Jones
    Don Jones
    Keymaster

    So, assuming you're referring to the FTP credentials, this really isn't PowerShell per se. I realize it's written in PowerShell, but it's really using low-level .NET classes, same as could be done in VB or C#. But the code looks correct to me – the problem is likely something in the interaction with your switch or its configuration. Unfortunately, I don't think I can really give you any pointers without access to your environment for troubleshooting.

    • #55068
      Profile photo of Kerry Guillory
      Kerry Guillory
      Participant

      Thanks for your time. I can do this with wget, but it requires multiple steps. The switches are adtran switches. AOS is not very complicated, and the switches are running an ftp server. The other down side to wget is that the creds need to be in the file.

      Can you maybe point me to a very basic powershell script that would be able to complete the ftp download (even if I have to put the creds in the script, so I can maybe figure out how to make it work for this purpose ?

      The wget example: wget -r -N ftp://backup:PASSWORD@10.0.0.200. I just have a series of these in a file, and paste them in a command prompt, so i don't have to run them all separately. It would be nice to automate the backup of the switch configs so I can run them as a scheduled task.

      Thanks again,
      Kerry

  • #55069
    Profile photo of Don Jones
    Don Jones
    Keymaster

    PowerShell doesn't have a native FTP function, so there really isn't a simple script. You could go down the .NET path, which is what your script has done, or you could find a 3rd-party FTP-specific command set. I'm a huge fan of Netcmdlets (http://www.netcmdlets.com), for example. Or see http://www.powertheshell.com/ftp_module/.

    But... if you're wanting to run this as a scheduled task, you're still going to have to store the password in a file someplace. PowerShell doesn't eliminate that need. So you're going to be in the same bucket regardless, no? Get-Credential is always going to want to visually prompt for a password.

  • #55070
    Profile photo of Kerry Guillory
    Kerry Guillory
    Participant

    Thank you for your patience with me. I will check out the links. I bet they will help me through the learning curve.

You must be logged in to reply to this topic.