代码之家  ›  专栏  ›  技术社区  ›  ayushgp

如何使用bash脚本在远程主机上执行命令

  •  1
  • ayushgp  · 技术社区  · 6 年前

    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脚本实现所有这些,有什么想法吗?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Paul Hodges    6 年前

    如果你有无密码访问

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

    sudo 在遥控器上,这也很简单,而且相当透明。

    更详细的治疗,c.f。 this post

        2
  •  1
  •   Samarth    6 年前

    如果您可以在您的计算机上安装python包,那么 Fabric 会帮你的。

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

    另一种选择是使用 expect