What is the cleanest way to ssh and run multiple commands in Bash?

前端 未结 12 2090
礼貌的吻别
礼貌的吻别 2020-11-22 09:14

I already have an ssh agent set up, and I can run commands on an external server in Bash script doing stuff like:

ssh blah_server "ls; pwd;"
         


        
相关标签:
12条回答
  • 2020-11-22 09:36

    The posted answers using multiline strings and multiple bash scripts did not work for me.

    • Long multiline strings are hard to maintain.
    • Separate bash scripts do not maintain local variables.

    Here is a functional way to ssh and run multiple commands while keeping local context.

    LOCAL_VARIABLE=test
    
    run_remote() {
        echo "$LOCAL_VARIABLE"
        ls some_folder; 
        ./someaction.sh 'some params'
        ./some_other_action 'other params'
    }
    
    ssh otherhost "$(set); run_remote"
    
    0 讨论(0)
  • 2020-11-22 09:38

    Put all the commands on to a script and it can be run like

    ssh <remote-user>@<remote-host> "bash -s" <./remote-commands.sh
    
    0 讨论(0)
  • 2020-11-22 09:38

    This works well for creating scripts, as you do not have to include other files:

    #!/bin/bash
    ssh <my_user>@<my_host> "bash -s" << EOF
        # here you just type all your commmands, as you can see, i.e.
        touch /tmp/test1;
        touch /tmp/test2;
        touch /tmp/test3;
    EOF
    
    # you can use '$(which bash) -s' instead of my "bash -s" as well
    # but bash is usually being found in a standard location
    # so for easier memorizing it i leave that out
    # since i dont fat-finger my $PATH that bad so it cant even find /bin/bash ..
    
    0 讨论(0)
  • 2020-11-22 09:40

    Edit your script locally, then pipe it into ssh, e.g.

    cat commands-to-execute-remotely.sh | ssh blah_server
    

    where commands-to-execute-remotely.sh looks like your list above:

    ls some_folder
    ./someaction.sh
    pwd;
    
    0 讨论(0)
  • 2020-11-22 09:42

    I see two ways:

    First you make a control socket like this:

     ssh -oControlMaster=yes -oControlPath=~/.ssh/ssh-%r-%h-%p <yourip>
    

    and run your commands

     ssh -oControlMaster=no -oControlPath=~/.ssh/ssh-%r-%h-%p <yourip> -t <yourcommand>
    

    This way you can write an ssh command without actually reconnecting to the server.

    The second would be to dynamically generate the script, scping it and running.

    0 讨论(0)
  • 2020-11-22 09:46

    To match your sample code, you can wrap your commands inside single or double qoutes. For example

    ssh blah_server "
      ls
      pwd
    "
    
    0 讨论(0)
提交回复
热议问题