How to store a Telnet output into a variable in python - python

I am trying to use telnet to run a command and grab a value from a text output and store it in a variable in python. In the image, the value I am trying to grab is the External alarm contact 2: Analog input value. In this case 5.99 which I want stored in a variable.
I need to store the 5.99 value or whatever it may change to in a variable :

If you are using the telnetlib library for Python, you can use read_until() and specify a string it should read up to, or read_all() to read the output until EOF and obtain the output from the string.
import getpass
import sys
import telnetlib
HOST = "localhost"
user = raw_input("Enter your remote account: ")
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("ls\n")
tn.write("exit\n")
print tn.read_all()
https://docs.python.org/2/library/telnetlib.html#telnet-objects

Related

Issues with input() and raw_input() for Python 2.7. User entered data is not read properly. What is going on?

So at my company they are making me use python 2.7 because of the product for a compatibility reason that I won't get into here.
So I am writing a program that connects to a device using SSH (a switch specifically) and I am able to actually access the device using SSH and this device is ping-able on my machine. The problem ? raw_input seems to not be taking it as a string. When I try input(), it gives me an invalid syntax error.
For the scripts I write, I usually use arparse and the user enters the IP address, username, and password through the terminal, but I want this script to not use argparse and to use input() or raw_input. All my SSH scripts work good except for this one, the only one using raw_input and input() instead of argparse
def runMain():
scriptName = os.path.basename(__file__)
print("The name of this script is: " + scriptName)
print("**************************************\n")
print("This script allows you to enable and disable ports on the SNET or SOOBM switches, have fun ! \n")
print("**************************************\n")
optionPrinter_switches_top()
user_input = raw_input("Make your selection") # This does not work if I change to input(), it exits out of the program
if user_input == 1:
print("You selected the SNET switch, lets proceed !")
deviceIP = input("Enter the IP address for this device") # I tried changing these to raw_input, I get a syntax issue
deviceUsername = input("Enter the username for this device")
devicePassword = input("Enter the password for this device")
confirm_ping = canPing(deviceIP) # This is a boolean function that works correctly in every script but this one.
if confirm_ping:
ssh_SNET = connectToSSH_SNET(deviceIP, deviceUsername, devicePassword)
else:
print("Sorry, that device is not even ping-able. Figure that issue out and retry the program...")
sys.exit(-1)
while True:
SNET_options()
user_choice_SNET = input("Please select an option")
switch_result = SNET_switch_func(user_choice_SNET)
if switch_result == "displayInterfaceBrief":
time.sleep(5)
displayInterfaceBrief_SNET(ssh_SNET)
elif switch_result == "enablePort":
time.sleep(5)
enablePort_SNET(ssh_SNET)
elif switch_result == "disablePort":
disablePort_SNET(ssh_SNET)
elif switch_result == "switchReboot":
reboot_SNET_switch(ssh_SNET)
else:
print("Exiting program now....")
sys.exit(-1)
Here are relevant issues:
user_input = raw_input("Make your selection") # This does not work if I change to input(), it exits out of the program
deviceIP = input("Enter the IP address for this device") # I tried changing these to raw_input, I get a syntax issue
deviceUsername = input("Enter the username for this device")
devicePassword = input("Enter the password for this device")
confirm_ping = canPing(deviceIP) # This is a boolean function that works correctly in every script but this one.
Conclusion ? There is an issue with input()/raw_input() . What is going on here and how can I fix this ? I can't use python 3.7 and it really is frustrating. Thanks for the help
Try changing if user_input == 1: to if int(user_input) == 1: as the input function takes an input in string format, by default.
And, if you want to use input() instead of raw_input() to take input from users in python 2.x, then you can try below code:
if hasattr(__builtins__, 'raw_input'):
input=raw_input
user_input = input("Enter a number: ")

Python: Telnetlib only commands without a space

I have some problems with the python libary telnetlib. Login works. Enable, ? and Exit works. But all commands with an space doesn't work.
import getpass
import sys
import telnetlib
HOST = "10.159.123.91"
user = "1234"
command = "show version"
tn = telnetlib.Telnet(HOST)
tn.read_until("Password: ")
tn.write(user + "\n")
tn.write("enable\n")
tn.write("5678\n")
tn.write("?\n")
tn.write("exit\n")
print tn.read_all()
tn.close()
This one is working. If I replace tn.write("?\n") with tn.write("show version\n") nothing happen.
Does anyone have any idea where my problem is?
I found an solution. I'm not sure if it is an good and clean solution. But it works. I add behind the command an sleep for 2 seconds.
import getpass
import sys
import time
import telnetlib
HOST = "10.159.123.91"
user = "1234"
command = "show version"
tn = telnetlib.Telnet(HOST)
tn.read_until("Password: ")
tn.write(user + "\n")
tn.write("enable\n")
tn.write("5678\n")
tn.write("show ip interface brief\n")
time.sleep(2)
tn.write("exit\n")
print tn.read_all()
tn.close()

Controlling VLC via telnet with python script

So I have this script I can't get working. I have verified it's the script, as I can cmd->telnet to localhost 4212 and are able to change vlc there(like next and stop).
But the script doesn't give any errors either. I have python installed:
#!/usr/bin/python
import sys
import telnetlib
cmd = " ".join(sys.argv[1:])
tn = telnetlib.Telnet("localhost", 4212)
tn.read_until("Password: ")
tn.write("admin\n")
tn.read_until("> ")
tn.write(cmd + "\n")
tn.close()

input hidden string via sys.argv in python

I need to input the password via the command line and use it in the program via sys.argv[2].
The problem with CLI is that the password is displayed in clear text.
Below is the code :
import sys
user_args = sys.argv[1:]
username, password = user_args
print username
print password
Take a look :
You can use the getpass module (https://docs.python.org/3.5/library/getpass.html)
import getpass
password = getpass.getpass('Enter password: ')

telnetlib python example

So I'm trying this really simple example given by the python docs:
import getpass
import sys
import telnetlib
HOST = "<HOST_IP>"
user = raw_input("Enter your remote account: ")
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("ls\n")
tn.write("exit\n")
print tn.read_all()
My issue is that it hangs at the end of the read_all()... It doesn't print anything out. I've never used this module before so I'm trying to get this really basic example to work before continuing. BTW, I'm using python 2.4
Thank you.
Okay, I found a solution. Before I entered ls and exit, I needed to first specify the terminal type. Adding
tn.write("vt100\n")
before the "ls" fixed the problem for me.
If you're using Windows, be sure to add carriage return (\r) before the new line character:
tn.write(user.encode('ascii') + "\r\n".encode('ascii'))
I know this is late to post but may help others. I also struggled to get this right but here is my piece of code. My telnet would follow certain flow like it would ask for loginID and then Password and then you have to wait for a particular string to be displayed here,which for my case was "DB>" then you can proceed with the command and all. My output would be saved in "out" varible
import os,re,telnetlib
host = "10.xxx.xxx.xxx"
port = 23
telnet = telnetlib.Telnet()
telnet.open(host, port)
telnet.write('loginID\r\n')
telnet.write('Password\r\n')
out = telnet.read_until("DB>", 5)
telnet.write('show cable modem reg\r\n') #Mycommand
out = telnet.read_until("DB>", 5)
telnet.write('quit\r\n')
telnet.close()
For more variations and help, Check the website nullege
I don't have a telnet server to test against, but I think the issue is that you are not reading server responses up to the prompt, after each command you write.
PROMPT = ':~$'
tn = telnetlib.Telnet(HOST)
tn.read_until('login: ')
tn.write(user + '\n')
if password:
tn.read_until('Password: ')
tn.write(password + '\n')
tn.read_until(PROMPT)
tn.write('ls\n')
print tn.read_until(PROMPT)
tn.write('exit\n')
btw, telnetnetlib can be tricky and things varies depending on your FTP server and environment setup. you might be better off looking into something like pexpect to automate login and user interaction over telnet.
I struggled for a while trying to write to a SynAccess power strip. This is how I did it:
import sys
import telnetlib
HOST = < your SynAccess switch ip address >
user = < user name >
password = < password >
tn = telnetlib.Telnet(HOST, 23, 5)
tn.write("login\r\n")
tn.write(user + "\r\n")
tn.write(password + "\r\n")
tn.write("rb 3\r\n") # this reboots plug 3
tn.write("rb 1\r\n") # this reboots plug 1
tn.write("logout\r\n")
tn.close
use python 2.7 or use a higher version with"(" ,")" at last line
If none of these answers worked, you can also try:
tn.read_until(b"Password: ")
tn.write(password.encode('utf-8') + b"\n")
tn.read_until(b"Terminal type?", 5)
tn.write("vt100\n".encode('utf-8'))
tn.read_until(b">", 5)
Even though I never saw the actual request for the terminal type being printed, this write seemed to work.

Categories