0

I'm trying to send command using ssh spawn to remote machine. I'm sending the command using Popen() and I can see the command was done but after that I'm trying to use communicate() (to close the session and get a return code) and the program get stuck.

cmd = """expect -c 'spawn ssh -o LogLevel=quiet """ \
      """-o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o PreferredAuthentications=publickey """ \
      """-o ConnectTimeout=10 -2 -o CheckHostIP=no -i {0} {1}@{2} ;\
      """expect "#";send "mkdir test9\n" ;interact'""".format(self.sshKey, SSHUser, self.hostname) 
process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p_stdoutdata, p_stderrdata = process.communicate()

When I'm reaching the communicate the program gets stuck.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
MayaC
  • 61
  • 1
  • 7

1 Answers1

0

Don't use Popen to call ssh. Instead, use a library that does it all in-process in Python, such as the excellent Paramiko. In your case it might look something like this:

import paramiko

client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
client.connect(self.hostname, 22, SSHUser, password)

sftp = paramiko.SFTPClient.from_transport(client.get_transport())
sftp.mkdir("test9")
sftp.close()

client.close()
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • How can i send SSHkey instead of password? How can i get a return code that way? and if i need other commends send by the user? – MayaC Dec 16 '15 at 11:45
  • Please read the docs (http://docs.paramiko.org/). Other commands can be executed by `client.exec_command()`. You can pass `key_filename` instead of `password` if you like. And as for how to get a return code, I'm not sure what you mean, but if you are asking how to find out if `mkdir` failed--it will raise an exception. – John Zwinck Dec 16 '15 at 11:54