bash 期望脚本 su 到 root 并执行 sed
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6023982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Expect script to su to root and perform sed
提问by jaxxstorm
I've never used expect before but need a script to do the following for a large list of hosts
我以前从未使用过expect,但需要一个脚本来为大量主机执行以下操作
- ssh into a machine
- su to root and enter the root password
- sed a file in /etc/passwd to replace some text with some other text, for this example lets just say the original text is TEXT and the text to replace it with is NEWTEXT
- ssh 进入机器
- su 到 root 并输入 root 密码
- 在 /etc/passwd 中创建一个文件,用其他一些文本替换一些文本,对于这个例子,我们只说原始文本是 TEXT,替换它的文本是 NEWTEXT
Can anyone help?
任何人都可以帮忙吗?
回答by wallyk
Understandably, executing a script to process commands as root is a huge security issue, and is generally not allowed.
可以理解,以 root 身份执行脚本来处理命令是一个巨大的安全问题,通常是不允许的。
However, Expecthas the ability to run a pseudo terminal, so it can act just like a human typing away at a keyboard.
然而,Expect有能力运行一个伪终端,所以它可以像人类在键盘上打字一样工作。
This is more or less what you asked, but is untested.
这或多或少是你问的,但未经测试。
#!/bin/sh
# if run from shell, restart with wish \
exec wish "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`"
" "$@"
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"}
If it were me, I'd change the sed command to something far less destructive, like grep TEXT /etc/passwduntil confident it works well. For a remote command which display output you want to see, use
如果是我,我会将 sed 命令更改为破坏性小得多的命令,grep TEXT /etc/passwd直到确信它运行良好。对于显示您想要查看的输出的远程命令,请使用

