期望脚本可以su到root并执行sed [英] Expect script to su to root and perform sed

查看:38
本文介绍了期望脚本可以su到root并执行sed的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以前从未使用过Expect,但是需要脚本来对大量主机进行以下操作

I've never used expect before but need a script to do the following for a large list of hosts

  • ssh进入机器
  • su到root并输入root密码
  • 在/etc/passwd中添加一个文件,以将某些文本替换为其他文本,在本示例中,我们只说原始文本为TEXT,替换文本为NEWTEXT

任何人都可以帮忙吗?

推荐答案

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

Understandably, executing a script to process commands as root is a huge security issue, and is generally not allowed.

但是,期望具有运行伪终端的能力,因此它可以像一个人在键盘上打字.

However, Expect has the ability to run a pseudo terminal, so it can act just like a human typing away at a keyboard.

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

This is more or less what you asked, but is untested.

#!/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 ,直到确信它可以正常工作为止.对于显示您想要查看的输出的远程命令,请使用

If it were me, I'd change the sed command to something far less destructive, like grep TEXT /etc/passwd until confident it works well. For a remote command which display output you want to see, use

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`"

这篇关于期望脚本可以su到root并执行sed的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆