【问题标题】:How to execute commands on a remote host using a bash script如何使用 bash 脚本在远程主机上执行命令
【发布时间】:2018-11-29 11:51:11
【问题描述】:

假设我有一堆命令要在我的本地机器上执行,还有一堆其他命令要在远程主机上执行。例如:

execute_locally_then_remotely() {
    # Things I want to execute locally
    foo --bar
    foo --baz
    scp filename.gz $1:/tmp

    ssh $1
    # Execute these commands on remote host
    gunzip -xvf /tmp/filename.gz
    rm -f /tmp/filename.gz

    sudo -su otheruser
    # Bunch of other commands I'd like to execute as a different user on remote host
    foobar filename

    # Exit back to local shell and execute following commands here:
    ls
}

关于如何使用 shell 脚本实现所有这些的任何想法?

【问题讨论】:

    标签: bash shell


    【解决方案1】:

    如果您有无密码访问权限,这很容易。

    ssh user@hostname " : remote script; echo hi; date; : etc; "
    

    在遥控器上使用无密码sudo,这也很简单,而且非常透明。

    如需更详细的处理,请参阅this post 还讨论了如何提供密码。其中之一应该可以帮助您。 :)

    【讨论】:

      【解决方案2】:

      如果您可以在您的机器上安装 python 包,那么Fabric 会为您解决问题。 示例远程命令如下所示:

      fab -H <host1> -u <username> -p <password> -- gunzip -xvf /tmp/filename.gz
      

      另一种选择是使用expect,但它不如Fabric那么光滑,所以我不推荐它。

      【讨论】:

        猜你喜欢
        • 2012-01-12
        • 2016-11-01
        • 2015-11-20
        • 1970-01-01
        • 2017-11-24
        • 2010-10-10
        • 2011-04-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多