How to execute get command in redis cluster mode using python? - python

I want to perform the following scenario on redis using python.
Using command line:
1) redis-cli -c
2) redis_prompt >> get some_string
I tried using redis and rediscluster modules, but with no luck. Below are the codes that i tried:
1)
r = redis.Redis(host='123.123.123.123', port=6379, db=0)
r.get('some srting')
Got the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\redis\client.py", line 880, in get
return self.execute_command('GET', name)
File "C:\Python27\lib\site-packages\redis\client.py", line 573, in execute_command
return self.parse_response(connection, command_name, **options)
File "C:\Python27\lib\site-packages\redis\client.py", line 585, in parse_response
response = connection.read_response()
File "C:\Python27\lib\site-packages\redis\connection.py", line 582, in read_response
raise response
redis.exceptions.ResponseError: MOVED 9442 172.16.176.36:6380
2)
from rediscluster import StrictRedisCluster
startup_nodes = [{"host": "123.123.123.123", "port": "7000"}]
rc_readonly = StrictRedisCluster(startup_nodes=startup_nodes, decode_responses=True, readonly_mode=True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python27\lib\site-packages\rediscluster\client.py", line 181, in __init__
**kwargs
File "C:\Python27\lib\site-packages\rediscluster\connection.py", line 353, in __init__
**connection_kwargs)
File "C:\Python27\lib\site-packages\rediscluster\connection.py", line 141, in __init__
self.nodes.initialize()
File "C:\Python27\lib\site-packages\rediscluster\nodemanager.py", line 240, in initialize
raise RedisClusterException("Redis Cluster cannot be connected. Please provide at least one reachable node.")
rediscluster.exceptions.RedisClusterException: Redis Cluster cannot be connected. Please provide at least one reachable node.
Any help would be great.

Ok, so this error means one of the following:
In these lines of code (1):
r = redis.Redis(host='123.123.123.123', port=6379, db=0)
r.get('some srting')
you try to fetch the key "some sting" from host 123.123.123.123 and
port 6379. The error redis.exceptions.ResponseError: MOVED 9442
172.16.176.36:6380 means that this key lies in 172.16.176.36:6380. So try to connect with ./redis-cli -c -p 6380 in this node and then
execute CLUSTER GETKEYSINSLOT 6380 3 to see if this key is actually
here.
From (2) this error: rediscluster.exceptions.RedisClusterException: Redis Cluster cannot be connected. Please provide at least one reachable node means that something is wrong with the cluster. Maybe, you have not made correct the initialization.
First in /home/{{user}}/redis-yourversion/utils/create-cluster you
will find create-cluster.sh. Set up port and host and nodes and then
execute ./create-cluster start ./create-cluster-create. But first you
have to start redis server in cluster mode. Go to redis.conf and in
the configuration parameters you will see cluster-enabled no. Set up
to yes. After this you must run ./redis-server ../redis.conf (give
the path for redis.conf). If cluster enabled is correct you will see Running in cluster mode
Important thing to remember:
The parameter -c in terminal means that redis nodes can execute the redirections and find the correct node that the key belongs without MOVED errors. If you have a driver suppose in python to manipulate the nodes and fetch keys or whatever you must manage these redirections by yourself.

Related

VI_ERROR_TMO (-1073807339) on Anritsu OSA

I'm working on interfacing an old Optical Spectrum Analyzer Anritsu MS9710B with a RS232 connection. A year ago, I managed to comunicate with him, send SCPI command using pyvisa and receive data. Today, I execute the exact same code with libraries up to date and I get an error Timeout when I query IDN or anything. The RS232-USB drivers are ok, I manage to open a communication but a query or read fail.
I changed the parameter to "RS232C" on the OSA parameters and my communication parameters are the same between OSA and program. Following advices from the forum, I tried the connection with NI-VISA where I get the same error. I tried to change timeout parameter, write_termination and read_termination but there isn't any change. The manual is very hard to understand termination value, but when it worked I didn't add anything.
I don't know anymore what to do.
Any advices and help would be warmly welcome to fix my problem !
import pyvisa
from pyvisa.constants import StopBits, Parity
rm = pyvisa.ResourceManager()
print(rm.list_resources())
my_instrument = rm.open_resource('ASRL5::INSTR')
my_instrument.baud_rate=9600
my_instrument.data_bits=8
my_instrument.parity=Parity.even
my_instrument.stop_bits=StopBits.one
my_instrument.write('*IDN?')
print(my_instrument.read())```
'''
('ASRL5::INSTR',)
Traceback (most recent call last):
File "PremiereComm.py", line 26, in <module>
print(my_instrument.read())
File "C:\Program Files\Python38\lib\site-packages\pyvisa\resources\messagebased.py", line 486, in read
message = self._read_raw().decode(enco)
File "C:\Program Files\Python38\lib\site-packages\pyvisa\resources\messagebased.py", line 442, in _read_raw
chunk, status = self.visalib.read(self.session, size)
File "C:\Program Files\Python38\lib\site-packages\pyvisa\ctwrapper\functions.py", line 2337, in read
ret = library.viRead(session, buffer, count, byref(return_count))
File "C:\Program Files\Python38\lib\site-packages\pyvisa\ctwrapper\highlevel.py", line 222, in _return_handler
return self.handle_return_value(session, ret_value) # type: ignore
File "C:\Program Files\Python38\lib\site-packages\pyvisa\highlevel.py", line 251, in handle_return_value
raise errors.VisaIOError(rv)
pyvisa.errors.VisaIOError: VI_ERROR_TMO (-1073807339): Timeout expired before operation completed.
>>> '''

How to store dictionary in redis from python

I'm trying to store a python dict in memory through redis, I was following the pypi doc, when I try to instance RedisCluster i got this error:
from redis.cluster import RedisCluster as Redis # this line works
rc = Redis(host='localhost', port=6379) # here is the problem
Traceback (most recent call last):
File "/home/developer/.pyenv/versions/redisTesting/lib/python3.9/site-packages/redis/cluster.py", line 1306, in initialize
raise RedisClusterException(
redis.exceptions.RedisClusterException: Cluster mode is not enabled on this node
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/developer/.pyenv/versions/3.9.5/lib/python3.9/code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "/home/developer/.pyenv/versions/redisTesting/lib/python3.9/site-packages/redis/cluster.py", line 507, in __init__
self.nodes_manager = NodesManager(
File "/home/developer/.pyenv/versions/redisTesting/lib/python3.9/site-packages/redis/cluster.py", line 1128, in __init__
self.initialize()
File "/home/developer/.pyenv/versions/redisTesting/lib/python3.9/site-packages/redis/cluster.py", line 1334, in initialize
raise RedisClusterException(
redis.exceptions.RedisClusterException: ERROR sending "cluster slots" command to redis server 127.0.0.1:6379. error: Cluster mode is not enabled on this node
I know that the problem is Cluster mode is not enabled on this node but I didn't find a way to solve this error, how can enable the cluster mode on the node?
Also I find a way to store this dict in memory with
import redis
r = redis.Redis()
r.hmset({
"color": "green",
"price": 99.99,
"style": "baseball",
"quantity": 200,
"npurchased": 0,
})
but this got me a deprecate warning <input>:1: DeprecationWarning: Redis.hmset() is deprecated. Use Redis.hset() instead. and when I tryed to use r.hset() the terminal got me redis.exceptions.DataError: Invalid input of type: 'dict'. Convert to a bytes, string, int or float first.
Change redis.cluster to redis and connection would succeed.
#from redis.cluster import RedisCluster as Redis # this line works (but assumes you are connecting to Redis Cluster)
from redis import Redis
rc = Redis(host='localhost', port=6379)

ciscoaxl api python errors

I am starting out working on looking into using Python for some Cisco CUCM automation. I found the plugin ciscoaxl here, I installed it and programed the following script:
from ciscoaxl import axl
cucm = "10.10.20.1"
username = "axlusr"
password = "password1"
version = "12.5"
ucm = axl(username, password, cucm, version)
for phone in ucm.get_phones():
print(phone.name)
I am connected to Cisco's DevNET Sandbox and all the login and configuration for the AXL user appear to be correct, however I get the following output when I attempt to run the script:
Traceback (most recent call last):
File "%home%\AppData\Local\Programs\Python\Python39\axl-test.py", line 7, in <module>
for phone in ucm.get_phones():
File "%home%\AppData\Local\Programs\Python\Python39\lib\site-packages\ciscoaxl\axl.py", line 1877, in get_phones
for each in inner(skip):
File "%home%\AppData\Local\Programs\Python\Python39\lib\site-packages\ciscoaxl\axl.py", line 1869, in inner
res = self.client.listPhone(
File "%home%\AppData\Local\Programs\Python\Python39\lib\site-packages\zeep\proxy.py", line 40, in __call__
return self._proxy._binding.send(
File "%home%\AppData\Local\Programs\Python\Python39\lib\site-packages\zeep\wsdl\bindings\soap.py", line 130, in send
return self.process_reply(client, operation_obj, response)
File "%home%\AppData\Local\Programs\Python\Python39\lib\site-packages\zeep\wsdl\bindings\soap.py", line 195, in process_reply
return self.process_error(doc, operation)
File "%home%\AppData\Local\Programs\Python\Python39\lib\site-packages\zeep\wsdl\bindings\soap.py", line 283, in process_error
raise Fault(
zeep.exceptions.Fault: Unknown fault occured
I have run it on Windows10 in an IDLE enviornment, from the Linux-Subsystem (Ubuntu 20.04) via python and ipython3.
After some additional research this is a know issue with CUCM 12.5. It should be fixed in CU1 see here: https://github.com/mvantellingen/python-zeep/issues/989
I still receive this error on 12.5.1.12900-115, but I receive it when I don't have the appropriate permissions. Fixing user permissions for AXL access resolves it.

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.

python-iptables: Cryptic error when allowing incoming TCP traffic on port 1234

I wanted to write an iptables script in Python. Rather than calling iptables itself I wanted to use the python-iptables package. However I'm having a hard time getting some basic rules setup. I wanted to use the filter chain to accept incoming TCP traffic on port 1234. So I wrote this:
import iptc
chain = iptc.Chain(iptc.TABLE_FILTER,"INPUT")
rule = iptc.Rule()
target = iptc.Target(rule,"ACCEPT")
match = iptc.Match(rule,'tcp')
match.dport='1234'
rule.add_match(match)
rule.target = target
chain.insert_rule(rule)
However when I run this I get this thrown back at me:
Traceback (most recent call last):
File "testing.py", line 9, in <module>
chain.insert_rule(rule)
File "/usr/local/lib/python2.6/dist-packages/iptc/__init__.py", line 1133, in insert_rule
self.table.insert_entry(self.name, rbuf, position)
File "/usr/local/lib/python2.6/dist-packages/iptc/__init__.py", line 1166, in new
obj.refresh()
File "/usr/local/lib/python2.6/dist-packages/iptc/__init__.py", line 1230, in refresh
self._free()
File "/usr/local/lib/python2.6/dist-packages/iptc/__init__.py", line 1224, in _free
self.commit()
File "/usr/local/lib/python2.6/dist-packages/iptc/__init__.py", line 1219, in commit
raise IPTCError("can't commit: %s" % (self.strerror()))
iptc.IPTCError: can't commit: Invalid argument
Exception AttributeError: "'NoneType' object has no attribute 'get_errno'" in <bound method Table.__del__ of <iptc.Table object at 0x7fcad56cc550>> ignored
Does anyone have experience with python-iptables that could enlighten on what I did wrong?
Oh, just noticed this one. Can you give the latest head from github a shot? I've fixed tons of bugs and updated python-iptables to work with the latest iptables version. If you still experience issues please open a ticket on github.
One thing that sure is not quite right is that you don't set the protocol in the rule:
import iptc
chain = iptc.Chain(iptc.TABLE_FILTER,"INPUT")
rule = iptc.Rule()
Set protocol e.g. here:
rule.protocol = 'tcp'
and then you should be all right:
target = iptc.Target(rule,"ACCEPT")
match = iptc.Match(rule,'tcp')
match.dport='1234'
rule.add_match(match)
rule.target = target
chain.insert_rule(rule)

Categories

Resources