如何在一个脚本/批处理文件中更改多个unix密码?

n00*_*00b 5 unix ssh scripting putty batch-file

我从Windows连接到8个不同的unix服务器,在putty中使用连接类型"SSH".我为每个服务器使用相同的用户名/密码.

目前,当我需要更改密码(每60天)时,我需要打开putty,选择我要连接的会话,输入我当前的密码(在打开的putty窗口中),输入"passwd",输入我当前的密码,然后输入我的新密码.

然后我退出并重复该过程7次.

如何将其转换为自动化流程,我只需要使用旧密码和新密码提供脚本/批处理流程?

n00*_*00b 2

以下是我如何自动化该过程:

  1. 下载并安装ActiveTCL Community Edition(下载 32 位版本,即使您使用的是 64 位 Windows,因为 64 位版本没有运行自动化脚本所需的“Expect”)

  2. 打开安装时创建的 tclsh85 可执行文件

  3. 运行此命令“teacup install Expect”(注意,此命令区分大小写。如果收到错误和/或使用 VPN 或使用代理,则可能需要设置特殊的 http 设置)

  4. 下载 Putty 的“plink.exe”并将其放置在 ActiveTCL 的 bin 目录中(默认安装目录为“C:\Tcl\bin”)或更改“Path”环境变量以包含此可执行文件的路径(无论您下载到何处) plink.exe)。这是您的脚本将使用的 Putty 命令行版本。

  5. 在驱动器上的任意位置创建一个名为“servers.txt”的文本文件,其中包含服务器列表(每行一个)。它们都应该共享相同的密码,因为脚本将使用相同的密码(您提供的)登录所有它们,并将密码更改为您提供的密码。

  6. 在与“servers.txt”相同的目录中创建一个名为“ChangePassword.tcl”的新文本文件(或任何您想要的名称,但请确保其文件类型为“tcl”)。右键单击该文件并在记事本(或您喜欢的任何文本编辑器)中进行编辑,然后将此脚本粘贴到其中。

    package require Expect
    
    exp_log_user 0
    set exp::nt_debug 1
    
    proc changepw {host user oldpass newpass} {
           spawn plink $host
           log_user 0
           expect {
               "login as: " { }
           }
           exp_send "$user\r"
           expect "sword: "
           exp_send "$oldpass\r"
           expect "\$ "
           exp_send "passwd\r"
           expect "sword: "
         exp_send "$oldpass\r"
         expect "sword: "
         exp_send "$newpass\r"
         expect "sword: "
         exp_send "$newpass\r"
           set result $expect_out(buffer)
           exp_send "exit\r"
           return $result
    }
    
    label .userlbl -text "Username:"
    label .oldpasslbl -text "\nOld Password: "
    label .newpasslbl -text "\nNew Password: "
    
    set username "username"
    entry .username -textvariable username
    set oldpassword "oldpassword"
    entry .oldpassword -textvariable oldpassword
    set newpassword "newpassword"
    entry .newpassword -textvariable newpassword
    
    button .button1 -text "Change Password" -command {
      set fp [open "servers.txt" r]
      set file_data [read $fp]
      close $fp
      set data [split $file_data "\n"]
      foreach line $data {
          .text1 insert end "Changing password for: $line\n"
        set output [changepw $line $username $oldpassword $newpassword]
        .text1 insert end "$output\n\n"
      }
    }
    
    text .text1 -width 50 -height 30 
    pack .userlbl .username .oldpasslbl .oldpassword .newpasslbl .newpassword .button1 .text1
    
    Run Code Online (Sandbox Code Playgroud)
  7. 保存脚本,然后启动 ChangePassword.tcl 文件。

这是打开 ChangePassword.tcl 文件时的样子的图片: 更改密码 TCL 程序,servers.txt 在后台打开

其余的应该是不言自明的。请注意,当您的密码更改成功时,程序不会输出,但当密码更改失败时,它会告诉您。另请注意,这是我的第一个 tcl 脚本(也是第一次使用 Expect),因此该脚本绝非“优化”的,可能还可以改进,但它完成了工作。请随意编辑或提出建议/改进。