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()
Related
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
This question already has an answer here:
Executing command using "su -l" in SSH using Python
(1 answer)
Closed 1 year ago.
I am trying to make script to ssh my device with r/o user and then super user and execute a command.Below are the steps i did on my putty
login as admin ( r/o user) and password.
sudo su and than password
execute a command
print output of executed command
i tried below code to make it working but i didn't get any output.
import paramiko
import pandas as pd
import openpyxl
from paramiko import AuthenticationException
from paramiko.ssh_exception import SSHException, NoValidConnectionsError
import socket
import time
import os
import inspect
import datetime
start = time.time()
print("Starting................................Please Wait")
df=pd.DataFrame(columns=["ip","Status","Remarks"])
ips = ['10.11.8.71']
root = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
#ips = open (root+ "/440_ip.txt")
for ipp in ips:
ip = ipp.strip()
port=22
username='admin'
#password='AeGEBUx66m_1ND'
#cmd='interface wireless set [ find default-name=wlan1 ] ampdu-priorities=0,1,2,3,4,5,6,7 rate-set=configured rx-chains=0,1 scan-list=5825-5875 security-profile=iB440 ssid=iBw supported-rates-a/g="" basic-rates-a/g=""'
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,timeout=5,password='HeWGEUx66m=_4!ND')
stdin, stdout, stderr = ssh.exec_command('sudo bash', get_pty = True)
time.sleep(0.1)
stdin.write('HeWGEUx66m=_4!ND\n')
stdin.flush()
stdin.write('whoami\n')
#time.sleep(1)
stdin.flush()
dd = stdout.readlines()
print(dd)
ssh.close()
After running the code there is no error, seems it stuck in some loop.,
Starting................................Please Wait
Using ssh with plink in single line command
C:\Users\Administrator\AppData\Local\Programs\Python\Python38>plink.exe -ssh -t admin#10.11.8.71 sudo bash admin#10.11.8.71's password: Access granted. Press Return to begin session. Password: bash-3.2# whoami root bash-3.2#```
To make it working properl i used channels from paramiko, and it worked like charm.
import paramiko
from paramiko import *
from paramiko.channel import Channel
import time
import os
import inspect
import datetime
from socket import *
import pandas as pd
df = pd.DataFrame(columns=["Ip","Status",'Remarks'])
root = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
#ips = ['10.23.0.30', '10.23.0.11','10.23.0.12','10.23.0.13']
ips = open(root+ "\\ahip.txt")
for ipp in ips:
ip = ipp.strip()
print(ip)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(ip, port=22,timeout = 5,username='op', password='C#Uj!AnX')
channel:Channel = ssh.invoke_shell()
#print(type(channel))
channel_data = str()
while True:
#channel.recv_ready():
#time.sleep(1)
channel_data += str(channel.recv(999))
channel.send("su -\n")
time.sleep(1)
#channel_data += str(channel.recv(999))
# if "Password" in channel_data:
channel.send("HeWGEUx\n")
time.sleep(3)
#channel_data += str(channel.recv(999))
channel.send("/bs/lteCli\n")
time.sleep(3)
channel.send("logger threshold set cli=6\n")
time.sleep(4)
channel.send("db set stackCfg [1] EnCLPC=0\n")
time.sleep(4)
channel.send("db get stackCfg EnCLPC\n")
time.sleep(3)
#channel.send("db get stackCfg EnCLPC\n")
time.sleep(.1)
channel_data += str(channel.recv(99999))
str2 = 'Done'
df.loc[ip]=[ip,str2,channel_data]
#print(channel_data)
channel.close()
ssh.close()
break
except (timeout ,AuthenticationException):
print(ip+'not done')
str1 = 'Not Done'
df.loc[ip]=[ip,'failed',str1]
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()
import getpass
import sys
import telnetlib
tn = telnetlib.Telnet("xxxxxxxx")
tn.write("xxxxxx" + "\n")
tn.write("xxxxxx" + "\n")
tn.write("show version\n")
tn.write("exit\n")
print tn.read_all()
Trying to telnet to a router and the script is hanging.... Not sure whats up. Have tried a debug but cant make head or toe of the output.
telnetlib.py(511): if self.irawq >= len(self.rawq):
telnetlib.py(512): self.rawq = ''
telnetlib.py(513): self.irawq = 0
telnetlib.py(516): buf = self.sock.recv(50)
This is where it hangs in the debug.
Thanks
William
I can answer this one. Managed to get it fixed.
The python script was going off the rails when the router asked for user input to see more information on the command.
So when i asked for a "show version" it would give out a lot of information onto the command line and then ask you hit space to see more.
To solve this the first command i execute is "term len 0". Stops it asking for any user input and just fires it all out at once.
below is the final script. Changed quite a bit but its works.
import sys
import telnetlib
tn = telnetlib.Telnet("xxxxxxxx")
TELNET_PROMPT="xxxxxxxxxx"
TIMEOUT=1
tn.write("xxxxxxx"+"\n")
tn.write("xxxxxxx"+"\n")
print tn.read_until(TELNET_PROMPT, TIMEOUT)
tn.write("term len 0" + "\n")
print tn.read_until(TELNET_PROMPT, TIMEOUT)
tn.write("show version" + "\n")
print tn.read_until(TELNET_PROMPT, TIMEOUT)
tn.write("exit"+"\n")
tn.close()
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.