Saturday, March 30, 2019

Python with telnet

There are many resources related to telnet lib from the net. I'm just going to show you a few of them

1) Just enter the host ip adress and username and password

import telnetlib
HOST = "192.168.1.253"
user = "root"
password = "arrisc4"

def command(con, flag, str_=""):
    data = con.read_until(flag.encode())
    print(data.decode(errors='ignore'))
    con.write(str_.encode() + b"\n")
    return data
tn = telnetlib.Telnet(HOST)
command(tn, "Login:", user)
if password:
    command(tn, "Password:", password)
command(tn, "#", "en")
#command(tn, "$", " exit")
#command(tn, "$", "")
tn.close()

2)user just enter in their username and password

import getpass
import telnetlib
HOST = "192.168.1.253"
user = input("Enter your remote account: ")
password = getpass.getpass()
tn = telnetlib.Telnet(HOST)
tn.read_until(b"Login:")
tn.write(user.encode('ascii') + b"\n")
if password:
    tn.read_until(b"Password:")
    tn.write(password.encode('ascii') + b"\n")
#tn.write(b"ls\n")
#tn.write(b"exit\n")
tn.write(b"en\n")
tn.write(password.encode('ascii') + b"\n")
tn.write(b"show running-config \n")
tn.write(b"exit\n")
print(tn.read_all().decode('ascii'))

PYTHON read and write file

When we wants to read some file especially with text file, we will used the read and write methods.


 line = line.strip()  and print(line,end='') is the same.
If you don't used this two code, it will automatic add new line to each line while it read the text file.



===========================Source code===================


EXAMPLE1:

 METHOD1

with open('test.txt') as f,open('out.txt', 'w') as f_out:
    for line in f:
        line = line.strip()
        print(line)

 METHOD2

with open('test.txt') as f,open('out.txt', 'w') as f_out:
    for line in f:
        print(line,end='')




Note:
There are two ways to implement this function on reading a file from text file.
You can use line.strip or use (ine,end’’)


OUTPUT:



EXAMPLE2:


with open('test.txt') as f,open('out.txt', 'w') as f_out:
    for line in f:
        line = line.strip()
        #print(line)
        f_out.write('{}\n'.format(line))
    

 NOTE:

Output to a file need to use this:
f_out.write('{}\n'.format(line))

OUTPUT:

EXAMPLE3:
 

sum=0
count=0
for grade in open('grade.txt'):
    print(grade, end='')
    sum=sum+int(grade)
    count=count+1
average =sum/count
print("Aaverage:"+str(average))

 OUTPUT: