Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

open a putty window and run ssh commands - Python

I am new to python. I need to login to a server daily (Desktop -> 1.32 -> 0.20 -> 3.26). For this I need to open putty and using ssh connection i am logging in. To do all this I want to write a script using python.

By using google I thought subprocess.Popen will do that. But Its not working fine.

1st trail:

import subprocess
pid = subprocess.Popen("putty.exe [email protected] -pw password").pid

Its working fine (Opening window logging into .32). But cant able to give input. I came to know that to give input for the same process we need to use pipes.

2nd trail:

from subprocess import Popen, PIPE, STDOUT
p = Popen("putty.exe [email protected] -pw password", stdout=PIPE, stdin=PIPE, stderr=STDOUT)    
grep_stdout = p.communicate(input=b'ssh xx.xx.x.20\n')[0]
print(grep_stdout.decode())

by using this i cant login for the first server also. After logging in to all servers I need the terminal as alive. how to do this???

Edit

I need to do this in a new putty window. After logging in dont close the window. I have some manual work to do.

like image 238
Swapna murahari Avatar asked Feb 26 '26 03:02

Swapna murahari


1 Answers

There is a SSHv2 protocol implementation for python: http://www.paramiko.org/. You can easily install it with pip:

pip install paramiko

Then you can create ssh client, connect to your host and execute commands:

import paramiko
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect('hostname', username='login', password='pwd')
stdin, stdout, stderr = ssh_client.exec_command('command')
like image 146
wombatonfire Avatar answered Mar 01 '26 04:03

wombatonfire