Retaining SSH session in bash script The 2019 Stack Overflow Developer Survey Results Are InHow to determine if a bash variable is empty?Need help with executing and deleting remote bash script via a local bash scriptSSH: Access local file (redirect local file contents) via remote SSH consoleSSH not seeming to run in bash script called via web serverSSH - set env vairables by every connection - godaddy shared hostTerminate remote process when backgrounded ssh session is terminatedRemote bash script execution via ssh causes local script to stopPause BASH script to allow user to enter SSH passwordHow to exit a SSH connection in a bash scriptUse bash script to send commands to SSH client?

Do these rules for Critical Successes and Critical Failures seem Fair?

How to type this arrow in math mode?

What did it mean to "align" a radio?

Falsification in Math vs Science

Shouldn't "much" here be used instead of "more"?

Can one be advised by a professor who is very far away?

What is the meaning of Triage in Cybersec world?

Can you compress metal and what would be the consequences?

What is the motivation for a law requiring 2 parties to consent for recording a conversation

Write faster on AT24C32

Output the Arecibo Message

Which Sci-Fi work first showed weapon of galactic-scale mass destruction?

Is an up-to-date browser secure on an out-of-date OS?

Can someone be penalized for an "unlawful" act if no penalty is specified?

"as much details as you can remember"

How technical should a Scrum Master be to effectively remove impediments?

FPGA - DIY Programming

Does a dangling wire really electrocute me if I'm standing in water?

Where to refill my bottle in India?

What to do when moving next to a bird sanctuary with a loosely-domesticated cat?

Why do we hear so much about the Trump administration deciding to impose and then remove tariffs?

Can a rogue use sneak attack with weapons that have the thrown property even if they are not thrown?

Why was M87 targetted for the Event Horizon Telescope instead of Sagittarius A*?

How can I autofill dates in Excel excluding Sunday?



Retaining SSH session in bash script



The 2019 Stack Overflow Developer Survey Results Are InHow to determine if a bash variable is empty?Need help with executing and deleting remote bash script via a local bash scriptSSH: Access local file (redirect local file contents) via remote SSH consoleSSH not seeming to run in bash script called via web serverSSH - set env vairables by every connection - godaddy shared hostTerminate remote process when backgrounded ssh session is terminatedRemote bash script execution via ssh causes local script to stopPause BASH script to allow user to enter SSH passwordHow to exit a SSH connection in a bash scriptUse bash script to send commands to SSH client?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I have a bash script which loops over a server list, runs a couple of remote commands via SSH, and writes the output of those commands to a local file.
For every command I run on the remote server I open a new SSH session.
Is there a way that only one SSH session remains open to a server, and that I can run multiple commands which the output I can redirect to a local file?










share|improve this question




























    1















    I have a bash script which loops over a server list, runs a couple of remote commands via SSH, and writes the output of those commands to a local file.
    For every command I run on the remote server I open a new SSH session.
    Is there a way that only one SSH session remains open to a server, and that I can run multiple commands which the output I can redirect to a local file?










    share|improve this question
























      1












      1








      1


      1






      I have a bash script which loops over a server list, runs a couple of remote commands via SSH, and writes the output of those commands to a local file.
      For every command I run on the remote server I open a new SSH session.
      Is there a way that only one SSH session remains open to a server, and that I can run multiple commands which the output I can redirect to a local file?










      share|improve this question














      I have a bash script which loops over a server list, runs a couple of remote commands via SSH, and writes the output of those commands to a local file.
      For every command I run on the remote server I open a new SSH session.
      Is there a way that only one SSH session remains open to a server, and that I can run multiple commands which the output I can redirect to a local file?







      linux ssh bash scripting






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Oct 27 '09 at 10:51









      Tom_13Tom_13

      3615




      3615




















          5 Answers
          5






          active

          oldest

          votes


















          2














          You want to look into the ControlMaster setting for SSH. That allows you to create a single SSH connection and then have all the other SSH connections to the same server multiplex over that one connection. Very handy.






          share|improve this answer























          • Would this not add a lot of complexity in your script to start the master and kill it again after.

            – David Pashley
            Oct 27 '09 at 11:10











          • TANSTAAFL. Virtual memory adds a lot of complexity to your OS kernel, but we do it anyway because the benefits outweigh the disadvantages.

            – womble
            Oct 27 '09 at 12:15











          • No there's not a significant increase in complexity because ControlMaster can be made automatic, and then ssh handles creating and removing the master (unix-domain) socket.

            – Jim Zajkowski
            Oct 29 '09 at 21:51


















          1














          Note: When you say local file, I am not sure if you mean local the machine you just ssh'd into, or if you mean local to the machine the starts the ssh session.



          Push vs Pull:

          It sounds like this might not be the right tool, maybe you just want to use cron on each local machine? If information is needed from the master, you can have the cron job fetch a file from the server. This would be more of a pull method, the ssh is what I would call push method. I can't say which is better for your situation, but this may be something to think about.



          Run Multiple Commands:

          I don't understand if you mean keep the session open for each itteration of the multiple commands, or just have it sort of always open. If it is the former, you can just use semi-colons between commands, or && to make so the next command will only be executed if the first works. For example:



          #bar echoed only if foo exists and can be read
          ssh myServer 'cat foo && echo bar'
          ssh myServer 'cat foo; echo bar'


          You can also do stuff like the following if you want to specify use of things in a shell:



          ssh myServer "bash -c 'cat foo && echo bar'"


          Lastly, you could always just put the script on each server, and just run that.






          share|improve this answer
































            1














            The "expect" tool could also do what you want, but involves writing tcl.






            share|improve this answer






























              1














              To expand on the ControlMaster use, here's a slightly more concrete example:



              CONTROL=/tmp/ssh-control-`date +%s`-$RANDOM
              ssh -o BatchMode=yes -NfM -S $CONTROL &
              MASTERPID=$?

              ssh -o BatchMode=yes -S $CONTROL user@host command1 > outfile1
              ssh -o BatchMode=yes -S $CONTROL user@host command2 > outfile2

              kill $MASTERPID


              This is largely untested, but it should give you the right general idea.






              share|improve this answer
































                0














                You can run several commmands in sequence by starting a shell on the remote system and passing it the commands:



                ssh server "echo this is; all in one session"


                will automatically pass the quoted string through a remote shell. Beware of shell quoting rules, though!






                share|improve this answer























                  Your Answer








                  StackExchange.ready(function()
                  var channelOptions =
                  tags: "".split(" "),
                  id: "2"
                  ;
                  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%2fserverfault.com%2fquestions%2f78630%2fretaining-ssh-session-in-bash-script%23new-answer', 'question_page');

                  );

                  Post as a guest















                  Required, but never shown

























                  5 Answers
                  5






                  active

                  oldest

                  votes








                  5 Answers
                  5






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  2














                  You want to look into the ControlMaster setting for SSH. That allows you to create a single SSH connection and then have all the other SSH connections to the same server multiplex over that one connection. Very handy.






                  share|improve this answer























                  • Would this not add a lot of complexity in your script to start the master and kill it again after.

                    – David Pashley
                    Oct 27 '09 at 11:10











                  • TANSTAAFL. Virtual memory adds a lot of complexity to your OS kernel, but we do it anyway because the benefits outweigh the disadvantages.

                    – womble
                    Oct 27 '09 at 12:15











                  • No there's not a significant increase in complexity because ControlMaster can be made automatic, and then ssh handles creating and removing the master (unix-domain) socket.

                    – Jim Zajkowski
                    Oct 29 '09 at 21:51















                  2














                  You want to look into the ControlMaster setting for SSH. That allows you to create a single SSH connection and then have all the other SSH connections to the same server multiplex over that one connection. Very handy.






                  share|improve this answer























                  • Would this not add a lot of complexity in your script to start the master and kill it again after.

                    – David Pashley
                    Oct 27 '09 at 11:10











                  • TANSTAAFL. Virtual memory adds a lot of complexity to your OS kernel, but we do it anyway because the benefits outweigh the disadvantages.

                    – womble
                    Oct 27 '09 at 12:15











                  • No there's not a significant increase in complexity because ControlMaster can be made automatic, and then ssh handles creating and removing the master (unix-domain) socket.

                    – Jim Zajkowski
                    Oct 29 '09 at 21:51













                  2












                  2








                  2







                  You want to look into the ControlMaster setting for SSH. That allows you to create a single SSH connection and then have all the other SSH connections to the same server multiplex over that one connection. Very handy.






                  share|improve this answer













                  You want to look into the ControlMaster setting for SSH. That allows you to create a single SSH connection and then have all the other SSH connections to the same server multiplex over that one connection. Very handy.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Oct 27 '09 at 10:59









                  womblewomble

                  85.7k18144204




                  85.7k18144204












                  • Would this not add a lot of complexity in your script to start the master and kill it again after.

                    – David Pashley
                    Oct 27 '09 at 11:10











                  • TANSTAAFL. Virtual memory adds a lot of complexity to your OS kernel, but we do it anyway because the benefits outweigh the disadvantages.

                    – womble
                    Oct 27 '09 at 12:15











                  • No there's not a significant increase in complexity because ControlMaster can be made automatic, and then ssh handles creating and removing the master (unix-domain) socket.

                    – Jim Zajkowski
                    Oct 29 '09 at 21:51

















                  • Would this not add a lot of complexity in your script to start the master and kill it again after.

                    – David Pashley
                    Oct 27 '09 at 11:10











                  • TANSTAAFL. Virtual memory adds a lot of complexity to your OS kernel, but we do it anyway because the benefits outweigh the disadvantages.

                    – womble
                    Oct 27 '09 at 12:15











                  • No there's not a significant increase in complexity because ControlMaster can be made automatic, and then ssh handles creating and removing the master (unix-domain) socket.

                    – Jim Zajkowski
                    Oct 29 '09 at 21:51
















                  Would this not add a lot of complexity in your script to start the master and kill it again after.

                  – David Pashley
                  Oct 27 '09 at 11:10





                  Would this not add a lot of complexity in your script to start the master and kill it again after.

                  – David Pashley
                  Oct 27 '09 at 11:10













                  TANSTAAFL. Virtual memory adds a lot of complexity to your OS kernel, but we do it anyway because the benefits outweigh the disadvantages.

                  – womble
                  Oct 27 '09 at 12:15





                  TANSTAAFL. Virtual memory adds a lot of complexity to your OS kernel, but we do it anyway because the benefits outweigh the disadvantages.

                  – womble
                  Oct 27 '09 at 12:15













                  No there's not a significant increase in complexity because ControlMaster can be made automatic, and then ssh handles creating and removing the master (unix-domain) socket.

                  – Jim Zajkowski
                  Oct 29 '09 at 21:51





                  No there's not a significant increase in complexity because ControlMaster can be made automatic, and then ssh handles creating and removing the master (unix-domain) socket.

                  – Jim Zajkowski
                  Oct 29 '09 at 21:51













                  1














                  Note: When you say local file, I am not sure if you mean local the machine you just ssh'd into, or if you mean local to the machine the starts the ssh session.



                  Push vs Pull:

                  It sounds like this might not be the right tool, maybe you just want to use cron on each local machine? If information is needed from the master, you can have the cron job fetch a file from the server. This would be more of a pull method, the ssh is what I would call push method. I can't say which is better for your situation, but this may be something to think about.



                  Run Multiple Commands:

                  I don't understand if you mean keep the session open for each itteration of the multiple commands, or just have it sort of always open. If it is the former, you can just use semi-colons between commands, or && to make so the next command will only be executed if the first works. For example:



                  #bar echoed only if foo exists and can be read
                  ssh myServer 'cat foo && echo bar'
                  ssh myServer 'cat foo; echo bar'


                  You can also do stuff like the following if you want to specify use of things in a shell:



                  ssh myServer "bash -c 'cat foo && echo bar'"


                  Lastly, you could always just put the script on each server, and just run that.






                  share|improve this answer





























                    1














                    Note: When you say local file, I am not sure if you mean local the machine you just ssh'd into, or if you mean local to the machine the starts the ssh session.



                    Push vs Pull:

                    It sounds like this might not be the right tool, maybe you just want to use cron on each local machine? If information is needed from the master, you can have the cron job fetch a file from the server. This would be more of a pull method, the ssh is what I would call push method. I can't say which is better for your situation, but this may be something to think about.



                    Run Multiple Commands:

                    I don't understand if you mean keep the session open for each itteration of the multiple commands, or just have it sort of always open. If it is the former, you can just use semi-colons between commands, or && to make so the next command will only be executed if the first works. For example:



                    #bar echoed only if foo exists and can be read
                    ssh myServer 'cat foo && echo bar'
                    ssh myServer 'cat foo; echo bar'


                    You can also do stuff like the following if you want to specify use of things in a shell:



                    ssh myServer "bash -c 'cat foo && echo bar'"


                    Lastly, you could always just put the script on each server, and just run that.






                    share|improve this answer



























                      1












                      1








                      1







                      Note: When you say local file, I am not sure if you mean local the machine you just ssh'd into, or if you mean local to the machine the starts the ssh session.



                      Push vs Pull:

                      It sounds like this might not be the right tool, maybe you just want to use cron on each local machine? If information is needed from the master, you can have the cron job fetch a file from the server. This would be more of a pull method, the ssh is what I would call push method. I can't say which is better for your situation, but this may be something to think about.



                      Run Multiple Commands:

                      I don't understand if you mean keep the session open for each itteration of the multiple commands, or just have it sort of always open. If it is the former, you can just use semi-colons between commands, or && to make so the next command will only be executed if the first works. For example:



                      #bar echoed only if foo exists and can be read
                      ssh myServer 'cat foo && echo bar'
                      ssh myServer 'cat foo; echo bar'


                      You can also do stuff like the following if you want to specify use of things in a shell:



                      ssh myServer "bash -c 'cat foo && echo bar'"


                      Lastly, you could always just put the script on each server, and just run that.






                      share|improve this answer















                      Note: When you say local file, I am not sure if you mean local the machine you just ssh'd into, or if you mean local to the machine the starts the ssh session.



                      Push vs Pull:

                      It sounds like this might not be the right tool, maybe you just want to use cron on each local machine? If information is needed from the master, you can have the cron job fetch a file from the server. This would be more of a pull method, the ssh is what I would call push method. I can't say which is better for your situation, but this may be something to think about.



                      Run Multiple Commands:

                      I don't understand if you mean keep the session open for each itteration of the multiple commands, or just have it sort of always open. If it is the former, you can just use semi-colons between commands, or && to make so the next command will only be executed if the first works. For example:



                      #bar echoed only if foo exists and can be read
                      ssh myServer 'cat foo && echo bar'
                      ssh myServer 'cat foo; echo bar'


                      You can also do stuff like the following if you want to specify use of things in a shell:



                      ssh myServer "bash -c 'cat foo && echo bar'"


                      Lastly, you could always just put the script on each server, and just run that.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Oct 27 '09 at 11:48

























                      answered Oct 27 '09 at 11:38









                      Kyle BrandtKyle Brandt

                      66.4k61263414




                      66.4k61263414





















                          1














                          The "expect" tool could also do what you want, but involves writing tcl.






                          share|improve this answer



























                            1














                            The "expect" tool could also do what you want, but involves writing tcl.






                            share|improve this answer

























                              1












                              1








                              1







                              The "expect" tool could also do what you want, but involves writing tcl.






                              share|improve this answer













                              The "expect" tool could also do what you want, but involves writing tcl.







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Oct 27 '09 at 12:16









                              pjc50pjc50

                              1,7001012




                              1,7001012





















                                  1














                                  To expand on the ControlMaster use, here's a slightly more concrete example:



                                  CONTROL=/tmp/ssh-control-`date +%s`-$RANDOM
                                  ssh -o BatchMode=yes -NfM -S $CONTROL &
                                  MASTERPID=$?

                                  ssh -o BatchMode=yes -S $CONTROL user@host command1 > outfile1
                                  ssh -o BatchMode=yes -S $CONTROL user@host command2 > outfile2

                                  kill $MASTERPID


                                  This is largely untested, but it should give you the right general idea.






                                  share|improve this answer





























                                    1














                                    To expand on the ControlMaster use, here's a slightly more concrete example:



                                    CONTROL=/tmp/ssh-control-`date +%s`-$RANDOM
                                    ssh -o BatchMode=yes -NfM -S $CONTROL &
                                    MASTERPID=$?

                                    ssh -o BatchMode=yes -S $CONTROL user@host command1 > outfile1
                                    ssh -o BatchMode=yes -S $CONTROL user@host command2 > outfile2

                                    kill $MASTERPID


                                    This is largely untested, but it should give you the right general idea.






                                    share|improve this answer



























                                      1












                                      1








                                      1







                                      To expand on the ControlMaster use, here's a slightly more concrete example:



                                      CONTROL=/tmp/ssh-control-`date +%s`-$RANDOM
                                      ssh -o BatchMode=yes -NfM -S $CONTROL &
                                      MASTERPID=$?

                                      ssh -o BatchMode=yes -S $CONTROL user@host command1 > outfile1
                                      ssh -o BatchMode=yes -S $CONTROL user@host command2 > outfile2

                                      kill $MASTERPID


                                      This is largely untested, but it should give you the right general idea.






                                      share|improve this answer















                                      To expand on the ControlMaster use, here's a slightly more concrete example:



                                      CONTROL=/tmp/ssh-control-`date +%s`-$RANDOM
                                      ssh -o BatchMode=yes -NfM -S $CONTROL &
                                      MASTERPID=$?

                                      ssh -o BatchMode=yes -S $CONTROL user@host command1 > outfile1
                                      ssh -o BatchMode=yes -S $CONTROL user@host command2 > outfile2

                                      kill $MASTERPID


                                      This is largely untested, but it should give you the right general idea.







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited 13 hours ago









                                      V1pr

                                      52




                                      52










                                      answered Oct 27 '09 at 13:18









                                      Walter MundtWalter Mundt

                                      35414




                                      35414





















                                          0














                                          You can run several commmands in sequence by starting a shell on the remote system and passing it the commands:



                                          ssh server "echo this is; all in one session"


                                          will automatically pass the quoted string through a remote shell. Beware of shell quoting rules, though!






                                          share|improve this answer



























                                            0














                                            You can run several commmands in sequence by starting a shell on the remote system and passing it the commands:



                                            ssh server "echo this is; all in one session"


                                            will automatically pass the quoted string through a remote shell. Beware of shell quoting rules, though!






                                            share|improve this answer

























                                              0












                                              0








                                              0







                                              You can run several commmands in sequence by starting a shell on the remote system and passing it the commands:



                                              ssh server "echo this is; all in one session"


                                              will automatically pass the quoted string through a remote shell. Beware of shell quoting rules, though!






                                              share|improve this answer













                                              You can run several commmands in sequence by starting a shell on the remote system and passing it the commands:



                                              ssh server "echo this is; all in one session"


                                              will automatically pass the quoted string through a remote shell. Beware of shell quoting rules, though!







                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Oct 27 '09 at 11:39









                                              sleskesleske

                                              8,45732440




                                              8,45732440



























                                                  draft saved

                                                  draft discarded
















































                                                  Thanks for contributing an answer to Server Fault!


                                                  • 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%2fserverfault.com%2fquestions%2f78630%2fretaining-ssh-session-in-bash-script%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

                                                  How to make RAID controller rescan devices The 2019 Stack Overflow Developer Survey Results Are InLSI MegaRAID SAS 9261-8i: Disk isn't recognized after replacementHow to monitor the hard disk status behind Dell PERC H710 Raid Controller with CentOS 6?LSI MegaRAID - Recreate missing RAID 1 arrayext. 2-bay USB-Drive with RAID: btrfs RAID vs built-in RAIDInvalid SAS topologyDoes enabling JBOD mode on LSI based controllers affect existing logical disks/arrays?Why is there a shift between the WWN reported from the controller and the Linux system?Optimal RAID 6+0 Setup for 40+ 4TB DisksAccidental SAS cable removal

                                                  How can I have a shield and a way of attacking at distance at the same time? The 2019 Stack Overflow Developer Survey Results Are InDoes the Thrown property mean I can attack with my DEX?Is it possible to build a custom weapon, and if so, how will my character be able to use it?Can the Ghost Touch weapon property allow an attacker to perform incorporeal touch attacks?The DM allowed me to wield two shields, how can I get the most AC and HP, as a Bear Barbarian?Are there ways other than Kensei Weapons or Hex Warrior to use an ability other than STR for non-finesse melee weapons?Cheapest way to cast spells with sword and (heavy) shield?Is this homebrew “Throwing Weapons Master” feat balanced?Can Hexblade warlocks use a staff and shield?Are there any balance issues with allowing thrown Javelins to be drawn for free like ammunition weapons?Does an unattuned Frost Brand weapon still glow in freezing temperatures?Does a druid starting with a bow start with no arrows?Is it possible to build a custom weapon, and if so, how will my character be able to use it?

                                                  How to properly configure ESX VMs to use hyper threading in a usefull way? The 2019 Stack Overflow Developer Survey Results Are InSQL 2005 Standard QuestionsHow do I best archive VMWare VMs for reuse?ESXi Server with 12 physical cores maxed out with only 8 cores assigned in virtual machinesScaling out within a VMware host - add vCPUs or VMs?VMware - Can a 1 vCPU VM use more than 1 physical core at the same time?Taskset not working over a range of cores in isolcpusWhat are the performance implications of Hyper-threading for single Nehalem+ CPU?VMware CPU Hyper Threading Scheduling AffinityESXi hyper threading numbering for affinity settingsCannot balance eth0 IRQs across CPUs