这是我的脚本:
#!/bin/sh
if [ $# -lt 1 ]; then
echo "Usage: $0 SERVER"
exit 255
fi
ssh $1 'su;apachectl restart'
我只希望它登录到服务器并重新启动 apache,但它需要超级用户权限才能做到这一点。但是,在它发出su
命令后,它不会停止并等待我输入密码。我可以让它这样做吗?
看看这是否适合你!此解决方案在执行 SSH 之前需要密码...
#!/bin/sh
if [ $# -lt 1 ]; then
echo "Usage: $0 SERVER"
exit 255
fi
read -s -p "Password: " PASSWORD
ssh $1 'echo $PASSWORD>su;apachectl restart'
该-s
选项可防止在从用户那里读取密码时回显密码。
看看期待。执行此类操作的最佳方式是通过期望脚本。这是我刚刚输入的一个示例,可以让您抢先一步,但它现在所做的只是向您展示如何在期望中处理密码。
#!/usr/bin/expect -f
set timeout 60
set pswd [lindex $argv 0]
send "su\r"
match_max 2000
expect {
-re "assword:$" {
sleep 1
set send_human {.2 .15 .25 .2 .25}
send -h -- "$pswd\r"
exp_continue
} "login failed." {
send "exit\r"
log_user 1
send_user "\r\nLogin failed.\r\n"
exit 4
} timeout {
send "exit\r"
log_user 1
send_user "\r\nCommand timed out\r\n"
exit 1
} -re "(#|%)\\s*$" {
# If we get here, then su succeeded
sleep 1
send "apachectl restart\r"
expect {
-re "(#|%)\\s*$" {
send "exit\r"
log_user 1
send_user "\r\nApache restart Successful\r\n"
exit 0
} timeout {
send "exit\r"
log_user 1
send_user "\r\nCommand timed out\r\n"
exit 1
}
}
}
}
Modifying your command to:
ssh -t $1 'sudo apachectl restart'
will open a TTY and allow sudo to interact with the remote system to ask for the user account's password without storing it locally in memory.
You could probably also modify your sudo config on the remote system to allow for execution without a password. You can do this by adding the following to /etc/sudoers
(execute visudo and insert this line, substituting <username>
appropriately.)
<username> ALL=NOPASSWD: ALL
Also, I'm a security guy and I really hope you understand the implication of allowing an SSH connection (presuming without a passphrase on the key) and remote command execution as root. If not, you should really, really, really rethink your setup here.
[Edit] Better still, edit your sudoers file to allow only apachectl to run without a password. Insert the following and modify %staff
to match your user's group, or change that to your username without the percent sign.
%staff ALL=(ALL) NOPASSWD: /usr/sbin/apachectl
Then your command should simply be changed to:
ssh $1 'sudo apachectl restart'