bash 在远程 Linux 主机上执行本地脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18001544/
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
Execute local script on remote Linux host
提问by John Milller
I have a local script that will not run without root privs on the remote host. I have edited and allowed the sudoers file to run the script from the home dir (/home/username/script). The script creates a txt file with the results but I redirect the output to terminal and pipe the output to a text file on the local machine.
我有一个本地脚本,如果没有远程主机上的 root 权限,它就不会运行。我已经编辑并允许 sudoers 文件从主目录(/home/username/script)运行脚本。该脚本使用结果创建了一个 txt 文件,但我将输出重定向到终端并将输出通过管道传输到本地计算机上的文本文件。
I cannot "ssh user@hostname sudo -Sv < script.sh > results.txt" because this will not run the script from the remote host, specifically the home dir.
我不能“ssh user@hostname sudo -Sv <script.sh> results.txt”,因为这不会从远程主机运行脚本,特别是主目录。
Does anyone know of a way (one line) to copy the script to the remote host & execute it as root while retrieving the output?
有谁知道一种方法(一行)将脚本复制到远程主机并在检索输出时以 root 身份执行它?
Thank you for any assistance
感谢您的任何帮助
采纳答案by Barmar
Copy the script with scp
, then run it.
用 复制脚本scp
,然后运行它。
scp script.sh user@hostname:
ssh user@hostname sudo ./script.sh > results.txt
To do it in one line:
要在一行中完成:
ssh user@hostname 'cat > script.sh; chmod 755 script.sh; sudo ./script.sh' < script.sh > results.txt
However, this won't work if you need to enter a password into sudo
. All of ssh
's stdin will be put in the script. There might be a way to do this using Expect
, but I don't have much expertise there.
但是,如果您需要在sudo
. 所有ssh
的标准输入都将放入脚本中。可能有一种方法可以使用 来做到这一点Expect
,但我在那里没有太多的专业知识。
回答by Gregory Patmore
if you have sudo, AND allowed to sudo to root, then this works with a bit less syntax:
如果你有 sudo,并且允许 sudo 到 root,那么这可以使用更少的语法:
ssh -T user@hostname 'sudo su -' < script.sh
ssh -T user@hostname 'sudo su -' < script.sh