Command execution on a remote server with ssh2-python

Hey guys!

I’m fairly new to python (3 hours in tbh) and I’m tryin to write a function that is able to connect to a remote server and then execute those commands.
As stated, I’m using ssh2-python.

def command_exec(command):
    print('Executing command: ' + command)
    channel.write(command + '\n')
    print('Wrote command!')
    size, data = channel.read()
    print(size)
    print(data.decode())

This code works perfectly… whenever I forward a command that has stdout.
For example running: command_exec(‘echo “hey”’) will work perfectly!
But, running something like: command_exec(‘cd /usr/local/folder/’) will get stuck…

So I’ve figured out the issue: if a command that is forwarded doesn’t return any response (doesn’t have stdout), the function will get stuck.
I’ve tried finding a solution, but to no avail.
Worth mentioning: I don’t want to set timeout on a command, because there are some commands that I’m gonna execute on the remote server that might take a while, so setting a timeout would be a huge mistake.
Is there any solution to this?

Thanks!

What happens if you run a multi-command with the final command being an outputting function?

Instead of sending ‘cd /usr/local/folder/’, what happens if you send ‘cd /usr/local/folder/; echo 1’?

1 Like

Also, adding to this question. Is it possible to know when a command is done executing?
Basically, I have an array of commands:

commands = ['command_1', 'command_2', 'command_3']

and I’m looping through those commands:

 for command in commands:
        command_exec(command)

And if say, “command_2” takes 20 seconds to execute, is there a way to wait for command_2 to execute before jumping to command_3?

That didn’t cross my mind and that works perfectly! Thank you!

It may also be able to help you with your timing issue; if you end your command with somehting meaningful (echo command1 for command 1), and wait until you read an output that says “command1”, you know the command is finished (as long as it’s not asynchronous, anyway)

1 Like

I think that’ll actually do it! Thank you @m_hutley!