【问题标题】:Bash Script works locally, but not over ssh. Ideas why?Bash 脚本在本地工作,但不能通过 ssh。想法为什么?
【发布时间】:2014-11-21 00:28:48
【问题描述】:

问题:我正在尝试创建一组脚本,提示用户输入 IP/主机名和密码(我都可以访问),然后通过 SSH 连接到 VM。第二个脚本运行一组命令来为具有各种更新和服务的环境建立基线。

在本地运行时,此脚本可以正常工作。它显示主机名并要求验证以在该环境中运行更新。

-----------------baseline.sh

#!/bin/bash
#filename: baseline.sh

echo "Are you sure you want to run your script on $(hostname -f)?"
OPTIONS="yes no"
select opt in $OPTIONS; do
if [ "$opt" = "yes" ]; then
    echo Running Script...
    #do script things
    exit
elif [ "$opt" = "no" ]; then
    echo Canceling Run...
    exit
else
    echo Please Input Either the # 1 or 2.
fi
done

这是输出:

is-mbp-jsmith:Setting Up Dev Env's jsmith $ sh baseline.sh 
Are you sure you want to run your script on is-mbp-jsmith.somecompany.com?
1) yes
2) no
#? 1
Running Script...

此脚本在我的本地机器上按预期工作

-------------------------------------------修改DevEnv.sh

这是我用来将上面的脚本通过管道传输到 VM 中的脚本。

#!/bin/bash
#filename: modifyDevEnv.sh

echo Enter a hostname/IP for the Dev Environment to connect to.
read HOST

ssh $HOST -l root 'bash -s' < baseline.sh

这是我运行此脚本时得到的输出:

is-mbp-jsmith:Setting Up Dev Env's jsmith $ sh modifyDevEnv.sh 
Enter a hostname/IP for the Dev Environment to connect to.
10.58.88.53
root@10.58.88.53's password: 
Are you sure you want to run your script on vm-jsmith.somecompany.com?

1) yes
2) no
#? 1) yes
2) no
#? is-mbp-jsmith:Setting Up Dev Env's jsmith $

当通过 ssh 运行时,脚本看起来像是运行了两次选项命令然后立即结束。它永远不会允许用户输入是/否的选项

我不知道它是否与要求脚本不喜欢的用户通过 ssh 输入有关,但这个问题让我很困惑。我对 Bash 相当陌生(我正在尝试的第一个实际脚本),但我没有发现语法有任何问题。有什么我想念的吗?

【问题讨论】:

    标签: linux bash shell ssh


    【解决方案1】:

    这是重现问题的更简单方法:

    $ cat script
    read -p "Enter name: " name
    echo "Hello $name"
    
    $ bash script
    Enter name: World
    Hello World
    
    $ ssh localhost 'bash -s' < script
    Enter name:
    Hello
    Connection to localhost closed.
    

    这是因为&lt; 的意思是“从这个文件而不是从终端读取”。

    远程运行本地脚本而不复制它的最简单方法是将其嵌入到 ssh 命令中:

    $ ssh -t localhost "$(< script)"
    Enter name: World
    Hello World
    Connection to localhost closed.
    

    请注意,这将在登录 shell 中运行脚本,而不是在 shebang 指定的任何地方。

    【讨论】:

      【解决方案2】:

      您有两个不同的进程从同一个输入流中读取:bash -s,以及bash -s 正在执行的脚本。将脚本复制到远程机器,然后使用绑定到终端的标准输入执行它会简单得多。

      #!/bin/bash
      #filename: modifyDevEnv.sh
      
      echo Enter a hostname/IP for the Dev Environment to connect to.
      read HOST
      
      scp baseline.sh root@$HOST:
      ssh $HOST -l root basline.sh
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-10-27
        • 1970-01-01
        • 2016-03-10
        • 2021-10-27
        • 2011-01-23
        • 2021-04-16
        • 1970-01-01
        相关资源
        最近更新 更多