Continuous ssh connection and sudo password with python

Arif Burak Demiray
1 min readNov 21, 2022

Hi all,

We needed a custom manuel deployer with ssh connection. To send commands and watch their responses were a bit tricky.

Firstly, I did it with bash but it was not easy to manage ssh connection in bash.

I learned paramiko in python and decided use it.

To give sudo pwd to connection you need to send sudo password in a new line like

user$ sudo ls
SUDO_PWD

To make this in paramiko send your command like

channel.send(f"{str(command)}\nSUDO_PWD")

This is the basic way, you can implement your own.

And to read big responses I implemented duration based command control mechanism

start = datetime.utcnow()
try:
while((datetime.utcnow() - start).seconds <= command.duration*3):
froze() #2.5 seconds
output = channel.recv(9999) #read all possible
print(output.decode('utf-8')) #and print
except KeyboardInterrupt:
break

Here you can see, I know pretty much how my command is gonna take. I wait for duration*3 seconds and read response every 2.5 seconds to simulate continuous response.

To learn about my code please have a look at my github repo

Thank you for reading

--

--