I'm using Python's telnetlib to telnet to some machine and executing few commands and I want to get the output of these commands.
So, what the current scenario is -
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("command1")
tn.write("command2")
tn.write("command3")
tn.write("command4")
tn.write("exit\n")
sess_op = tn.read_all()
print sess_op
#here I get the whole output
Now, I can get all the consolidated output in sess_op.
But, what I want is to get the output of command1 immediately after its execution and before the execution of command2 as if I'm working in the shell of the other machine, as shown here -
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("command1")
#here I want to get the output for command1
tn.write("command2")
#here I want to get the output for command2
tn.write("command3")
tn.write("command4")
tn.write("exit\n")
sess_op = tn.read_all()
print sess_op
I ran into something similar while working with telnetlib.
Then I realized a missing carriage return and a new line at the end of each command and did a read_eager for all commands. Something like this:
tn = telnetlib.Telnet(HOST, PORT)
tn.read_until("login: ")
tn.write(user + "\r\n")
tn.read_until("password: ")
tn.write(password + "\r\n")
tn.write("command1\r\n")
ret1 = tn.read_eager()
print ret1 #or use however you want
tn.write("command2\r\n")
print tn.read_eager()
... and so on
instead of only writing the command like:
tn.write("command1")
print tn.read_eager()
If it worked with just a "\n" for you, adding only a "\n" might be enough instead of "\r\n" but in my case, I had to use "\r\n" and I haven't tried with just a new line yet.
You must refer to the documentation of telnetlib module here.
Try this -
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("command1")
print tn.read_eager()
tn.write("command2")
print tn.read_eager()
tn.write("command3")
print tn.read_eager()
tn.write("command4")
print tn.read_eager()
tn.write("exit\n")
sess_op = tn.read_all()
print sess_op
I was also going through the same issue where the read_very_eager() function was not displaying any data. From some post got the idea that the command will require some time to execute. so used the time.sleep() function.
Code Snippet:
tn.write(b"sh ip rou\r\n")
time.sleep(10)
data9 = tn.read_very_eager()
print(data9)
Related
with python script I want to make some configuration on mikrotik routers, looks like script is right and no gives errors but ends without printing command outputs
import telnetlib
import time
dev_ip = "172.16.62.160"
user = "admin"
PASSWORD = ""
comm1 = "ip address print"
tn = telnetlib.Telnet(dev_ip, timeout=1)
tn.read_until(b"Login: ")
tn.write(user.encode("ascii") + b'\n')
tn.read_until(b"Password: ")
tn.write(PASSWORD.encode("ascii") + b'\n')
tn.read_until(b">")
time.sleep(1)
tn.write(comm1.encode("ascii") + b"\r\n")
Showcmdoutput = tn.read_very_eager().decode('ascii')
print(Showcmdoutput)
tn.close()
print("DONE")
running on Ubuntu Desktop
problem solved after putting:
time.sleep(1)
before Showcmdoutput = tn.read_very_eager().decode('ascii')
tn.write(comm1.encode("ascii") + b"\r\n")
time.sleep(1)
Showcmdoutput = tn.read_very_eager().decode('ascii')
I have written a program that can change the system's IP address/password automatically at a specific time. In addition, it has two separate python files.
The first one is a program that runs the main program under the service, retrieves the desired information from the user and stores it in a `.txt' file.
# Import/Lib
import os
import sys
import pysc
import time
# Services
if __name__ == '__main__':
service_name = 'test4'
script_path = os.path.join(
os.path.dirname(__file__)+"\\"+"Run.exe"
)
pysc.create(
service_name=service_name,
cmd=[sys.executable, script_path]
)
print("CreateService SUCCESS")
pysc.start(service_name)
print("StartService SUCCESS")
# Input data
time_today = input("Enter a Time (MM:SS): ")
date_today = input("Enter a Date (YYYY-MM-DD): ")
adapter_name = input("Enter your interface name: ")
interface_name = "\"" + adapter_name + "\""
static_ip = input("Enter your static ip: ")
subnet = input("Enter your subnet mask: ")
gateway = input("Enter your gateway: ")
time.sleep(0.5)
print("")
pass_complexity = "Windows password complexity rules:""\n" \
"-Password must not contain the user's account name or more than two consecutive "\
"characters from the user's full name.""\n"\
"-Password must be six or more characters long.""\n"\
"-Password must contain characters from three of the following four categories:""\n"\
" .Uppercase characters A-Z (Latin alphabet)""\n"\
" .Lowercase characters a-z (Latin alphabet)""\n"\
" .Digits 0-9""\n"\
" .Special characters (!, $, #, %, etc.)""\n"
print(pass_complexity)
password = input("New password: ")
conform_pass = input("Confirm password: ")
stop = True
while stop == True:
if password == conform_pass:
print("Input info completed")
print("Interface adapter", interface_name + ":")
print("IPv4 Address. . . . . . . . . . . : ", static_ip)
print("Subnet Mask . . . . . . . . . . . : ", subnet)
print("Default Gateway . . . . . . . . . : ", gateway, "\n")
print("Your password:", password, "\n")
stop = False
else:
print("Sorry, passwords do not match.", "\n")
password = input("New password: ")
conform_pass = input("Confirm password: ")
# Write file
file_name = os.path.dirname(__file__)+"\\"+"Network Monitoring Utility.txt"
my_file = open(file_name, 'w')
my_file.write(time_today+" ")
my_file.write(date_today+" ")
my_file.write(interface_name+" ")
my_file.write(static_ip+" ")
my_file.write(subnet+" ")
my_file.write(gateway+" ")
my_file.write(password+" ")
my_file.close()
wait = input("Please enter for exit.")
The second program compares the system clock with the read time by reading the desired .txt file information. If the system date and time are the same as the date and time entered, it will change the system's IP address/password.
# Import Lib
import subprocess
import getpass
from datetime import date
import datetime
import time
time.sleep(90)
# Read data
my_file = open('Network Monitoring Utility.txt', 'r')
data = my_file.read()
data = data.split()
my_file.close()
time = data[0]
set_date = data[1]
interface_name = data[2]
static_ip = data[3]
subnet = data[4]
gateway = data[5]
password = data[6]
# Check data and time and change ip, subnet mask, gateway and password
stop = True
while stop == True:
now_time = str(datetime.datetime.now().time())
now_date = str(date.today())
if now_date == set_date and now_time > time:
stop = False
subprocess.check_call("netsh interface ipv4 set address name="
+ interface_name + " " + "static" + " " + static_ip + " " + subnet + " "
+ gateway, shell=True)
username = getpass.getuser()
subprocess.check_call("net users " + username + " " + password, shell=True)
When I run this program in Pycharm it runs without any problems. But when I convert both programs with pyinstaller to '.exe', the program will not run under service. this will cause an error.
filenotfounderror: [winerror 2] the system cannot find the file specified.
This message is also because the program requires a Python executable file to run severely on the service.
How to run this service without having to install Python on a system?
I need to write in a txt file during a infinite while. But it's not writing and if I don't use infinite while it's works.
What do I have to change ?
My goal is to ping different ip infinite time and when the ping fails, it's written in the file with the time and date
I've tried the code without the while True and it works.
I think the code need to be stop to write but can we do without stop ?
import os
import datetime
fichier = open("log.txt", "a")
date = datetime.datetime.now()
hostnames = [
'192.168.1.1',
'192.168.1.2',
'192.168.1.3',
]
while True :
for hostname in hostnames:
ping = os.system(" Ping " + str(hostname))
if ping == 1:
print("DOWN")
fichier.write(str(date) + " " + str(hostname) + '\n' + '\n')
else:
print("UP")
I expect the output when it's failed with a stamp Date/Time and the IP Address
To sum up all the answers in one:
try:
with open('log.txt', 'a') as fichier:
while True:
for hostname in hostnames:
ping = os.system(" Ping " + str(hostname))
if ping == 1:
print("DOWN")
fichier.flush()
fichier.write(str(date) + " " + str(hostname) + '\n' + '\n')
else:
print("UP")
except KeyboardInterrupt:
print("Done!")
I am writing a simple script in python , to telnet multiple cisco switches and add vlans. I am testing my script in UNET LABS or latest EVE-NG.
When I telnet to multiple switches using FOR loop and call
tn = telnetlib.Telnet(HOST)
from with in loop , it only telnets to last value in variable HOST i.e. 10.1.1.7
Here is my code,
#!/usr/bin/env python
import getpass
import sys
import telnetlib
user = raw_input("Enter your telnet username: ")
password = getpass.getpass()
for h in range (2,8):
print "Telnet to host" + str(h)
HOST = "10.1.1." + str(h)
tn = telnetlib.Telnet(HOST)
tn.read_until("Username: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("conf t\n")
for n in range (10,20):
tn.write("vlan " + str(n) + "\n")
Following code is working for me. Put all of your IPs in a sheet (IP_test.txt).
import getpass
import sys
import telnetlib
user = "YOURUSER"
password = "YOURPASSWORD"
with open('IP_test.txt') as file:
for HOST in file:
tn = telnetlib.Telnet(HOST)
tn.read_until("login: ")
tn.write(user + "\n")
if password:
tn.read_until("Password: ")
tn.write(password + "\n")
tn.write("Command1\n")
tn.write("Command2\n")
print(tn.read_all())
This python script below works for me for the same purpose
#!/usr/bin/env python3
import getpass
import telnetlib
user = input("Enter your Telnet Username: ")
password = getpass.getpass()
DeviceList=open('/home/tt/Hostname.txt')
for HOST in DeviceList:
print('Configuring on Device : ',HOST)
tn = telnetlib.Telnet(HOST)
tn.read_until(b"Username: ")
tn.write(user.encode('ascii') + b"\n")
if password:
tn.read_until(b"Password: ")
tn.write(password.encode('ascii') + b"\n")
tn.write(b"enable\n")
EnPass=input('Enter your Enable password : ')
tn.write(EnPass.encode('ascii')+b'\n')
c=open('/home/tt/Commands.txt')
for i in c:
tn.write(i.encode('ascii')+b'\n')
c.close()
print(tn.read_all().decode('ascii'))
tn.close()
DeviceList.close()}
Here's my issue. I'm trying to ssh to Cisco devices and pull information off. When I run my code, the print statement adds a new line with a 0 in it to the bottom of the output. Here is the output of the code followed by the output of the plink CLI input:
C:\Python30>python PLINKSSHtest.py
Enter your username: josh
Password:
plink -pw nowayjose -ssh nope#1.1.1.1 "show run | inc hostname"
hostname net-R2
0 <------------MY ISSUE
C:\Python30>plink -pw nowayjose -ssh nope#1.1.1.1 "show run | inc hostname"
hostname net-R2
<------------WHAT I EXPECT
Here is my code:
def read_dev():
# Print statement here for debugging
print ("plink -pw " + password + " -ssh " + user + "#" + HOST + " " + command)
cur_dev = os.system("plink -pw " + password + " -ssh " + user + "#" + HOST + " " + command)
return(cur_dev)
HOST = None
user = input("Enter your username: ")
password = getpass.getpass()
command = '"show run | inc hostname"'
HOST = '1.1.1.1'
print (read_dev())
cur_dev is getting the result code returned by the plink command, which is 0. Your read_dev function returns this code, so print(read_dev()) prints the 0.
Just say read_dev() instead of print(read_dev()).
It doesn't "print zero". It prints cur_dev which is returned by read_dev function, which happens to be zero. And it does so, because you told it to. Remove print function and it won't print anything."
If you want to explicitly set the exit code use sys.exit(cur_dev). Simply using a return value from a function does not do what you want it to.