问题描述
我有以下示例脚本,用于在远程主机上运行命令。
该脚本从用户输入中接受远程主机的密码,我们可以使用该密码以该用户身份登录,并且我希望还会传递给sudo
。
问题是,我似乎无法在第二个函数中使用我需要的sudo
运行 runOnRemoteHostAsRoot 函数。
如何使它工作?
两端的平台都是Ubuntu 18或20。
#!/bin/bash
read SSHPASS
export SSHPASS
runOnRemoteHost() {
# ...
whoami
# ...
}
# ...
sshpass -e ssh -o PasswordAuthentication=yes "user@remotehost" "$(declare -f runOnRemoteHost); runOnRemoteHost" 2>&1
# ...
runOnRemoteHostAsRoot() {
# ...
whoami
# ...
}
# ...
echo "${SSHPASS}" | sshpass -e ssh -o PasswordAuthentication=yes "user@remotehost" "$(declare -f runOnRemoteHostAsRoot); sudo --stdin runOnRemoteHostAsRoot" 2>&1
# ...
预期输出:
user
root
实际输出:
user
[sudo] password for user: sudo: runOnRemoteHostAsRoot: command not found
解决方法
在这种情况下,@Will的建议非常有用,先使用sudo bash -c
,然后声明并运行该函数:
sudo bash -c "$(declare -f runOnRemoteHostAsRoot); runOnRemoteHostAsRoot"
将密码通过sshpass
进行无密码登录后,我们将使用该行,例如:
echo '${SSHPASS}' | sudo --stdin bash -c '$(declare -f runOnRemoteHostAsRoot); runOnRemoteHostAsRoot'`
因此在上面的示例中使用它:
#!/bin/bash
read SSHPASS
export SSHPASS
runOnRemoteHost() {
# ...
whoami
# ...
}
# ...
sshpass -e ssh -o PasswordAuthentication=yes "user@remotehost" "$(declare -f runOnRemoteHost); runOnRemoteHost" 2>&1
# ...
runOnRemoteHostAsRoot() {
# ...
whoami
# ...
}
# ...
sshpass -e ssh -o PasswordAuthentication=yes "user@remotehost" "echo '${SSHPASS}' | sudo --stdin bash -c '$(declare -f runOnRemoteHostAsRoot); runOnRemoteHostAsRoot'" 2>&1
输出:
user
root