Shell script to SSH into another server and execute a script there





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







3















I have 6 servers in my testing environment. I want to write a script to stop the Tomcat server in all boxes by logging into one box instead of logging into each and every box.



Please help me with shell scripting, SSH and executing a script in all other boxes.
I use SSH with a password and custom port number.










share|improve this question































    3















    I have 6 servers in my testing environment. I want to write a script to stop the Tomcat server in all boxes by logging into one box instead of logging into each and every box.



    Please help me with shell scripting, SSH and executing a script in all other boxes.
    I use SSH with a password and custom port number.










    share|improve this question



























      3












      3








      3








      I have 6 servers in my testing environment. I want to write a script to stop the Tomcat server in all boxes by logging into one box instead of logging into each and every box.



      Please help me with shell scripting, SSH and executing a script in all other boxes.
      I use SSH with a password and custom port number.










      share|improve this question
















      I have 6 servers in my testing environment. I want to write a script to stop the Tomcat server in all boxes by logging into one box instead of logging into each and every box.



      Please help me with shell scripting, SSH and executing a script in all other boxes.
      I use SSH with a password and custom port number.







      command-line server bash scripts ssh






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Feb 12 at 7:51









      Melebius

      5,09352041




      5,09352041










      asked Feb 12 at 6:58









      nithinithi

      162




      162






















          2 Answers
          2






          active

          oldest

          votes


















          5














          You should combine two related Ask Ubuntu answers, one for logging into SSH via specific port and one for running commands on remote server , into one script. Of course, you'd need to have some form of data-structure to hold server+port correspondence. That could be either bash associative arrays or with POSIX shell script - a case statement. Assuming your username on all hosts is the same, we could come up with something like this:



          #!/bin/sh
          # bar host has ssh server on port 22, while baz - on port 2222
          host_port(){
          case "$1" in
          "bar") echo 22 ;;
          "baz") echo 2222 ;;
          esac
          }

          # set positional parameters of script to hosts and iterate over them
          set -- bar baz
          for host ; do
          # command substitution will call function,
          # function's return value will be the port number
          ssh ssh://username@"$host":"$(host_port "$host")" -t "systemctl stop tomcat"
          done


          Now, a giant disclaimer: This is just an example. I don't have 6 servers to test the script, so adapt it to your needs as necessary. If you have different usernames on each host, use another case statement





          Side note on logging in: if you have private key, which is accepted by all 6 servers it will be easy to log-in just by adding -i ~/.ssh/id_rsa. Alternative to that would be to create a ~/.ssh/config file with key/password information for each host. This is described in Lekensteyn's answer. If you're not familiar with SSH keys (and I understand it's kinda confusing topic), you might wanna read ssh.com article on the topic.






          share|improve this answer

































            0














            You can use sshpass:



            sudo apt install sshpass -y 


            then you can execute command on remote server, for example



                #!/bin/bash
            # login info
            HOST='192.168.0.1'
            USER='user'
            PORT='2222'
            PASSWORD='password'
            # command
            sshpass -p $PASSWORD ssh -p $PORT $USER@$HOST touch 1.txt





            share|improve this answer


























            • I have installed sshpass and white I run this script this is showing me bash: ./bscript: Permission denied Error

              – nithi
              Feb 12 at 9:20






            • 1





              chmod u+x the script ?

              – Goufalite
              Feb 12 at 9:38













            • but where should I mention my custom port number?? we have changed changed our portnumber from 22 to 2222 in all our servers

              – nithi
              Feb 12 at 10:08






            • 1





              sshpass -p 'password' ssh -p 2222 user@host touch 1.txt

              – Yaroslav Urshulyak
              Feb 12 at 15:29











            • Permission denied, please try again. even after chmod u+x the script.......should I pass the password as root

              – nithi
              Feb 15 at 11:08














            Your Answer








            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "89"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f1117583%2fshell-script-to-ssh-into-another-server-and-execute-a-script-there%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            5














            You should combine two related Ask Ubuntu answers, one for logging into SSH via specific port and one for running commands on remote server , into one script. Of course, you'd need to have some form of data-structure to hold server+port correspondence. That could be either bash associative arrays or with POSIX shell script - a case statement. Assuming your username on all hosts is the same, we could come up with something like this:



            #!/bin/sh
            # bar host has ssh server on port 22, while baz - on port 2222
            host_port(){
            case "$1" in
            "bar") echo 22 ;;
            "baz") echo 2222 ;;
            esac
            }

            # set positional parameters of script to hosts and iterate over them
            set -- bar baz
            for host ; do
            # command substitution will call function,
            # function's return value will be the port number
            ssh ssh://username@"$host":"$(host_port "$host")" -t "systemctl stop tomcat"
            done


            Now, a giant disclaimer: This is just an example. I don't have 6 servers to test the script, so adapt it to your needs as necessary. If you have different usernames on each host, use another case statement





            Side note on logging in: if you have private key, which is accepted by all 6 servers it will be easy to log-in just by adding -i ~/.ssh/id_rsa. Alternative to that would be to create a ~/.ssh/config file with key/password information for each host. This is described in Lekensteyn's answer. If you're not familiar with SSH keys (and I understand it's kinda confusing topic), you might wanna read ssh.com article on the topic.






            share|improve this answer






























              5














              You should combine two related Ask Ubuntu answers, one for logging into SSH via specific port and one for running commands on remote server , into one script. Of course, you'd need to have some form of data-structure to hold server+port correspondence. That could be either bash associative arrays or with POSIX shell script - a case statement. Assuming your username on all hosts is the same, we could come up with something like this:



              #!/bin/sh
              # bar host has ssh server on port 22, while baz - on port 2222
              host_port(){
              case "$1" in
              "bar") echo 22 ;;
              "baz") echo 2222 ;;
              esac
              }

              # set positional parameters of script to hosts and iterate over them
              set -- bar baz
              for host ; do
              # command substitution will call function,
              # function's return value will be the port number
              ssh ssh://username@"$host":"$(host_port "$host")" -t "systemctl stop tomcat"
              done


              Now, a giant disclaimer: This is just an example. I don't have 6 servers to test the script, so adapt it to your needs as necessary. If you have different usernames on each host, use another case statement





              Side note on logging in: if you have private key, which is accepted by all 6 servers it will be easy to log-in just by adding -i ~/.ssh/id_rsa. Alternative to that would be to create a ~/.ssh/config file with key/password information for each host. This is described in Lekensteyn's answer. If you're not familiar with SSH keys (and I understand it's kinda confusing topic), you might wanna read ssh.com article on the topic.






              share|improve this answer




























                5












                5








                5







                You should combine two related Ask Ubuntu answers, one for logging into SSH via specific port and one for running commands on remote server , into one script. Of course, you'd need to have some form of data-structure to hold server+port correspondence. That could be either bash associative arrays or with POSIX shell script - a case statement. Assuming your username on all hosts is the same, we could come up with something like this:



                #!/bin/sh
                # bar host has ssh server on port 22, while baz - on port 2222
                host_port(){
                case "$1" in
                "bar") echo 22 ;;
                "baz") echo 2222 ;;
                esac
                }

                # set positional parameters of script to hosts and iterate over them
                set -- bar baz
                for host ; do
                # command substitution will call function,
                # function's return value will be the port number
                ssh ssh://username@"$host":"$(host_port "$host")" -t "systemctl stop tomcat"
                done


                Now, a giant disclaimer: This is just an example. I don't have 6 servers to test the script, so adapt it to your needs as necessary. If you have different usernames on each host, use another case statement





                Side note on logging in: if you have private key, which is accepted by all 6 servers it will be easy to log-in just by adding -i ~/.ssh/id_rsa. Alternative to that would be to create a ~/.ssh/config file with key/password information for each host. This is described in Lekensteyn's answer. If you're not familiar with SSH keys (and I understand it's kinda confusing topic), you might wanna read ssh.com article on the topic.






                share|improve this answer















                You should combine two related Ask Ubuntu answers, one for logging into SSH via specific port and one for running commands on remote server , into one script. Of course, you'd need to have some form of data-structure to hold server+port correspondence. That could be either bash associative arrays or with POSIX shell script - a case statement. Assuming your username on all hosts is the same, we could come up with something like this:



                #!/bin/sh
                # bar host has ssh server on port 22, while baz - on port 2222
                host_port(){
                case "$1" in
                "bar") echo 22 ;;
                "baz") echo 2222 ;;
                esac
                }

                # set positional parameters of script to hosts and iterate over them
                set -- bar baz
                for host ; do
                # command substitution will call function,
                # function's return value will be the port number
                ssh ssh://username@"$host":"$(host_port "$host")" -t "systemctl stop tomcat"
                done


                Now, a giant disclaimer: This is just an example. I don't have 6 servers to test the script, so adapt it to your needs as necessary. If you have different usernames on each host, use another case statement





                Side note on logging in: if you have private key, which is accepted by all 6 servers it will be easy to log-in just by adding -i ~/.ssh/id_rsa. Alternative to that would be to create a ~/.ssh/config file with key/password information for each host. This is described in Lekensteyn's answer. If you're not familiar with SSH keys (and I understand it's kinda confusing topic), you might wanna read ssh.com article on the topic.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Feb 12 at 7:51

























                answered Feb 12 at 7:39









                Sergiy KolodyazhnyySergiy Kolodyazhnyy

                75.5k9155329




                75.5k9155329

























                    0














                    You can use sshpass:



                    sudo apt install sshpass -y 


                    then you can execute command on remote server, for example



                        #!/bin/bash
                    # login info
                    HOST='192.168.0.1'
                    USER='user'
                    PORT='2222'
                    PASSWORD='password'
                    # command
                    sshpass -p $PASSWORD ssh -p $PORT $USER@$HOST touch 1.txt





                    share|improve this answer


























                    • I have installed sshpass and white I run this script this is showing me bash: ./bscript: Permission denied Error

                      – nithi
                      Feb 12 at 9:20






                    • 1





                      chmod u+x the script ?

                      – Goufalite
                      Feb 12 at 9:38













                    • but where should I mention my custom port number?? we have changed changed our portnumber from 22 to 2222 in all our servers

                      – nithi
                      Feb 12 at 10:08






                    • 1





                      sshpass -p 'password' ssh -p 2222 user@host touch 1.txt

                      – Yaroslav Urshulyak
                      Feb 12 at 15:29











                    • Permission denied, please try again. even after chmod u+x the script.......should I pass the password as root

                      – nithi
                      Feb 15 at 11:08


















                    0














                    You can use sshpass:



                    sudo apt install sshpass -y 


                    then you can execute command on remote server, for example



                        #!/bin/bash
                    # login info
                    HOST='192.168.0.1'
                    USER='user'
                    PORT='2222'
                    PASSWORD='password'
                    # command
                    sshpass -p $PASSWORD ssh -p $PORT $USER@$HOST touch 1.txt





                    share|improve this answer


























                    • I have installed sshpass and white I run this script this is showing me bash: ./bscript: Permission denied Error

                      – nithi
                      Feb 12 at 9:20






                    • 1





                      chmod u+x the script ?

                      – Goufalite
                      Feb 12 at 9:38













                    • but where should I mention my custom port number?? we have changed changed our portnumber from 22 to 2222 in all our servers

                      – nithi
                      Feb 12 at 10:08






                    • 1





                      sshpass -p 'password' ssh -p 2222 user@host touch 1.txt

                      – Yaroslav Urshulyak
                      Feb 12 at 15:29











                    • Permission denied, please try again. even after chmod u+x the script.......should I pass the password as root

                      – nithi
                      Feb 15 at 11:08
















                    0












                    0








                    0







                    You can use sshpass:



                    sudo apt install sshpass -y 


                    then you can execute command on remote server, for example



                        #!/bin/bash
                    # login info
                    HOST='192.168.0.1'
                    USER='user'
                    PORT='2222'
                    PASSWORD='password'
                    # command
                    sshpass -p $PASSWORD ssh -p $PORT $USER@$HOST touch 1.txt





                    share|improve this answer















                    You can use sshpass:



                    sudo apt install sshpass -y 


                    then you can execute command on remote server, for example



                        #!/bin/bash
                    # login info
                    HOST='192.168.0.1'
                    USER='user'
                    PORT='2222'
                    PASSWORD='password'
                    # command
                    sshpass -p $PASSWORD ssh -p $PORT $USER@$HOST touch 1.txt






                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Feb 14 at 9:08

























                    answered Feb 12 at 7:50









                    Yaroslav UrshulyakYaroslav Urshulyak

                    52446




                    52446













                    • I have installed sshpass and white I run this script this is showing me bash: ./bscript: Permission denied Error

                      – nithi
                      Feb 12 at 9:20






                    • 1





                      chmod u+x the script ?

                      – Goufalite
                      Feb 12 at 9:38













                    • but where should I mention my custom port number?? we have changed changed our portnumber from 22 to 2222 in all our servers

                      – nithi
                      Feb 12 at 10:08






                    • 1





                      sshpass -p 'password' ssh -p 2222 user@host touch 1.txt

                      – Yaroslav Urshulyak
                      Feb 12 at 15:29











                    • Permission denied, please try again. even after chmod u+x the script.......should I pass the password as root

                      – nithi
                      Feb 15 at 11:08





















                    • I have installed sshpass and white I run this script this is showing me bash: ./bscript: Permission denied Error

                      – nithi
                      Feb 12 at 9:20






                    • 1





                      chmod u+x the script ?

                      – Goufalite
                      Feb 12 at 9:38













                    • but where should I mention my custom port number?? we have changed changed our portnumber from 22 to 2222 in all our servers

                      – nithi
                      Feb 12 at 10:08






                    • 1





                      sshpass -p 'password' ssh -p 2222 user@host touch 1.txt

                      – Yaroslav Urshulyak
                      Feb 12 at 15:29











                    • Permission denied, please try again. even after chmod u+x the script.......should I pass the password as root

                      – nithi
                      Feb 15 at 11:08



















                    I have installed sshpass and white I run this script this is showing me bash: ./bscript: Permission denied Error

                    – nithi
                    Feb 12 at 9:20





                    I have installed sshpass and white I run this script this is showing me bash: ./bscript: Permission denied Error

                    – nithi
                    Feb 12 at 9:20




                    1




                    1





                    chmod u+x the script ?

                    – Goufalite
                    Feb 12 at 9:38







                    chmod u+x the script ?

                    – Goufalite
                    Feb 12 at 9:38















                    but where should I mention my custom port number?? we have changed changed our portnumber from 22 to 2222 in all our servers

                    – nithi
                    Feb 12 at 10:08





                    but where should I mention my custom port number?? we have changed changed our portnumber from 22 to 2222 in all our servers

                    – nithi
                    Feb 12 at 10:08




                    1




                    1





                    sshpass -p 'password' ssh -p 2222 user@host touch 1.txt

                    – Yaroslav Urshulyak
                    Feb 12 at 15:29





                    sshpass -p 'password' ssh -p 2222 user@host touch 1.txt

                    – Yaroslav Urshulyak
                    Feb 12 at 15:29













                    Permission denied, please try again. even after chmod u+x the script.......should I pass the password as root

                    – nithi
                    Feb 15 at 11:08







                    Permission denied, please try again. even after chmod u+x the script.......should I pass the password as root

                    – nithi
                    Feb 15 at 11:08




















                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Ask Ubuntu!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2faskubuntu.com%2fquestions%2f1117583%2fshell-script-to-ssh-into-another-server-and-execute-a-script-there%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Questions related to Moebius Transform of Characteristic Function of the Primes

                    List of scandals in India

                    Can not write log (Is /dev/pts mounted?) - openpty in Ubuntu-on-Windows?