ssh 并通过heredoc以另一个用户身份执行多个命令

Ant*_*Kim 2 linux ssh bash

我有一个脚本需要通过 ssh 执行作为另一种用途,有没有办法像这样传递整个脚本:

ssh -t user@server.com sudo -u user2 sh -c << EOF
 cd /home
 ls
 dir=$(pwd)
 echo "$dir"
 echo "hello"
 ....
EOF
Run Code Online (Sandbox Code Playgroud)

返回:sh: -c: 选项需要参数

单独使用 sshsudo不是一种选择,并且不可能将 .sh 文件直接放在计算机上。

cod*_*ter 5

sh -c需要命令字符串作为参数。由于您正在从标准输入(通过heredoc)读取命令,因此您需要使用sh -s选项:

ssh -t user@server.com sudo -u user2 sh -s << 'EOF'
 cd /home
 ls
 dir=$(pwd)
 echo "$dir"
 echo "hello"
 ...
EOF
Run Code Online (Sandbox Code Playgroud)

man sh

-C

string 如果存在 -c 选项,则从字符串中读取命令。如果字符串后面有参数,它们将被分配给位置参数,从 $0 开始。

-s

如果存在 -s 选项,或者选项处理后没有剩余参数,则从标准输入读取命令。该选项允许在调用交互式 shell 时设置位置参数。

需要引用heredoc标记以防止父shell解释内容。