【问题标题】:Reading script and replacing specific line. vbscript读取脚本并替换特定行。脚本
【发布时间】:2020-07-21 01:48:08
【问题描述】:

我正在开发一个脚本来加密用户 Tacacs 密码,并将这个字符串写入另一个脚本。我的脚本打开,读取 Tacacs 密码并将其写入我的其他脚本,但它不会覆盖它。

第一次运行:

strTacacs = "Test1234"

第二次运行:

strTacacs = "Test1234"strTacacs = "Test1234"

我当前的脚本:

'***********Write to auto-logon script************

Const ForReading = 1
Const ForWriting = 2
newline = "strTacacs = " & chr(34) & Tacacs & chr(34)
line = 30


Set objFSO = CreateObject("Scripting.FileSystemObject")

Dim lineCount : lineCount = 0
Dim firstContent : firstContent = ""

Set objFolder = objFSO.GetFolder(objStartFolder)
Set colFiles = objFolder.Files
For Each objFile in colFiles
    If LCase(objFSO.GetExtensionName(objFile)) = "vbs" Then
        lineCount = 0
        firstContent = ""
        FileName = objStartFolder & objFile.Name
        Set objStream = objFSO.OpenTextFile(strFile, ForReading)
        Do Until objStream.AtEndOfStream
            lineCount = lineCount + 1
            firstContent = firstContent & objStream.ReadLine & vbCrLf
            'msgbox(firstContent)
            if lineCount = 30 Then 
                firstContent = firstContent & newline
                msgbox(firstContent)
            End if
        Loop  
        Set objStream = objFSO.OpenTextFile(FileName, ForWriting)
        objStream.WriteLine firstContent
        objStream.Close 
    End If  
Next

.

有人知道我做错了什么吗? 我是脚本领域的新​​手,非常感谢您的帮助!

谢谢!

【问题讨论】:

    标签: vbscript


    【解决方案1】:

    当您到达第 30 行时,您似乎正在编写原始行和新行。您应该只在 lineCount 为 30 时编写 newline,否则编写原始行:

    Do Until objStream.AtEndOfStream
        
        lineCount = lineCount + 1
        
        If lineCount = 30 Then
            ' Replace line with newline
            firstContent = firstContent & newline & vbCrLf
        Else
            ' Write original line
            firstContent = firstContent & objStream.ReadLine & vbCrLf
        End If
    Loop
    

    如果您知道原始文件中的密码,则可以使用ReadAll method一次性读取整个文件内容:

    Set objStream = objFSO.OpenTextFile(strFile, ForReading)
    firstContent = objStream.ReadAll
    

    然后用Replace替换密码,最后写回内容。

    如果您不知道密码并简单地替换特定行,您当前的逐行方法会更容易。您还可以检查行是否以 strTacacs = 开头,这使您无需对行号进行硬编码:

    Dim sLine
    Dim sPasswordLine
    sPasswordLine = "strTacas ="
    
    Do Until objStream.AtEndOfStream
    
        ' Read line
        sLine = objStream.ReadLine
    
        If Left(sLine, Len(sPasswordLine)) = sPasswordLine Then
            ' Replace line with newline
            firstContent = firstContent & newline & vbCrLf
        Else
            ' Write original line
            firstContent = firstContent & sLine & vbCrLf
        End If
        
    Loop
    

    【讨论】:

    • 很好的解释。
    猜你喜欢
    • 1970-01-01
    • 2021-01-10
    • 2011-02-14
    • 1970-01-01
    • 2016-02-20
    • 1970-01-01
    • 2020-10-13
    • 2013-06-27
    • 2013-11-08
    相关资源
    最近更新 更多