none
VBScript para acessar e enviar arquivos via FTP RRS feed

  • Pergunta

  • Amigos,

    Tenho o seguinte script, e ele esta funcionando exatamente como preciso exceto o fato dele estar pedindo para fazer o upload do arquivo 2x. Já olhei as linhas mas não descobri o porque ele está fazendo isso.

    Alguem poderia me dar uma força?? Valeu!!

    '------------------------------------------------------------------------------ 
    Const appName = "FTP Upload Utility" 
    '------------------------------------------------------------------------------
    
    Const defaultHostname = "servidor ftp" 
    Const defaultPort = 21 
    Const defaultUsername = "usuarioFTP" 
    Const defaultPassword = "senha" 
    Const defaultRemoteDir = "/pasta remota"
    
    ' set this var to the fully qualified path of a local file to prevent file 
    ' selection dialog from being displayed 
    defaultFile = "" 
    
    
    ' if useDefaultsExclusively = True, the default values above will be leveraged 
    ' as-is, meaning no override options will be prompted for. 
    Const useDefaultsExclusively = True 
    
    
    ' if skipConfirmation = True, the upload will be attempted without requesting 
    ' confirmation to commence. 
    Const skipConfirmation = False
    
    '------------------------------------------------------------------------------
    
    Set shell = CreateObject( "WScript.Shell" ) 
    defaultLocalDir = shell.ExpandEnvironmentStrings("%USERPROFILE%") & "\Desktop" 
    Set shell = Nothing
    
    hostname = GetNonEmptyValue(useDefaultsExclusively, defaultHostname, _ 
      "Enter FTP server remote hostname:", "Hostname")
    
    port = GetNonEmptyValue(useDefaultsExclusively, defaultPort, _ 
      "Enter FTP server remote port:", "Port")
    
    username = GetNonEmptyValue(useDefaultsExclusively, defaultUsername, _ 
      "Enter username:", "Username")
    
    password = GetNonEmptyValue(useDefaultsExclusively, defaultPassword, _ 
      "Enter password:", "Password")
    
    If Len(defaultFile) > 0 Then 
      file = defaultFile 
    Else 
      file = ChooseFile(defaultLocalDir) 
      TestNotEmpty file, "Upload File" 
    End If
    
    Set fso = CreateObject("Scripting.FileSystemObject") 
    localFile = fso.getFileName(file) 
    localDir = fso.getParentFolderName(file) 
    Set fso = Nothing
    
    remoteDir = GetNonEmptyValue(useDefaultsExclusively, defaultRemoteDir, _ 
      "Remote upload directory:", "Remote Directory")
    
    Msg = "Você está carregando o arquivo " & localFile & " em ftp://" & _ 
      username & "@" & hostname & ":" & port & remoteDir & _ 
      vbCRLF & _ 
      vbCRLF & "Nota - Isso pode levar algum tempo!" & _ 
      vbCRLF & _ 
      vbCRLF & "Clique OK para iniciar o carregamento."
    
    ' VB appears to evaluate all the "OR" conditions when using if t1 OR t2 then ... 
    ' hence, it does not stop testing the conditions after the first condition 
    ' it detects is true. Thus the silly logic below... 
    If skipConfirmation Then 
      Upload hostname, port, username, password, localFile, localDir, remoteDir 
    ElseIf vbOK = MsgBox(Msg, vbOKCancel, appName) Then 
      Upload hostname, port, username, password, localFile, localDir, remoteDir 
    End If
    
    '------------------------------------------------------------------------------
    
    Function GetNonEmptyValue(useDefaultExclusively, defaultValue, prompt, dialogTitle)
    
      If useDefaultExclusively Then 
        value = defaultValue 
      Else 
        value = InputBox(prompt, dialogTitle, defaultValue) 
      End If
    
      TestNotEmpty value, dialogTitle 
      GetNonEmptyValue = value 
    End Function
    
    '------------------------------------------------------------------------------
    
    Sub TestNotEmpty(value, description) 
      If Len(value) = 0 Then 
        MsgBox "ERROR: No value provided for " & description, vbExclamation, appName 
        wscript.quit 
      End If 
    End Sub
    
    '------------------------------------------------------------------------------
    
    Set shell = CreateObject( "WScript.Shell" )
    defaultLocalDir = shell.ExpandEnvironmentStrings("%USERPROFILE%") & "\Desktop"
    Set shell = Nothing
    
    file = ChooseFile(defaultLocalDir)
    MsgBox file
    
    Function ChooseFile (ByVal initialDir)
        Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
    
        Set colItems = objWMIService.ExecQuery("Select * from Win32_OperatingSystem")
        Dim winVersion
    
        ' This collection should contain just the one item
        For Each objItem in colItems
            'Caption e.g. Microsoft Windows 7 Professional
            'Name e.g. Microsoft Windows 7 Professional |C:\windows|...
            'OSType e.g. 18 / OSArchitecture e.g 64-bit
            'Version e.g 6.1.7601 / BuildNumber e.g 7601
            winVersion = CInt(Left(objItem.version, 1))
        Next
        Set objWMIService = Nothing
        Set colItems = Nothing
    
        If (winVersion <= 5) Then
            ' Then we are running XP and can use the original mechanism
            Set cd = CreateObject("UserAccounts.CommonDialog")
            cd.InitialDir = initialDir
            cd.Filter = "ZIP files|*.zip|Text Documents|*.txt|Shell Scripts|*.*sh|All Files|*.*"
            ' filter index 4 would show all files by default
            ' filter index 1 would show zip files by default
            cd.FilterIndex = 1
            If cd.ShowOpen = True Then
                ChooseFile = cd.FileName
            Else
                ChooseFile = ""
            End If
            Set cd = Nothing    
    
        Else
            ' We are running Windows 7 or later
            Set shell = CreateObject( "WScript.Shell" )
            Set ex = shell.Exec( "mshta.exe ""about: <input type=file id=X><script>X.click();new ActiveXObject('Scripting.FileSystemObject').GetStandardStream(1).WriteLine(X.value);close();resizeTo(0,0);</script>""" )
            ChooseFile = Replace( ex.StdOut.ReadAll, vbCRLF, "" )
    
            Set ex = Nothing
            Set shell = Nothing
        End If
    End Function    
    
    '------------------------------------------------------------------------------
    
    Sub Upload(hostname, port, username, password, localFile, localDir, remoteDir)
    
      Set shell = CreateObject("WScript.Shell") 
      Set fso = CreateObject("Scripting.FileSystemObject")
    
      tempDir = shell.ExpandEnvironmentStrings("%TEMP%") 
      ' temporary script file supplied to Windows FTP client 
      scriptFile = tempDir & "\" & fso.GetTempName 
      ' temporary file to store standard output from Windows FTP client 
      outputFile = tempDir & "\" & fso.GetTempName
    
      'input script 
      script = script & "lcd " & """" & localDir & """" & vbCRLF 
      script = script & "open " & hostname & " " & port & vbCRLF 
      script = script & "user " & username & vbCRLF 
      script = script & password & vbCRLF 
      script = script & "cd " & """" & remoteDir & """" & vbCRLF 
      script = script & "binary" & vbCRLF 
      script = script & "prompt n" & vbCRLF 
      script = script & "put " & """" & localFile & """" & vbCRLF 
      script = script & "quit" & vbCRLF
    
      Set textFile = fso.CreateTextFile(scriptFile, True) 
      textFile.WriteLine(script) 
      textFile.Close 
      Set textFile = Nothing
    
      ' bWaitOnReturn set to TRUE - indicating script should wait for the program 
      ' to finish executing before continuing to the next statement 
      shell.Run "%comspec% /c FTP -n -s:" & scriptFile & " > " & outputFile, 0, True 
      Wscript.Sleep 500 
      ' open standard output temp file read only, failing if not present 
      Set textFile = fso.OpenTextFile(outputFile, 1, 0, -2) 
      results = textFile.ReadAll 
      textFile.Close 
      Set textFile = Nothing 
      If InStr(results, "550") > 0 And InStr(results, "226") Then 
        fso.DeleteFile(scriptFile) 
        fso.DeleteFile(outputFile) 
        Msg ="ATENÇÃO: O Diretório de destino não foi alterado!!" & _ 
          vbCRLF & "No entanto o arquivo foi carregado no diretório informado." & _ 
          "O Diretório FTP foi associado com o usuário informado." 
        MsgBox Msg, vbExclamation, appName
    
      ElseIf InStr(results, "226") > 0 Then 
        MsgBox "Arquivo carregado com sucesso!!.", vbInformation, appName 
        fso.DeleteFile(scriptFile) 
        fso.DeleteFile(outputFile) 
      Else 
        If InStr(results, "530") > 0 Then 
          Msg ="ERROR: Invalid Username/Password" 
        ElseIf InStr(results, "550") > 0 Then 
          Msg ="ERROR: Could not change to destination directory on host" 
        ElseIf InStr(results, "553") > 0 Then 
          Msg ="ERROR: Could not create file on host" 
        ElseIf InStr(results, "Unknown host") > 0 Then 
          Msg ="ERROR: Unknown host" 
        ElseIf InStr(results, "File not found") > 0 Then 
          Msg ="ERROR: Local File Not Found" 
        Else 
          Msg ="An ERROR may have occurred." 
        End If
    
        Msg = Msg & _ 
         vbCRLF & "Script file leveraged: " & scriptFile & _ 
         vbCRLF & "FTP Output file: " & outputFile & _ 
         vbCRLF & _ 
         vbCRLF & "Ensure the above files are manually deleted, as they may " & _ 
         "contain sensitive information!" 
         Wscript.Echo Msg 
        MsgBox Msg, vbCritical, appName 
      End If 
      Set shell = Nothing 
      Set fso = Nothing
    
    End Sub

    segunda-feira, 20 de julho de 2015 21:07

Respostas

  • Reveja a lógica do script, no primeiro bloco ele pede que selecione o arquivo e logo a frente faz o processo de upload:

    If Len(defaultFile) > 0 Then 
      file = defaultFile 
    Else 
      file = ChooseFile(defaultLocalDir) 
      TestNotEmpty file, "Upload File" 
    End If

    Neste bloco ele pede que selecione o arquivo e apenas exibe o caminho completo do mesmo:

    Set shell = CreateObject( "WScript.Shell" )
    defaultLocalDir = shell.ExpandEnvironmentStrings("%USERPROFILE%") & "\Desktop"
    Set shell = Nothing
    
    file = ChooseFile(defaultLocalDir)
    MsgBox file

    • Marcado como Resposta Walter_Santos terça-feira, 21 de julho de 2015 12:02
    terça-feira, 21 de julho de 2015 01:09

Todas as Respostas

  • Reveja a lógica do script, no primeiro bloco ele pede que selecione o arquivo e logo a frente faz o processo de upload:

    If Len(defaultFile) > 0 Then 
      file = defaultFile 
    Else 
      file = ChooseFile(defaultLocalDir) 
      TestNotEmpty file, "Upload File" 
    End If

    Neste bloco ele pede que selecione o arquivo e apenas exibe o caminho completo do mesmo:

    Set shell = CreateObject( "WScript.Shell" )
    defaultLocalDir = shell.ExpandEnvironmentStrings("%USERPROFILE%") & "\Desktop"
    Set shell = Nothing
    
    file = ChooseFile(defaultLocalDir)
    MsgBox file

    • Marcado como Resposta Walter_Santos terça-feira, 21 de julho de 2015 12:02
    terça-feira, 21 de julho de 2015 01:09
  • Funcionou perfeitamente!!! Não acredito que era só isso...

    Nada melhor do que uma cabeça fresca e de fora do problema para ter outra visão.

    Muito Obrigado!!

    terça-feira, 21 de julho de 2015 12:04