Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Paramiko send CTRL+C to an ssh shell

I'm invoking a shell using Paramiko in order to use a CLI over an ssh connection. The problem with this CLI is if I do not close it specifically using CTRL+C, the program will not be able to be opened again without rebooting my system.

I've tried the below commands:

SSH.send("^C\n")
SSH.send("\x003")

is there another way to call these? Again, I've established an SSH connection using paramiko.SSHClient() and then invoked a shell using ssh.invoke_shell() and now i need to send CTRL+C to that shell to close the shell (not the ssh connection)

like image 662
bladexeon Avatar asked Oct 22 '15 20:10

bladexeon


People also ask

What is Paramiko SSHClient ()?

SSHClient. A high-level representation of a session with an SSH server. This class wraps Transport , Channel , and SFTPClient to take care of most aspects of authenticating and opening channels. A typical use case is: client = SSHClient() client.

Can I SSH from python?

In python SSH is implemented by using the python library called fabric. It can be used to issue commands remotely over SSH.

How do I get stdout from Paramiko?

Using exec_command() in Paramiko returns a tuple (stdin, stdout, stderr) . Most of the time, you just want to read stdout and ignore stdin and stderr . You can get the output the command by using stdout. read() (returns a string) or stdout.


2 Answers

You're on the right track with your second example, but it isn't quite formatted right. You're actually getting a 2 character string there.

SSH.send("\x03") should do the trick.

However, I'd probably have used this instead.

SSH.send(chr(3))

like image 126
Bill Avatar answered Sep 29 '22 09:09

Bill


Based on: https://stackoverflow.com/a/11190794/565212

You can -
either: pass get_pty=True when calling client.exec_command(). Then client.close() terminates the remote tail.
or: do channel.get_pty() before calling channel.exec_command(). Then channel.close() terminates the remote tail.

like image 35
Tapomay Avatar answered Sep 29 '22 08:09

Tapomay