Write in to telnet session telnetlib - python-3.x

I need to get a connection to a device via TELNET and write in to telnet session.
I Use - Python 3.3.2 and PyDev For Eclipse 2.7.5
I use IP2COM cause it allows me to open another telnet to the same device and see how the commands are executed.
The main purpose of this is to Read\Write in to Telnet session using Python.
Here is the code that i use:
import getpass
import sys
import telnetlib
HOST = "172.17.174.50"
port = "1003"
#user = input("Enter your remote account: ")
#password = getpass.getpass()
tn = telnetlib.Telnet(HOST, port)
#tn.read_until("user:")
#tn.write(user.encode('ascii') + b"\r")
#tn.write(user.encode("test" + "\r")
#if password:
# tn.read_until(b"Password: ")
# tn.write(password.encode('ascii') + b"\n")
tn.write("sh run" + "\r")
tn.write("exit" + "\r")
print(tn.read_all()
Here is the error that i'm getting :
File "C:\Users\user\workspace\main\src\telnet.py", line 23
^
SyntaxError: unexpected EOF while parsing
The strange thing is that i have only 22 lines.. line number 23 is empty...
Can someone help me with that?
Thanks.

A parenthesis is missing in the last line.
print(tn.read_all())

print(tn.read_all().decode('ascii'))
Try this.

Related

Python3 telnetlib - telnet with username and password and then execute other commands

I would like to be able to telnet, input login and password credentials and then execute commands once connected but my code seems to not continue after password is entered.
import getpass
import telnetlib
HOST = "172.25.1.1"
user = input("Enter your remote account: ")
password = getpass.getpass()
tn = telnetlib.Telnet(HOST)
tn.read_until(b"login: ")
tn.write(user.encode('utf-8') + "\n")
if password:
tn.read_until(b"Password: ")
tn.write(password.encode('utf-8') + "\n")
tn.write(b"command to be issued")
print(tn.read_all())
with this code I want to telnet, input login credentials, input password, and once connected issue a command
Looks like the problem was a timing issue, I needed to import time and add time.sleep(2) after issuing the command before print(tn.read_all()).

How to execute commands in a remote server using python?

This question is related to this other one: How to use sockets to send user and password to a devboard using ssh
I want to connect to the devboard in order to execute a script. All the outputs of that script I want to send to a Elasticsearch machine.
I can connect to the devboard (see IMAGE below) using my laptop which happens to have Elasticsearch installed. But, when I want to send data to the devboard, the script shows nothing.
What I am doing is:
As soon as you find mendel#undefined-eft:~$ , send the command: cd coral/tflite/python/examples/classification/Auto_benchmark\n
What am I doing wrong?
import paramiko
import os
#Server's data
IP = '172.16.2.47'
PORT = 22
USER = 'mendel'
PASSWORD = 'mendel'
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname = IP, port=PORT, username = USER, password = PASSWORD)
channel = ssh.invoke_shell() #to get a dedicated channel
channel_data = str()
host = str()
while True:
if channel.recv_ready(): #is there data to be read?
channel_data += channel.recv(9999).decode("utf-8")
os.system('clear')
print(channel_data)
#ONLY WORKS UNTIL HERE!!!
else:
continue
if channel_data.endswith('mendel#undefined-eft:~$'):
channel.send('cd coral/tflite/python/examples/classification/Auto_benchmark\n')
channel_data += channel.recv(9999).decode("utf-8")
print(channel_data)
IMAGE
EDIT
channel = ssh.invoke_shell() #to get a dedicated channel
channel_data = str()
host = str()
while True:
if channel.recv_ready(): #is there data to be read?
channel_data += channel.recv(9999).decode("utf-8")
os.system('clear')
print(channel_data)
else:
continue
if channel_data.endswith('mendel#undefined-eft:~$ '):#it is good to send commands
channel.send('cd coral/tflite/python/examples/classification/Auto_benchmark\n')
#channel_data += channel.recv(9999).decode("utf-8")
#print(channel_data)
elif channel_data.endswith('mendel#undefined-eft:~/coral/tflite/python/examples/classification/Auto_benchmark$ '):
channel.send('ls -l\n') #python3 auto_benchmark.py')
channel_data += channel.recv(9999).decode("utf-8")
print(channel_data)
I guess you have to change the
if channel_data.endswith('mendel#undefined-eft:~$'):
to
if channel_data.endswith('mendel#undefined-eft:~$ '):
according to your prompt. Please note the space after :~$

Python code for telnetting DUT needs further optimization

I need to further optimize my code in Python.
I was earlier executing commands on the Device Under Test step by step which was a lot as I also required sleep timers. However I was able to minimize it through a list and calling elements of the list in a for loop:
I need your inputs to further optimize this code:
ConfigListBFD = ['conf t' , 'int Fa1/0' , 'ip address 10.10.10.1 255.255.255.0', 'no shut']
for i in ConfigListBFD:
tn.write(i.encode('ascii') + b"\n")
print (i, "command entered successfully")
time.sleep(2)
Please note: I am telnetting the DUT as ssh is not supported.
i am using this optimized common code for telnet. we can create a common file where you can add this method
import telnetlib
import time
def telnet(host):
user = <username>
password = <password>
try :
tn = telnetlib.Telnet(host)
except :
print("Unable to connect")
sys.exit()
tn.read_until(b"Username:") # read until username prompt
tn.write(user.encode('ascii') + b"\n")
if password:
tn.read_until(b"password:") #read until password prompt
tn.write(password.encode('ascii') + b"\n")
tn.read_until(b"#")
return tn #return telnetlib handle
than import this method to another file, where we write our script

Is their way, I can open a putty session and execute the commands written in the code below; (don't not share pywinauto examples)

Below is the source code which I created on python, however, unable to run from window machine.
If I use the same on Ubuntu, it works well.
Is their way, I can open a putty session and execute the commands written in the code below;
HOST = " 192.168.15.101"
user = input("Enter your device username: ")
password = getpass.getpass()
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("enable\n")
tn.write("cisco\n")
tn.write("conf t\n")
tn.write("interface loop 1\n")
tn.write("ip address 1.1.1.1 255.255.255.255\n")
tn.write("interface loop 2\n")
tn.write("ip address 1.1.1.2 255.255.255.255\n")
tn.write("interface loop 3\n")
tn.write("ip address 1.1.1.3 255.255.255.255\n")
tn.write("interface loop 4\n")
tn.write("ip address 1.1.1.4 255.255.255.255\n")
tn.write("end\n")
tn.write("exit\n")
print(tn.read_all())

Multiple printing to file

I'm newbie with python 3.6 and I have question about printing to file multiple times using ssh commands.
I'm trying to print multiple show commands after i create ssh session.
The ssh session established and the first show command works fine (printed to created file).
Any other command isn't working as the first one.
My code:
import paramiko
host = '192.168.100.1'
user = 'MyUser'
secret = 'MyPass'
port = 22
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #Set policy to use when connecting to servers without a known host key
ssh.connect(hostname=host, username=user, password=secret, port=port)
file = open("output/" + host + ".txt", "w")
stdin, stdout, stderr = ssh.exec_command('sh ver')
output = stdout.readlines()
file.write(''.join(output))
stdin.flush()
stdin, stdout, stderr = ssh.exec_command('sh arp')
output = stdout.readlines()
file.write(''.join(output))
file.close()
I would like to get assist,
Thanks.

Resources