bash 如何在远程服务器中以 root 身份执行本地脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18607939/
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
How to execute local script as root in remote servers?
提问by David
I need to execute a shell script with root privileges in remote servers. Those servers can't be connected directly via SSH by root user. Thus, I have to connect ssh as normal user first and then change it to root before execute the script. The user and root passwords are parameters stored previously so keyboard interaction is not an option. In that way I'd need a non-(human)-interactive script like:
我需要在远程服务器中以 root 权限执行 shell 脚本。root 用户无法通过 SSH 直接连接这些服务器。因此,我必须首先以普通用户身份连接 ssh,然后在执行脚本之前将其更改为 root。用户和 root 密码是先前存储的参数,因此无法进行键盘交互。这样我就需要一个非(人类)交互式脚本,如:
#!/bin/sh
username=admin
password=admin123
hosts={host1..host50}
for hostname in $hosts ;
do
ssh $username@$hostname sudo 'bash -s' < ./test.sh > results.txt
done
How can I do that? In my current code I need to type password for admin user connection and then I have an error like: sudo: no tty present and no askpass program specified
. Maybe a command like expect
is needed but I don't have much expertise there.
我怎样才能做到这一点?在我当前的代码,我需要键入管理员用户的连接密码,然后我有这样的错误:sudo: no tty present and no askpass program specified
。也许expect
需要像这样的命令,但我在那里没有太多的专业知识。
Thanks for your help.
谢谢你的帮助。
PS: I can't use SSH Keys and administration changes are not allowed in these servers.
PS:我不能使用 SSH 密钥,并且这些服务器中不允许进行管理更改。
回答by csikos.balint
So as I understand you can su -
into root but you don't want to edit neither sudoers nor ssh keys.
In this case expect
is your friend.
因此,据我所知,您可以su -
进入 root,但您既不想编辑 sudoers 也不想编辑 ssh 密钥。
在这种情况下expect
是你的朋友。
Hereyou can find a quite similar example, but I copy relevant code section here.
在这里你可以找到一个非常相似的例子,但我在这里复制了相关的代码部分。
#!/usr/bin/expect
set timeout 20
set host [lindex $argv 0]
set password [lindex $argv 1]
spawn ssh -tq $host su - root
expect "ssword" { send "pa55w0rd\r" } # only if you login with password auth
expect "ssword" { send "$password\r" }
expect "#" { send "id -a \r" } # run script as root
expect "#" { send \"exit\r" }
Of course you can embed this in a shell script as below.
当然,您可以将其嵌入到 shell 脚本中,如下所示。
#!/bin/bash
expect -c "
...
expect eof"
I hope I could help!
我希望我能帮上忙!
回答by Matt
Use SSH Keys to avoid having to enter a password
使用 SSH 密钥避免输入密码
view this link: https://wiki.archlinux.org/index.php/SSH_Keys
回答by David Lakatos
If you can modify the sudoers file on the remote host you can tell the sudoer service not to ask password for a specific user to do sudo commands.
如果您可以修改远程主机上的 sudoers 文件,您可以告诉 sudoer 服务不要为特定用户询问密码来执行 sudo 命令。
sudo visudo
sudo visudo
add the directive NOPASSWD
to the user
NOPASSWD
向用户添加指令