【问题标题】:Expect script to su to root and perform sed期望脚本 su 到 root 并执行 sed
【发布时间】:2011-05-16 22:05:43
【问题描述】:

我以前从未使用过 expect,但需要一个脚本来为大量主机执行以下操作

  • ssh 进入机器
  • su 到 root 并输入 root 密码
  • 在 /etc/passwd 中创建一个文件以将某些文本替换为其他文本,对于此示例,假设原始文本为 TEXT,而要替换的文本为 NEWTEXT

谁能帮忙?

【问题讨论】:

    标签: linux bash shell expect


    【解决方案1】:

    可以理解,以 root 身份执行脚本来处理命令是一个巨大的安全问题,通常是不允许的。

    但是,Expect 具有运行伪终端的能力,因此它的行为就像人类在键盘上打字一样。

    这或多或少是您所要求的,但未经测试。

    #!/bin/sh
    # if run from shell, restart with wish \
    exec wish "$0" "$@"
    
    package require Expect
    
    proc fix_a_host {host usrname password root_password} {
            # open session to host, wait for a username prompt
            spawn ssh $host
            expect "username:"
    
            # send username, wait for a password prompt
            send "$usrname\r"
            expect "password:"
    
            # send password, wait for shell prompt
            send "$password\r"
            expect "%"
    
            # become root, wait for prompt
            send "su\r"
            expect "#"
    
            # change TEXT to NEWTEXT in password file
            send "sed 's/TEXT/NEWTEXT'" /etc/passwd
            expect "#"
    
            # exit root, exit host connection
            send "exit\r"
            expect "%"
    
            send "exit\r"
            expect eof
    }       
    
    fix_a_host {"host1" "someuser" "user_password"  "root_password"}
    fix_a_host {"host2" "someuser" "user_password"  "root_password"}
    

    如果是我,我会将 sed 命令更改为破坏性较小的命令,例如 grep TEXT /etc/passwd,直到确信它运行良好。对于显示您想要查看的输出的远程命令,请使用

    set results $expect_out(buffer)
    send "some_command\r"
    expect "#"    # use the command prompt to indicate output is complete
    puts "command output is got `$buffer`"
    

    【讨论】:

      猜你喜欢
      • 2012-03-26
      • 2010-10-17
      • 1970-01-01
      • 2017-01-28
      • 1970-01-01
      • 2018-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多