I am doing ssh to a server using parmiko in python. From there, I need to telnet to several devices and capture the output. I am able to ssh and then telnet to only one device but not ablke to telnet multiple devices from a loop. please suggest me how to do this. I am using the following
import paramiko
import telnetlib
ip = ''
port = 42705
username = ''
password = ''
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)
f=open("abc.txt", "r")
x=f.readlines()
i=1
if i < 100:
print i
cmd = "telnet " + x[i]
print cmd
i=i+1
stdin, stdout, stderr = ssh.exec_command(cmd)
stdin.write('''
terminal length 0
show platform
exit
''')
outlines = stdout.readlines()
resp = ''.join(outlines)
print(resp)
when I am not using if statement and directly giving ip, its working good. But I need to telnet multiple devices from same server. Thanks for your reply!
I am now using the following code:
#! /usr/bin/python
import sys
import paramiko
ip=''
port=42705
username=''
password=''
f1=open("abc.txt", 'r')
devices=f1.readlines()
for device in devices:
device = device.rstrip()
print device
command = "telnet " + device
ssh = paramiko.SSHClient()
print command
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, port, username, password)
stdin, stdout, stderr = ssh.exec_command(command)
stdin.write('''
primenms
primenms123
terminal length 0
show platform
exit
ls
''')
outlines = stdout.readlines()
resp = ''.join(outlines)
print(resp)
ssh.close()
f1.close()
It is able to ssh but when I am doing telnet from ssh server, its entering credentials primenms and primenms123 as username and password, which is correct credentials, but its showing as authorization failed. Where am I going wrong? Please help me guys!
You should likely be using a for loop instead:
for i in f.readlines():
cmd = "telnet {0}".format(i)
print cmd
Ideally you'd want to execute the commands with:
ssh.exec_command(cmd)
Then you could use it like the following example:
for i in f.readlines():
cmd = "telnet {0}".format(i)
ssh.exec_command(cmd)
Without knowing what is within abc.txt you might need other ssh commands in there too.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With