bash bash脚本在ssh之后执行命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26434604/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:35:30  来源:igfitidea点击:

bash script execute commands after ssh

bashsshcentos

提问by Lukas Lukac

I am trying to execute a few commands via my first script but it's not working.

我正在尝试通过我的第一个脚本执行一些命令,但它不起作用。

#!/bin/bash

#connect to server
echo "Connecting to the server..."

ssh -t root@IP '

    #switch user to deploy
    su - deploy

    #switch path
    echo "Switching the path"
    cd /var/www/deploys/bin/app/config

    #run deploy script
    echo "Running deploy script"

    /usr/local/bin/cap -S env=prod deploy

    #restart apache
    sudo /bin/systemctl restart  httpd.service

    bash -l
'

What is happening? I am successfully connected to the server, the user is changed and then I don't see nothing happening. When I press ctrl + c just like that in terminal, some output from the command that should be executed appears but there are some errors.

怎么了?我已成功连接到服务器,用户已更改,然后我什么也没看到。当我像在终端中那样按 ctrl + c 时,会出现一些应该执行的命令的输出,但有一些错误。

Why I don't see everything what is happening in terminal after launching the script? Am I doing it the wrong way?

为什么在启动脚本后我看不到终端中发生的一切?我做错了吗?

BTW: when I try connect manually and run the commands myself, everything is working nicely.

顺便说一句:当我尝试手动连接并自己运行命令时,一切都运行良好。

Using CentOS 7.

使用 CentOS 7。

回答by nu11p01n73R

Clean way to login through ssh and excecute a set of commands is

通过 ssh 登录并执行一组命令的干净方法是

ssh user@ip << EOF
   #some commands
EOF

here EOFacts as the delimitter for the command list

这里EOF作为命令列表的分隔符

the script can be modified as

脚本可以修改为

ssh -t root@IP << EOF

    #switch user to deploy
    su - deploy

    #switch path
    echo "Switching the path"
    cd /var/www/deploys/bin/app/config

    #run deploy script
    echo "Running deploy script"

    /usr/local/bin/cap -S env=prod deploy

    #restart apache
    sudo /bin/systemctl restart  httpd.service

    bash -l
EOF

will excecutes the command and closes the connection there after

将执行命令并在那里关闭连接