pxssh.pxssh() is producing error in python - python-2.7

I got the following errors when I run pxssh.pxssh() in python. Please let me know what I am missing here.
Exception AttributeError: "'pxssh' object has no attribute 'closed'" in <bound method pxssh.__del__ of <pexpect.pxssh.pxssh object at 0x10d98e910>> ignored
.........
File "/Users/any_user/system/somelibrary_lib.py", line 377, in login
ssh = pxssh.pxssh(maxread=read_buffer, ignore_sighup=False)
TypeError: __init__() got an unexpected keyword argument 'ignore_sighup'
.........

I faced the same problem. the solution was like this :
s = pxssh.pxssh(timeout=time_out, maxread=2000000)
s.SSH_OPTS += " -o StrictHostKeyChecking=no"
s.SSH_OPTS += " -o UserKnownHostsFile=/dev/null"
You should add this two options

I faced the same problem. Solution I found was to use SSH_OPTS property of pxssh object instead of options ctor (__init__) argument.
So my code looks like this:
s = pxssh.pxssh()
s.SSH_OPTS += " -o StrictHostKeyChecking=no"
s.force_password = True
s.login(ip, user, passwd)
It doesn't throw AttributeError exception on module initialization and TypeError too.
But it still doesn't work for me. If the remote server has MOTD or some shell initialization on startup, it would break the logic of pxssh. I made the following trick:
s.login(ip, user, passwd, original_prompt = "Last login:")
Shell writes on each successful login line like Last login: %date% from %ip%. I used it to verify successful logon. Now, using s you can execute remote commands.
Original (default) value for original_prompt is r"[#$]". May be you need somehow to combine them for correct pxssh work. May be you need to add > to original_prompt if you are connecting to SQL shell or Cisco devices.

Related

Setting Spotify credentials using Spotipy

I am trying out spotipy with python 2.7.10 preinstalled on my mac 10.10, specifically [add_a_saved_track.py][1] Here is the code as copied from github:
# Add tracks to 'Your Collection' of saved tracks
import pprint
import sys
import spotipy
import spotipy.util as util
scope = 'user-library-modify'
if len(sys.argv) > 2:
username = sys.argv[1]
tids = sys.argv[2:]
else:
print("Usage: %s username track-id ..." % (sys.argv[0],))
sys.exit()
token = util.prompt_for_user_token(username, scope)
if token:
sp = spotipy.Spotify(auth=token)
sp.trace = False
results = sp.current_user_saved_tracks_add(tracks=tids)
pprint.pprint(results)
else:
print("Can't get token for", username)
I registered the application with developer.spotify.com/my-applications and received client_id and client_secret. I am a bit unclear about selection of redirect_uri so I set that to 'https://play.spotify.com/collection/songs'
Running this from terminal I get an error that says:
You need to set your Spotify API credentials. You can do this by
setting environment variables like so:
export SPOTIPY_CLIENT_ID='your-spotify-client-id'
export SPOTIPY_CLIENT_SECRET='your-spotify-client-secret'
export SPOTIPY_REDIRECT_URI='your-app-redirect-url'
I put that into my code with the id, secret, and url as strings, just following the imports but above the util.prompt_for_user_token method.
That caused a traceback:
File "add-track.py", line 8
export SPOTIPY_CLIENT_ID='4f...6'
^
SyntaxError: invalid syntax
I noticed that Text Wrangler does not recognize 'export' as a special word. And I searched docs.python.org for 'export' and came up with nothing helpful. What is export? How am I using it incorrectly?
I next tried passing the client_id, client_secret, and redirect_uri as arguments in the util.prompt_for_user_token method like so:
util.prompt_for_user_token(username,scope,client_id='4f...6',client_secret='xxx...123',redirect_uri='https://play.spotify.com/collection/songs')
When I tried that, this is what happens in terminal:
User authentication requires interaction with your
web browser. Once you enter your credentials and
give authorization, you will be redirected to
a url. Paste that url you were directed to to
complete the authorization.
Opening https://accounts.spotify.com/authorize?scope=user-library-modify&redirect_uri=https%3A%2F%2Fplay.spotify.com%2Fcollection%2Fsongs&response_type=code&client_id=4f...6 in your browser
Enter the URL you were redirected to:
I entered https://play.spotify.com/collection/songs and then got this traceback:
Traceback (most recent call last):
File "add-track.py", line 21, in <module>
token = util.prompt_for_user_token(username, scope, client_id='4f...6', client_secret='xxx...123', redirect_uri='https://play.spotify.com/collection/songs')
File "/Library/Python/2.7/site-packages/spotipy/util.py", line 86, in prompt_for_user_token
token_info = sp_oauth.get_access_token(code)
File "/Library/Python/2.7/site-packages/spotipy/oauth2.py", line 210, in get_access_token
raise SpotifyOauthError(response.reason)
spotipy.oauth2.SpotifyOauthError: Bad Request
It seems like I am missing something, perhaps another part of Spotipy needs to be imported, or some other python module. It seems I am missing the piece that sets client credentials. How do I do that? I am fairly new at this (if that wasn't obvious). Please help.
UPDATE: I changed redirect_uri to localhost:8888/callback. That causes a Firefox tab to open with an error -- "unable to connect to server." (Since I do not have a server running. I thought about installing node.js as in the Spotify Web API tutorial, but I have not yet). The python script then asks me to copy and paste the URL I was redirected to. Even though FF could not open a page, I got this to work by copying the entire URL including the "code=BG..." that follows localhost:8888/callback? I am not sure this is an ideal setup, but at least it works.
Does it matter if I set up node.js or not?
The process you've followed (including your update) is exactly as the example intends and you are not missing anything! Obviously, it is a fairly simple tutorial, but it sets you up with a token and you should be able to get the information you need.
For the credentials, you can set these directly in your Terminal by running each of the export commands. Read more about EXPORT here: https://www.cyberciti.biz/faq/linux-unix-shell-export-command/

unable to run openstack tempest testcases in group

i have created one sampletest.txt file in tempest folder and written tempest test case location in that file.
now i want to run that file using testr or nosetest so that all the test case present in that file get executed..
example
contents in sampletest.txt file
tempest.api.identity.admin.test_users:UsersTestJSON.test_create_user_with_enabled
tempest.api.identity.admin.test_roles:RolesTestJSON.test_role_create_delete
tempest.api.identity.admin.test_roles:RolesTestJSON.test_get_role_by_id
tempest.api.identity.admin.test_roles:RolesTestJSON.test_remove_user_role
now i want to execute this sampletest.txt file so that all the testcase get executed...
if i am executing this file nosetests -vx sampletest.txt , i am getting error
Try to use tilt and cat the file Eg:
nosetest -vx `cat sampletest.txt`
Please make sure to configure your etc/tempest.conf are as below,
[identity]
uri=http://127.0.0.1:5000/v2.0/
uri_v3 = http://127.0.0.1:5000/v3/
auth_version=v2
admin_domain_name = Default
admin_tenant_name = admin
admin_password = {your_openstack_admin_login_password}
admin_username = admin
tenant_name = {non-admin-tenant-eg-demo}
username = {non-admin-user-eg-demo}
password = {non-admin-user-password}
[dashboard]
login_url=http://127.0.0.1/auth/login/
uri_v3 = http://127.0.0.1:5000/v3/
If still you are getting any errors please post your error logs.
You can also refer my post :http://naggappan.wordpress.com/2014/10/15/configure-and-execute-tempest-in-openstack-environment/

Error with GDAL

I have tried and run this script from Rutger Kassies.
import gdal
import matplotlib.pyplot as plt
ds = gdal.Open('HDF4_SDS:sample:"A2002037045000.L2_LAC.SAMPLE.hdf":01')
data = ds.ReadAsArray()
ds = None
fig, ax = plt.subplots(figsize=(6,6))
ax.imshow(data[0,:,:], cmap=plt.cm.Greys, vmin=1000, vmax=6000)
But then an error always occured:
Traceback (most recent call last):
File "D:\path\to\python\stackoverflow.py", line 5, in <module>
data = ds.ReadAsArray()
AttributeError: 'NoneType' object has no attribute 'ReadAsArray'
What's wrong with the script? Am I missing something? In installing GDAL I have followed this instruction http://pythongisandstuff.wordpress.com/2011/07/07/installing-gdal-and-ogr-for-python-on-windows/
Am using windows 7/32 bit/Python 2.7.
Thanks!
gdal.Open() is failing and returning 'None'. This produces the sometimes counterintuitive message "NoneType' object has no attribute ...". Quoting from Python: Attribute Error - 'NoneType' object has no attribute 'something', "NoneType means that instead of an instance of whatever Class or Object you think you're working with, you've actually got None. That usually means that an assignment or function call up above failed or returned an unexpected result."
Apparently GDAL is correctly installed. It could be that the file is not readable or that there is an issue with the HDF driver. Are you getting any error message like:
`HDF4_SDS:sample:"A2002037045000.L2_LAC.SAMPLE.hdf":01' does not
exist in the file system, and is not recognised as a supported dataset
name.
To get additional information you can try something like this instead of the gdal.Open() line in your script:
gdal.UseExceptions()
ds=None
try:
ds = gdal.Open('HDF4_SDS:sample:"A2002037045000.L2_LAC.SAMPLE.hdf":01')
except RuntimeError, err:
print "Exception: ", err
exit(1)
Also, there's an extra '}' at the end of the script.
By default, osgeo.gdal returns None on error, and does not normally raise informative exceptions. You can change this with gdal.UseExceptions().
Try something like this:
from osgeo import gdal
gdal.UseExceptions()
source_path = r'HDF4_SDS:sample:"D:\path\to\file\A2002037045000.L2_LAC.SAMPLE.hdf":01'
try:
ds = gdal.Open(source_path)
except RuntimeError as ex:
raise IOError(ex)
The last bit just re-raises the exception as an IOError rather than a RuntimeException.
The solution is to modify source_path to a working path to your data source, e.g., I see
IOError: `HDF4_SDS:sample:"A2002037045000.L2_LAC.SAMPLE.hdf":01' does not exist in the file system, and is not recognised as a supported dataset name.

django generator function not working with real server

I have some code written in django/python. The principal is that the HTTP Response is a generator function. It spits the output of a subprocess on the browser window line by line. This works really well when I am using the django test server. When I use the real server it fails / basically it just beachballs when you press submit on the page before.
#condition(etag_func=None)
def pushviablah(request):
if 'hostname' in request.POST and request.POST['hostname']:
hostname = request.POST['hostname']
command = "blah.pl --host " + host + " --noturn"
return HttpResponse( stream_response_generator( hostname, command ), mimetype='text/html')
def stream_response_generator( hostname, command ):
proc = subprocess.Popen(command.split(), 0, None, subprocess.PIPE, subprocess.PIPE, subprocess.PIPE )
yield "<pre>"
var = 1
while (var == 1):
for line in proc.stdout.readline():
yield line
Anyone have any suggestions on how to get this working with on the real server? Or even how to debug why it is not working?
I discovered that the generator function is actually running but it has to complete before the httpresponse throws up a page onscreen. I don't want to have to wait for it to complete before the user sees output. I would like the user to see output as the subprocess progresses.
I'm wondering if this issue could be related to something in apache2 rather than django.
#evolution did you use gunicorn to deploy your app. If yes then you have created a service. I am having a similar kind of issue but with libreoffice. As much as I have researched I have found that PATH is overriding the command path present on your subprocess. I did not have a solution till now. If you bind your app with gunicorn in terminal then your code will also work.

No indexers created by Djapian for Django

I am working through the tutorial for setting up Djapian and am trying to use the indexshell (as demonstrated in this step). When I run the command 'list' I get the following output:
Installed spaces/models/indexers:
- 0: 'global'
I therefore cannot run any queries:
>>> query
No index selected
Which leads me to attempt:
>>> use 0
Illegal index alias '0'. See 'list' command for available aliases
My index.py is as follows:
from djapian import space, Indexer, CompositeIndexer
from cms.models import Article
class ArticleIndexer(Indexer):
fields = ['body']
tags = [
('title', 'title'),
('author', 'author'),
('pub_date', 'pub_date',),
('category', 'category')
]
space.add_index(Article, ArticleIndexer, attach_as='indexer')
Update: I moved the djapian folder from site-packages to within my project folder and I move index.py from the project root to within the djapian folder. When I run 'list' in the indexshell the following is now returned:
>>> list
Installed spaces/models/indexers:
- 0: 'global'
- 0.0 'cms.Article'
-0.0.0: 'djapian.space.defaultcmsarticleindexer'
I still cannot do anything though as when I try to select an index I still get the following error:
>>> use 0.0
Illegal index alias '0'. See 'list' command for available aliases
Update 2: I had a problem with my setting for DJAPIAN_DATABASE_PATH which is now fixed. I can select an indexer using the command 'use 0.0.0' but when I try to run a query it raises the following ValueError: "Empty slice".
Have you fixed the problem of the ValueError: Empty Slice?
I'm having the exact same problem using the djapian tutorial. First I was wondering if my database entries were right, but now I'm thinking it might have something to do with the actual querying of the Xapian install?
Seeing that I haven't had to point to the install at all wonders me if I placed it in the right directory and if djapian knows where to find it.
-- Edit
I've found the solution, atleast for me. The tutorial is not up to date and the query command expects a number of results too. So if you use 'query mykeyword 5' you get 5 results and the ValueError: Empty Slice disappears. It's a known issue and it will be fixed soon from what I read.
Perhaps you're not loading indexes?
You could try placing the following in your main urls.py:
import djapian
djapian.load_indexes()
In a comment to your question you write that you've placed index.py file in the project root. It should actually reside within an app, along models.py.
One more thing (which is very unlikely to be the cause of your problems); you've got a stray comma on the following line:
('pub_date', 'pub_date',),
^