Errors when connecting to router with python code - python

I am trying to connect to some router using the above code and I am using juniperj2320.py module and in test file I have
am using code base from this http://subversion.assembla.com/svn/clauzsistel08/trunk/dist/
#!/usr/bin/python
from localconf import *
from juniperj2320 import *
import sys
import traceback
SERIALDEVICE = '/dev/ttyUSB0'
# Now configure the router
try:
router = JuniperJ2320(SERIALDEVICE)
except RouterConfigurationException, err:
print "Router configuration error: ", err
print "Please try again."
sys.exit(1)
but am getting this following error
./test.py
> /root/pyserial-2.6/examples/serialrouter.py(37)__init__()
-> serial.Serial.__init__(self, serialdevice, baudrate=baudrate, \
(Pdb) c
Traceback (most recent call last):
File "./test.py", line 30, in
router = JuniperJ2320(SERIALDEVICE)
File "/root/pyserial-2.6/examples/juniperj2320.py", line 32, in __init__
BYTESIZE, PARITY, STOPBITS, TIMEOUT)
File "/root/pyserial-2.6/examples/serialrouter.py", line 44, in __init__
fdpexpect.fdspawn.__init__(self, self.fileno())
File "/usr/lib/python2.6/site-packages/fdpexpect.py", line 40, in __init__
spawn.__init__(self, None, args, timeout, maxread, searchwindowsize, logfile )
File "/usr/lib/python2.6/site-packages/pexpect.py", line 412, in __init__
self.closed = True # File-like object.
AttributeError: can't set attribute
and absolutely clue less on wat happening here ! any help ll be greatly appreciated
thanks

This is a little bit of a shot in the dark, because I'm not familiar with the modules you're using, but based on the traceback, it looks like the constructor is expecting a file-like object, not just a file path. Try this instead.
SERIALDEVICE = '/dev/ttyUSB0'
# Now configure the router
try:
router = JuniperJ2320(open(SERIALDEVICE))

Instead of writing your own serial communications program wouldn't be easier to have pexpect drive a serial program like minicom?

Related

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.

Twisted HTTPS Client

I am currently having some trouble accessing content hosted via https using the twisted python library. I am new to this library, and am assuming there is some concept I am missing that's causing the issue, but perhaps not based upon the example.
Here is a link to the page in which I gathered the example:
https://twistedmatrix.com/documents/current/web/howto/client.html
Under the heading HTTP over SSL
from twisted.python.log import err
from twisted.web.client import Agent
from twisted.internet import reactor
from twisted.internet.ssl import optionsForClientTLS
def display(response):
print("Received response")
print(response)
def main():
contextFactory = optionsForClientTLS(u"https://example.com/")
agent = Agent(reactor, contextFactory)
d = agent.request("GET", "https://example.com/")
d.addCallbacks(display, err)
d.addCallback(lambda ignored: reactor.stop())
reactor.run()
if __name__ == "__main__":
main()
When running this code, it straight up fails. I get an error that looks like this:
Traceback (most recent call last):
File "https.py", line 19, in <module>
main()
File "https.py", line 11, in main
contextFactory = optionsForClientTLS(u"https://example.com/")
File "/home/amaricich/.local/lib/python2.7/site-packages/twisted/internet/_sslverify.py", line 1336, in optionsForClientTLS
return ClientTLSOptions(hostname, certificateOptions.getContext())
File "/home/amaricich/.local/lib/python2.7/site-packages/twisted/internet/_sslverify.py", line 1198, in __init__
self._hostnameBytes = _idnaBytes(hostname)
File "/home/amaricich/.local/lib/python2.7/site-packages/twisted/internet/_sslverify.py", line 86, in _idnaBytes
return idna.encode(text)
File "/usr/local/lib/python2.7/dist-packages/idna/core.py", line 355, in encode
result.append(alabel(label))
File "/usr/local/lib/python2.7/dist-packages/idna/core.py", line 276, in alabel
check_label(label)
File "/usr/local/lib/python2.7/dist-packages/idna/core.py", line 253, in check_label
raise InvalidCodepoint('Codepoint {0} at position {1} of {2} not allowed'.format(_unot(cp_value), pos+1, repr(label)))
idna.core.InvalidCodepoint: Codepoint U+003A at position 6 of u'https://example' not allowed
This error lead me to believe the parameter being passed into optionsForClientTLS were incorrect. It calls for a hostname and not a full url, so I shortened the parameter to simply example.com. Once that change was made, the function completed successfully.
Unfortunately though, after making the change, the script now failed at the line invoking agent.request. The error it supplied was this:
Traceback (most recent call last):
File "https.py", line 19, in <module>
main()
File "https.py", line 13, in main
d = agent.request("GET", "https://example.com/")
File "/home/amaricich/.local/lib/python2.7/site-packages/twisted/web/client.py", line 1596, in request
endpoint = self._getEndpoint(parsedURI)
File "/home/amaricich/.local/lib/python2.7/site-packages/twisted/web/client.py", line 1580, in _getEndpoint
return self._endpointFactory.endpointForURI(uri)
File "/home/amaricich/.local/lib/python2.7/site-packages/twisted/web/client.py", line 1456, in endpointForURI
uri.port)
File "/home/amaricich/.local/lib/python2.7/site-packages/twisted/web/client.py", line 982, in creatorForNetloc
context = self._webContextFactory.getContext(hostname, port)
AttributeError: 'ClientTLSOptions' object has no attribute 'getContext'
This error leads me to believe that the object being produced by optionsForClientTLS is not the object type that is expected to be passed into the Agent upon creation. A function is trying to be invoked that does not exist. With all that said, I have two questions.
Is this example deprecated? The previous examples that make http requests all work like a charm. Am I doing something wrong, or is the example no longer valid?
I am only looking for a simple way to retrieve data from a server using HTTPS. If doing things this way is not the solution, is anyone familiar with how HTTPS requests can be made using twisted?
Yes you're absolutely correct that the example on the docs is wrong. I noticed the bug while working w/ treq. Try following this example from v14. With that being said, you should use treq as opposed to trying to use Twisted directly. Most of the heavy lifting has been taken care of for you. Here's an simple conversion of your example:
from __future__ import print_function
import treq
from twisted.internet import defer, task
from twisted.python.log import err
#defer.inlineCallbacks
def display(response):
content = yield treq.content(response)
print('Content: {0}'.format(content))
def main(reactor):
d = treq.get('https://twistedmatrix.com')
d.addCallback(display)
d.addErrback(err)
return d
task.react(main)
As you can see treq takes care of the SSL stuff for you. The display() callback function can be used to extract various components of the HTTP response, such as headers, status codes, body, etc. If you only need a single component, such as the response body, then you can simplify further like so:
def main(reactor):
d = treq.get('https://twistedmatrix.com')
d.addCallback(treq.content) # get response content when available
d.addErrback(err)
d.addCallback(print)
return d
task.react(main)

dbm 35 Resource temporarily unavailable on OSX python 2.7

I am using the Flask-WeRobot plugin and I am seeing an error being thrown here:
class FileStorage(SessionStorage):
"""
FileStorage 会把你的 Session 数据以 dbm 形式储存在文件中。
:param filename: 文件名, 默认为 ``werobot_session``
"""
def __init__(self, filename='werobot_session'):
print filename
try:
self.db = dbm.open(filename, "c")
except Exception, e:
print e
raise e
This is what is being outputted:
Traceback (most recent call last):
File "application.py", line 18, in <module>
another_robot = WeRoBot(token='abcdefg', enable_session=True)
File "/Users/vng/Dropbox/Code/Paw/venv/lib/python2.7/site-packages/flask_werobot.py", line 42, in __init__
super(WeRoBot, self).__init__(*args, **kwargs)
File "/Users/vng/Dropbox/Code/Paw/venv/lib/python2.7/site-packages/werobot/robot.py", line 47, in __init__
filename=os.path.abspath("werobot_session")
File "/Users/vng/Dropbox/Code/Paw/venv/lib/python2.7/site-packages/werobot/session/filestorage.py", line 20, in __init__
self.db = dbm.open(filename, "c")
File "/usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/anydbm.py", line 85, in open
return mod.open(file, flag, mode)
gdbm.error: (35, 'Resource temporarily unavailable')
At first I thought it would have something to do with permissions, but changing the file, werobot_session didn't work.
I am on OSX running python 2.7. This code works on my ubuntu production server.
Any ideas what's causing this?
We find this bug too and we are working on it now.
It seems that it's a bug of gdbm. And everything works fine on linux.
You can check this issue for further information.
https://github.com/whtsky/WeRoBot/issues/102

ladon throwing an AttributeError

I'm trying to get ladon working, however, I don't seem to be able to define the service properly.
Specifically, even with a minimal test case, it's throwing
Traceback (most recent call last):
File "C:\Python33\lib\site-packages\ladon\server\wsgi_application.py", line 332, in __call__
self.import_services(self.service_list)
File "C:\Python33\lib\site-packages\ladon\server\wsgi_application.py", line 288, in import_services
__import__(service)
File "D:\Workspaces\Python\SOAPManager.py", line 20, in <module>
#ladonize(PORTABLE_STRING, PORTABLE_STRING, rtype=PORTABLE_STRING)
File "C:\Python33\lib\site-packages\ladon\ladonizer\decorator.py", line 118, in decorator
injector.__doc__ = ladon_method_info._doc
AttributeError: 'NoneType' object has no attribute '_doc'
My Run.py contains:
from ladon.server.wsgi import LadonWSGIApplication
from os.path import abspath, dirname
from wsgiref.simple_server import make_server
application = LadonWSGIApplication(
['SOAPManager'],
[dirname(abspath(__file__))],
catalog_name='API',
catalog_desc='API Description')
httpd = make_server('0.0.0.0', 8004, application)
print("Listening on port 8004...")
# Respond to requests until process is killed
httpd.serve_forever()
And the minimal test case in SOAPManager.py:
from ladon.ladonizer import ladonize
from ladon.types.ladontype import LadonType
from ladon.compat import PORTABLE_STRING
#ladonize(PORTABLE_STRING, PORTABLE_STRING, rtype=PORTABLE_STRING)
def Authenticate(Username, Password):
return "Test"
The error is being raised from within the ladonize decorator. It seems to be occuring when trying to build up the definition of the service. Specifically, in ladon the decorator calls collection.add_service_method which returns None instead of a method. I think it's failing a line-number check.
firstlineno = f.__code__.co_firstlineno
# get an ast-analyzed object of the source file
sinfo = self.source_info(src_fname)
...
for clsname,v in sinfo.items():
if firstlineno>v[0] and firstlineno<=v[1]:
For some reason that check is failing so the method defaults to returning None.

how to use pywhois module in gae

I have problems when try to import pywhois module, i can import my own module but still have troubles when import pywhois. I moved the pywhois folder in my project folder domain, the screentshot is below:
This is the import and calling statment below:
import part:
from pywhois import *
calling part:
w = whois('hackbo.com')
self.response.out.write(w)
The problems is it will always throw a http 500 error, error text is below:
Traceback (most recent call last):
File "/home/li/Desktop/google_appengine/google/appengine/ext/webapp/__init__.py", line 700, in __call__
handler.get(*groups)
File "/home/li/Desktop/google_appengine/domain/main.py", line 43, in get
w = whois('hackbo.com')
File "pywhois/__init__.py", line 12, in whois
text = nic_client.whois_lookup(None, domain, 0)
File "pywhois/whois.py", line 157, in whois_lookup
result = self.whois(query_arg, nichost, flags)
File "pywhois/whois.py", line 100, in whois
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
AttributeError: 'module' object has no attribute 'socket'
What is this error means? why i could import my own module but can not import pywhois?
Google App Engine doesn't support the socket module, which pywhois uses. It allows you to import socket, but it's an empty module.
import whois
site = input ("Enter Site : ")
n = whois.whois (site)
print (n)
this is best whois
Enjoy that, easy.

Categories

Resources