title: How to handle SSH-session using pexpect?
body: <p>I am trying to automate a small task that requires several steps and some of the steps would be identical for all the "devices":
  - ssh login
  - run a command
  - clean after itself</p>
  
  <p>I have a script that uses pexpect but for every function (task) I have to establish SSH connection which is lame. </p>
  
  <p>What I am trying to do is kind of like this:</p>
  
  <p>A function that would create a session and another functions that would use the same "child"</p>
  
  <pre><code>def ssh_login(device):
      child.spawn("ssh root@"+device)
      child.expect("password:")
      child.sendline(password)
      child.expect("#")
  </code></pre>
  
  <p>Another function that would use the session and run some command like</p>
  
  <pre><code>def run_command():
      # run some command here
      child.sendline("some_command")
      child.expect("#")
  </code></pre>
  
  <p>And a clean up function</p>
  
  <pre><code>def cleanup():
      child.sendline(cleanup)
      child.expect("#")
      child.sendline("exit")
      child.interract()
  </code></pre>
  
  <p>Any ideas?</p>