title: Python ssh command to change user
body: <p>I need to run a python script that will ssh to a remote host.  The first command to run on this remote host is "sudo su".  I have the password for it.  Then I need to cd to a directory and copy a file to my local box.  I tried in two ways.  Both of them don't work.</p>
  
  <p>script #1:</p>
  
  <pre><code>ssh=paramiko.SSHClient()
  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  ssh.connect(hostName,username='e0258595',password='&lt;password&gt;')
  stdin,stdout,stderr = ssh.exec_command("sudo su; whoami")
  stdin.write('password\n')
  stdin.flush()
  data = stdout.readlines()
  for line in data:
      print line
  </code></pre>
  
  <p>The output is still e0258595.</p>
  
  <p>Script #2:</p>
  
  <pre><code>ssh = paramiko.SSHClient()
  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  ssh.connect(hostName, username="e0258595", password="&lt;password&gt;")
  transport = ssh.get_transport()
  session = transport.open_session()
  session.set_combine_stderr(True)
  session.get_pty()
  #for testing purposes we want to force sudo to always to ask for password. because of that we use "-k" key
  session.exec_command("sudo su; whoami")
  stdin = session.makefile('wb', -1)
  stdout = session.makefile('rb', -1)
  #you have to check if you really need to send password here
  stdin.write("&lt;password&gt;"+'\n')
  stdin.flush()
  data = stdout.readlines()
  for line in data:
       print line
  </code></pre>
  
  <p>This one just hang.  </p>
  
  <p>What is the problem?  </p>