2

I'm creating an SSH Channel to a remote host using paramiko. However, when I try to execute any command using the ssh_object.exec_command, the command doesn't seem to get executed.

This function creates my ssh handler:

def ssh_connect(ip,user,pwd):
    '''
    This function will make an ssh connection to the ip using the credentials passed and return the handler
    Args:
        ip: IP Address of the box into which ssh has to be done
        user: User name of the box to which ssh has to be done
        pass: password of the box to which ssh has to be done
    Returns:
        An ssh handler
    '''
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(ip, username=user, password=pwd)  
    return ssh

And this is where I'm using the handler:

ssh_obj = ssh_connect(ip, username, password)
folder = "/var/xyz/images/" + build_number
command = "mkdir " + folder
ssh_stdin, ssh_stdout, ssh_stderr = ssh_obj.exec_command(command)

When I go to the remote machine, the folder has not got created. Similarly, I tried reading the output of an ls command as well. No response arrives when I do ssh_stdout.read().

Where am I going wrong?

Randomly Named User
  • 1,889
  • 7
  • 27
  • 47

2 Answers2

1

I encountered with the same problem on CentOS 7 servers using paramiko 2.0.2. The example from the paramiko github homepage didn't work for me at first: https://github.com/paramiko/paramiko#demo

import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=self.server['host'], username=self.server['username'], password=self.server['password'])
stdin, stdout, stderr = client.exec_command('ls')
for line in stdout:
    print '... ' + line.strip('\n')
client.close()

After I updated the remote system the example above started to work. But not the code I wrote (similar to OP's code) This put an idea that I need to read the stdout buffer right after the execution. So that I amended the code to do it and it worked. Based on OP's code it could look like

ssh_obj = ssh_connect(ip, username, password)
folder = "/var/xyz/images/" + build_number
command = "mkdir " + folder
ssh_stdin, ssh_stdout, ssh_stderr = ssh_obj.exec_command(command)
# Read the buffer right after the execution:
ssh_stdout.read()

What's interesting is that reading the buffer later (after you close the client) gives you nothing.

Alexandr Nikitin
  • 7,258
  • 2
  • 34
  • 42
0

After the ssh_exec_command line; add the below condition.

The loop will exit only after the command(shell) gets fully executed.

while int(stdout.channel.recv_exit_status()) != 0: time.sleep(1)

ysf
  • 4,634
  • 3
  • 27
  • 29
Sarath Baby
  • 51
  • 1
  • 4