How to read telnet sessions with python - python

Aloha, i'm creating a teamspeakbot and want to write and read to a telnet session created with a TeamSpeak3 server
import telnetlib
tn = telnetlib.Telnet('localhost', 10011, 10)
tn.read_all()
What i'm expecting:
Connected to localhost
Escape character is '^]'.
TS3
Welcome to the TeamSpeak 3 ServerQuery interface, type "help" for a li...
But instead i get a time out after the 10 seconds:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/telnetlib.py", line 325, in read_all
self.fill_rawq()
File "/usr/lib/python2.7/telnetlib.py", line 516, in fill_rawq
buf = self.sock.recv(50)
socket.timeout: timed out
How can i read all stuff the telnet connection tells me and later write some stuff to it (like the login proces and submit commands and get the response ...)
The Solution is
tn.read_very_eager()
My code now looks like this:
import telnetlib, time
tn = telnetlib.Telnet('localhost', 10011, 10)
tn.write('help\n')
time.sleep(0.05)
print(tn.read_very_eager())

read_all() blocks until EOF is reached*, or until your timeout is reached. While I've not used telnetlib much, I have assumed it's for the sort of service which displays something then closes the connection.
How do you get on with code like:
tn = telnetlib.Telnet('localhost', 10011, 10)
tn.read_some()
*https://docs.python.org/2/library/telnetlib.html#telnetlib.Telnet.read_all

Related

getting OSError -202 where running urequests.get from micropy

hi im having error with this code but it runs in python shell could any body help me
from machine import Pin
import time
import network
import urequests
p0 = Pin(0,Pin.OUT)
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect('ssid', 'pass')
response = urequests.get('http://jsonplaceholder.typicode.com/albums/1')
while True:
ans = response.json()['userId']
p0.value(1)
time.sleep(1)
p0.off()
time.sleep(1)
print('ok')
and this is the error:
Traceback (most recent call last):
File "<stdin>", line 9, in <module>
File "urequests.py", line 108, in get
File "urequests.py", line 53, in request
OSError: -202
Your issue (my guess) is that you begin to urequest.get() without connected to WiFi. Create function that do wifi connection and call it
def do_connect():
import network
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('connecting to network...')
wlan.connect('essid', 'password')
while not wlan.isconnected():
pass
print('network config:', wlan.ifconfig())
Explain: wlan.connect() is asynchronous function and you have to wait, while it connects to wifi and only then continue with urequest.get()

EFOError when trying to connect Pyftpsync to remote server on port 22

I am trying to sync two folders via FTP, yes I know there are better or different ways but for now I need to implement it this way, I was trying the example code from pyftpsync since well, a sample code should work easily right? I am just trying to connect between some test folders I made, one is empty(local) and the remote has a single text file that I want to fetch. It tries to connect but after about 2 minutes I get this error.
Well, my FTP does work outside of python. I can connect over WinSCP just fine.
Some places mentioned that a proxy could possibly cause this, but it seems I am not behind a proxy currently, but maybe I did not set that properly and it believes there should be a proxy somehow?
Here is my code, just using commands on the prompt for pyftpsync produces the same errors for me. So it is possible some input parameter is off causing all of this.
import time
import os
import re
import shutil
import string
import sys
from ftpsync.targets import FsTarget
from ftpsync.ftp_target import FtpTarget
from ftpsync.synchronizers import DownloadSynchronizer
#synchronize a local folder with ftp
local = FsTarget( "C:\\testfolder\\" )
user = "login"
passwd = "password"
remote = FtpTarget("/my/folder/location/testfold/", "126.0.0.1",port=22, username=user,password=passwd,tls=False,timeout=None,extra_opts=None)
opts = {}
s=DownloadSynchronizer(local, remote, opts)
s.run()
This is the output I am getting, I have edited out the folder names and IP addresses.
INFO:keyring.backend:Loading KWallet
INFO:keyring.backend:Loading SecretService
INFO:keyring.backend:Loading Windows
INFO:keyring.backend:Loading chainer
INFO:keyring.backend:Loading macOS
INFO:pyftpsync:Download to C:\testfolder
from ftp://126.0.0.1/.../testfold
INFO:pyftpsync:Encoding local: utf-8, remote: utf-8
Traceback (most recent call last):
File "c:\..\.py", line 30, in <module>
s.run()
File "C:\\AppData\Local\Programs\Python\Python37-32\lib\site-
packages\ftpsync\synchronizers.py", line 1268, in run
res = super(DownloadSynchronizer, self).run()
File "C:\\AppData\Local\Programs\Python\Python37-
32\lib\site-packages\ftpsync\synchronizers.py", line 827, in run
res = super(BiDirSynchronizer, self).run()
File "C:\\AppData\Local\Programs\Python\Python37-
32\lib\site-packages\ftpsync\synchronizers.py", line 211, in run
self.remote.open()
File "C:\\AppData\Local\Programs\Python\Python37-
32\lib\site-packages\ftpsync\ftp_target.py", line 141, in open
self.ftp.connect(self.host, self.port)
File "C:\\AppData\Local\Programs\Python\Python37-
32\lib\ftplib.py", line 155, in connect
self.welcome = self.getresp()
File "C:\\Local\Programs\Python\Python37-
32\lib\ftplib.py", line 236, in getresp
resp = self.getmultiline()
File "C:\\AppData\Local\Programs\Python\Python37-
32\lib\ftplib.py", line 226, in getmultiline
nextline = self.getline()
File "C:\\AppData\Local\Programs\Python\Python37-
32\lib\ftplib.py", line 210, in getline
raise EOFError
EOFError
Anyways any possible troubleshooting ideas would help. Thank you.
Pyftpsync uses FTP protocol.
You are connecting to port 22, which is used for SSH/SFTP.
So if your server is actually SFTP server, not FTP server, you cannot use Pyftpsync with it.

I get an error of traceback (most recent call last) when I try to run this Python program. I want to know the solution to this

This is a Python program to receive the data from an XBee module using the python-xBee library. I have installed both the xbee and pyserial modules.
import serial
from xbee import XBee
serial_port = serial.Serial('/dev/ttyUSB0', 9600)
xbee = XBee(serial_port)
while True:
try:
print xbee.wait_read_frame()
except KeyboardInterrupt:
break
serial_port.close()
But when I run this and any kind of program with serial port, this is the error I am getting:
Traceback (most recent call last):
File "C:/Users/Manurajeev/PycharmProjects/untitled/one.py", line 4, in
<module>
serial_port = serial.Serial('/dev/ttyUSB0', 9600)
File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 31, in
__init__
super(Serial, self).__init__(*args, **kwargs)
File "C:\Python27\lib\site-packages\serial\serialutil.py", line 240, in
__init__
self.open()
File "C:\Python27\lib\site-packages\serial\serialwin32.py", line 62, in
open
raise SerialException("could not open port {!r}:
{!r}".format(self.portstr, ctypes.WinError()))
serial.serialutil.SerialException: could not open port '/dev/ttyUSB0':
WindowsError(3, 'The system cannot find the path specified.')
Process finished with exit code 1
I don't understand what the problem is. I tried everything, but the same error keeps popping up every time.
In Linux, check the permissions on the tty device (ls -l /dev/ttyUSB0) to ensure that you have read/write access to it. Note that it might have a different name.
For Windows, have you been able to open COM5 with a terminal emulator and send/receive data on the XBee? Do you still have it open in another program when you're trying to open it in Python? Only one program can access a COM port at a time.

Timeout error with PyVISA -- communicating with Agilent 34970A throug RS232 (USB)

This is my first time i try to use Pyvisa, in order to communicate with an Agilent 34970A, using a RS232 connection(using an USB port).
This is what's happening to me, inserting the basic first lines:
IN: import visa
IN: rm=visa.ResourceManager()
IN: print rm.list_resources()
(u'ASRL4::INSTR',)
IN: inst=rm.open_resource("ASRL4::INSTR")
IN: print inst.query("*IDN?")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Anaconda2\lib\site-packages\pyvisa-1.8-py2.7.egg\pyvisa\resources\messagebased.py", line 407, in query
return self.read()
File "C:\Anaconda2\lib\site-packages\pyvisa-1.8-py2.7.egg\pyvisa\resources\messagebased.py", line 332, in read
message = self.read_raw().decode(enco)
File "C:\Anaconda2\lib\site-packages\pyvisa-1.8-py2.7.egg\pyvisa\resources\messagebased.py", line 306, in read_raw
chunk, status = self.visalib.read(self.session, size)
File "C:\Anaconda2\lib\site-packages\pyvisa-1.8-py2.7.egg\pyvisa\ctwrapper\functions.py", line 1582, in read
ret = library.viRead(session, buffer, count, byref(return_count))
File "C:\Anaconda2\lib\site-packages\pyvisa-1.8-py2.7.egg\pyvisa\ctwrapper\highlevel.py", line 188, in _return_handler
raise errors.VisaIOError(ret_value)
pyvisa.errors.VisaIOError: VI_ERROR_TMO (-1073807339): Timeout expired before operation completed.
This timeout error happens everytime i try to read a value. I imposed also a larger timeout but nothing, i waited some minutes in vain. Any idea for this problem?
You need to match up your baud rate. Either on your 34970A or in the attributes of pyVisa.
The default that comes with visa is 9600.
https://buildmedia.readthedocs.org/media/pdf/pyvisa/master/pyvisa.pdf
here's an example if you wanted to change it to 115200, the highest baud on the 34970A.
inst = rm.open_resource('ASRL4::INSTR')
inst.baud_rate = 115200
Try changing the RS232 setting protocol to be XON/XOFF.

Exscript TimeoutException

So I finally got exscript working properly (I think). I wanted to test it, so I setup a simple python script I believe should work:
from Exscript.util.interact import read_login
from Exscript.protocols import SSH2
account = read_login()
conn = SSH2()
conn.connect('router.domain.com')
conn.login(account)
conn.execute('terminal length 0')
conn.execute('show version')
print conn.response
conn.send('exit\r')
conn.close()
I run the script and I'm presented with the following:
kidd#server scripts$ python test1.py
Please enter your user name [kidd]:
Please enter your password:
It sits there for about 20 seconds, then I get this:
Traceback (most recent call last):
File "test1.py", line 7, in <module>
conn.login(account)
File "/usr/lib/python2.7/site-packages/Exscript/protocols/Protocol.py", line 597, in login
self.auto_app_authorize(app_account, flush = flush)
File "/usr/lib/python2.7/site-packages/Exscript/protocols/Protocol.py", line 846, in auto_app_authorize
self.get_driver().auto_authorize(self, account, flush, bailout)
File "/usr/lib/python2.7/site-packages/Exscript/protocols/drivers/one_os.py", line 43, in auto_authorize
conn.app_authorize(account, flush, bailout)
File "/usr/lib/python2.7/site-packages/Exscript/protocols/Protocol.py", line 820, in app_authorize
self._app_authenticate(account, password, flush, bailout)
File "/usr/lib/python2.7/site-packages/Exscript/protocols/Protocol.py", line 690, in _app_authenticate
raise TimeoutException(msg)
Exscript.protocols.Exception.TimeoutException: Buffer: '\rThis is a private system \r\n \r\nrouter>'
Am I missing something simple? Just trying to login to a router (as a normal user, non-privilege mode), run a show version, then log out. Any help would be appreciated. Thanks.
It looks like the banner you have configured is messing with the prompt that Exscript is expecting back from the device. I'd suggest either tweaking the protocol driver within Exscript to handle the prompt better, or making sure your banner is set up properly (or removing it all together)

Categories

Resources