期望脚本su到root并执行sed

时间:2011-05-16 22:05:44

标签: linux bash shell expect

我之前从未使用过期望,但需要一个脚本来执行以下大量主机列表

  • ssh into a machine
  • su to root并输入root密码
  • 在/ etc / passwd中创建一个文件,用一些其他文本替换一些文本,对于这个例子,我们只说原文为TEXT,替换它的文本是NEWTEXT

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

可以理解,执行脚本以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`"