Simple pysFTP was working last night, but now does not - python-3.x

Last night I was writing my first pySFTP Notebook, and I was able to get it to work. It was working when I went to bed, but now it does not. I get an error on the connection command....
import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None # disable host key checking.
#with pysftp.Connection('test.rebex.net', username='demo',password='password', cnopts=cnopts) as sftp:
# do stuff here
# print('this works!')
s = pysftp.Connection(host='test.rebex.net', username='demo', password='password', cnopts=cnopts)
data = s.listdir()
s.close()
for i in data:
print (i)
The error I am receiving is...
Unknown exception: from_buffer() cannot return the address of the raw string within a bytes or unicode object
Traceback (most recent call last):
File "/databricks/python/lib/python3.5/site-packages/paramiko/transport.py", line 2075, in run
self.kex_engine.parse_next(ptype, m)
File "/databricks/python/lib/python3.5/site-packages/paramiko/kex_curve25519.py", line 64, in parse_next
return self._parse_kexecdh_reply(m)
File "/databricks/python/lib/python3.5/site-packages/paramiko/kex_curve25519.py", line 129, in _parse_kexecdh_reply
self.transport._activate_outbound()
File "/databricks/python/lib/python3.5/site-packages/paramiko/transport.py", line 2553, in _activate_outbound
self.local_cipher, key_out, IV_out, self._ENCRYPT
File "/databricks/python/lib/python3.5/site-packages/paramiko/transport.py", line 1934, in _get_cipher
return cipher.encryptor()
File "/databricks/python/lib/python3.5/site-packages/cryptography/hazmat/primitives/ciphers/base.py", line 121, in encryptor
self.algorithm, self.mode
File "/databricks/python/lib/python3.5/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 298, in create_symmetric_encryption_ctx
return _CipherContext(self, cipher, mode, _CipherContext._ENCRYPT)
File "/databricks/python/lib/python3.5/site-packages/cryptography/hazmat/backends/openssl/ciphers.py", line 67, in __init__
iv_nonce = self._backend._ffi.from_buffer(mode.nonce)
TypeError: from_buffer() cannot return the address of the raw string within a bytes or unicode object
TypeError: from_buffer() cannot return the address of the raw string within a bytes or unicode object
Thanks for your help!

pysftp lists paramiko as one of its dependencies. Paramiko issue #1037 documents and attributes the error thrown in your code to a version compatibility issue with cryptography.
My recommendations to avoid this include the following:
Use the Databricks Conda Runtime for improved Python dependency management and visibility
Upgrade the cryptography version (I tested with cryptography=2.6.1, which is included in the databricks-standard conda env)

Related

I keep getting Invalid Token error in python cryptography (cryptography.fernet.InvalidToken)

I wrote this prototype code to encrypt some text (and vice - versa). I keep getting this error when I set the command to self.get() while self.write works as it should. I have no idea what causes this error or how to solve it...Help...
from cryptography.fernet import Fernet
class EncodingText:
def __init__(self):
self.key = Fernet.generate_key()
self.f = Fernet(self.key)
self.get()
def write(self):
stuff = "hello there".encode()
token = self.f.encrypt(stuff)
open_file_for_edit = open("file.txt", 'wb')
open_file_for_edit.write(token)
open_file_for_edit.close()
def get(self):
read_file = open("file.txt", 'rb')
reading = read_file.read()
print(reading)
token = self.f.decrypt(reading)
print(token)
read_file.close()
if __name__ == "__main__":
EncodingText()
The error I get is as follows:
Traceback (most recent call last):
File "C:\Users\xoxo\AppData\Local\Programs\Python\Python38-32\lib\site-packages\cryptography\fernet.py", line 113, in _verify_signature
h.verify(data[-32:])
File "C:\Users\xoxo\AppData\Local\Programs\Python\Python38-32\lib\site-packages\cryptography\hazmat\primitives\hmac.py", line 70, in verify
ctx.verify(signature)
File "C:\Users\xoxo\AppData\Local\Programs\Python\Python38-32\lib\site-packages\cryptography\hazmat\backends\openssl\hmac.py", line 78, in verify
raise InvalidSignature("Signature did not match digest.")
cryptography.exceptions.InvalidSignature: Signature did not match digest.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:/Users/xoxo/Desktop/Python Programs/xoxo/xoxo.py", line 26, in <module>
EncodingText()
File "c:/Users/xoxo/Desktop/Python Programs/xoxo/xoxo.py", line 7, in __init__
self.get()
File "c:/Users/xoxo/Desktop/Python Programs/xoxo/xoxo.py", line 20, in get
tokenf = self.f.decrypt(reading)
File "C:\Users\xoxo\AppData\Local\Programs\Python\Python38-32\lib\site-packages\cryptography\fernet.py", line 76, in
decrypt
return self._decrypt_data(data, timestamp, ttl, int(time.time()))
File "C:\Users\xoxo\AppData\Local\Programs\Python\Python38-32\lib\site-packages\cryptography\fernet.py", line 125, in _decrypt_data
self._verify_signature(data)
File "C:\Users\xoxo\AppData\Local\Programs\Python\Python38-32\lib\site-packages\cryptography\fernet.py", line 115, in _verify_signature
raise InvalidToken
cryptography.fernet.InvalidToken
Let us go through the code line by line:
In the method __init__:
Line 1: key generation.
self.key = Fernet.generate_key() # this is called
We are generating a random key every time the method is called.
Line 2: Cipher generation
self.f = Fernet(self.key)
We are creating a cipher with a completely random key.
Line 3: Decryption
self.get()
We are calling a new method.
In method get:
Line 1, 2 and 3: Reading a file
read_file = open("file.txt", 'rb')
reading = read_file.read()
print(reading)
Here, 2 things are possible.
The file is missing from the path, and FileNotFoundError is raised and the program halts.
The file is present.
Assuming, the file is present (#2). The file contents will be read and the contents will be printed.
Line 4: Decryption
token = self.f.decrypt(reading)
Here, our file contents will be decrypted. Remember that, from point 1.1.1 and
1.1.2, each time our program is called, a random key is generated and the cipher
is generated with a random key.
Since Fernet, by implementation, uses AES, which is a symmetric cipher, we require the same key
for encryption and decryption.
But, by 1.1.1 and 1.1.2, we are generating a random key each time the program
runs.
This explains the error message. The cipher is trying to decrypt the data from
the file which was encrypted with a completely random key with another random
key, which leads to incorrect decryption.
If you insert self.write() before self.get(), the program runs. This is because
the same key is used to decrypt the data.

python pyttsx3 error -- _pickle.UnpicklingError: invalid load key, '\x00'

i am trying to convert text to speech using pyttsx3 in python. but iam getting the error -- _pickle.UnpicklingError: invalid load key, '\x00'.
it worked once. later it didn't
my code
import pyttsx3
engine = pyttsx3.init()
engine.say("I will speak this text")
engine.runAndWait()
error i am receiving is --
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\pyttsx3__init__.py",
line 20, in init
eng = _activeEngines[driverName]
File "C:\ProgramData\Anaconda3\lib\weakref.py", line 137, in
getitem
o = self.data[key]()
KeyError: None
During handling of the above exception, another exception occurred:
...
File "C:\ProgramData\Anaconda3\lib\site-packages\win32com\client\gencache.py", line 113, in _LoadDicts
version = p.load()
_pickle.UnpicklingError: invalid load key, '\x00'.
python version is 3.7.3 |
pyttsx3 version is 2.71|
pywin32 version is 224
please help
I had this problem as well and fixed it by deleting gen_py in my temp directory.
You can find this folder here:
C:\Users\USERNAME\AppData\Local\Temp\gen_py

'NoneType' object has no attribute 'open_session

i wrote a script to connect to sftp server in python but it showing this error below and i do not understand it. please help me fix the bug
import pysftp
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
with pysftp.Connection(host="127.0.0.1", username="new34",password="password",cnopts=cnopts) as srv:
print("connection successful")
# Get the directory and file listing
data = srv.listdir()
srv.put("testfile.txt")
# Closes the connection
srv.close()
# Prints out the directories and files, line by line
for i in data:
print(i)
it shows the following error; please help to fix the bug
C:\Users\Rohan\PycharmProjects\untitled1\venv\Scripts\python.exe C:/Users/Rohan/PycharmProjects/untitled1/yu.py
C:\Users\Rohan\PycharmProjects\untitled1\venv\lib\site-packages\pysftp\__init__.py:61: UserWarning: Failed to load HostKeys from C:\Users\Rohan\.ssh\known_hosts. You will need to explicitly load HostKeys (cnopts.hostkeys.load(filename)) or disableHostKey checking (cnopts.hostkeys = None).
warnings.warn(wmsg, UserWarning)
Traceback (most recent call last):
connection successful
File "C:/Users/Rohan/PycharmProjects/untitled1/yu.py", line 10, in <module>
data = srv.listdir()
File "C:\Users\Rohan\PycharmProjects\untitled1\venv\lib\site-packages\pysftp\__init__.py", line 591, in listdir
self._sftp_connect()
File "C:\Users\Rohan\PycharmProjects\untitled1\venv\lib\site-packages\pysftp\__init__.py", line 205, in _sftp_connect
self._sftp = paramiko.SFTPClient.from_transport(self._transport)
File "C:\Users\Rohan\PycharmProjects\untitled1\venv\lib\site-packages\paramiko\sftp_client.py", line 164, in from_transport
chan = t.open_session(
AttributeError: 'NoneType' object has no attribute 'open_session'
Process finished with exit code 1
Your code has indentation issue.
Try this,
with pysftp.Connection(host="127.0.0.1", username="new34",password="password",cnopts=cnopts) as srv:
print("connection successful")
# Get the directory and file listing
data = srv.listdir()
srv.put("testfile.txt")
with automatically closes the connection. No need to close explicitly.

TypeError: Can't convert 'bytes' object to str implicitly for tweepy

from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
ckey=''
csecret=''
atoken=''
asecret=''
class listener(StreamListener):
def on_data(self,data):
print(data)
return True
def on_error(self,status):
print(status)
auth = OAuthHandler(ckey,csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
twitterStream.filter(track="cricket")
This code filter the twitter stream based on the filter. But I am getting following traceback after running the code. Can somebody please help
Traceback (most recent call last):
File "lab.py", line 23, in <module>
twitterStream.filter(track="car".strip())
File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 430, in filter
self._start(async)
File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 346, in _start
self._run()
File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 286, in _run
raise exception
File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 255, in _run
self._read_loop(resp)
File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 298, in _read_loop
line = buf.read_line().strip()
File "C:\Python34\lib\site-packages\tweepy\streaming.py", line 171, in read_line
self._buffer += self._stream.read(self._chunk_size)
TypeError: Can't convert 'bytes' object to str implicitly
Im assuming you're using tweepy 3.4.0. The issue you've raised is 'open' on github (https://github.com/tweepy/tweepy/issues/615).
Two work-arounds :
1)
In streaming.py:
I changed line 161 to
self._buffer += self._stream.read(read_len).decode('UTF-8', 'ignore')
and line 171 to
self._buffer += self._stream.read(self._chunk_size).decode('UTF-8', 'ignore')
and then reinstalled via python3 setup.py install on my local copy of tweepy.
2)
remove the tweepy 3.4.0 module, and install 3.3.0 using command: pip install -I tweepy==3.3.0
Hope that helps,
-A
You can't do twitterStream.filter(track="car".strip()). Why are you adding the strip() it's serving no purpose in there.
track must be a str type before you invoke a connection to Twitter's Streaming API and tweepy is preventing that connection because you're trying to add strip()
If for some reason you need it, you can do track_word='car'.strip() then track=track_word, that's even unnecessary because:
>>> print('car'.strip())
car
Also, the error you're getting does not match the code you have listed, the code that's in your question should work fine.

Error using Scapy

I am using Python2.5 and Scapy2.2.0 . When I execute the following code:
from scapy.all import *
a = IP(dst='10.100.95.184')
a.src = "10.100.95.22"
ab = a/ICMP()
sendp(ab)
I get the following error:
WARNING: No route found for IPv6 destination :: (no default route?)
Traceback (most recent call last):
File "C:\Python25\att.py", line 6, in <module>
sendp(ab)
File "C:\Python25\Lib\site-packages\scapy\sendrecv.py", line 259, in sendp
__gen_send(conf.L2socket(iface=iface, *args, **kargs), x, inter=inter, loop=loop, count=count, verbose=verbose, realtime=realtime)
File "C:\Python25\Lib\site-packages\scapy\sendrecv.py", line 237, in __gen_send
os.write(1,".")
OSError: [Errno 9] Bad file descriptor
Any idea how I can correct this?
i had a similar problem (not this exactly error message) and it looks like not a problem in your code. I fixed my scenario reinstalling the scapy package. Have you tried it? Try to upgrade your Python version to the next one too.
Good luck !

Resources