python3 pythonscript.py 
Traceback (most recent call last):
  File "pythonscript.py", line 1, in <module>
    import pysftp as sftp
  File "/usr/local/lib/python3.4/dist-packages/pysftp/__init__.py", line 12, in <module>
    import paramiko
  File "/usr/local/lib/python3.4/dist-packages/paramiko/__init__.py", line 30, in <module>
    from paramiko.transport import SecurityOptions, Transport
  File "/usr/local/lib/python3.4/dist-packages/paramiko/transport.py", line 32, in <module>
    from cryptography.hazmat.backends import default_backend
ImportError: No module named 'cryptography'

Why am I getting the above error when I run the following script. Please note that I've tried using just python (which is 2.x) and python3 and I've installed paramiko, pycrypto, and pysftp for by 2.x and 3

import pysftp as sftp

def push_file_to_server():
    s = sftp.Connection(host='address', username='user', password='xxx')
    local_path = 'testme.txt'
    remote_path = '/home/testme.txt'

    s.put(local_path, remote_path)
    s.close()

push_file_to_server

Thanks.

Dani AI

Generated

This traceback is raised because Paramiko imports the cryptography package under the hood, and it is not installed in the interpreter you are using. As hinted, make sure you install it into the same Python that runs your script. Mixing pip (Python 2) and pip3 (Python 3) is a common cause of this on Linux.

Quick, reliable setup for Python 3:

python3 -m pip install --upgrade pip setuptools wheel
python3 -m pip install cryptography paramiko pysftp
python3 -c "import cryptography, paramiko, pysftp; print('ok')"

If installation of cryptography fails to build on Debian/Ubuntu, install the headers first, then retry:

sudo apt-get update
sudo apt-get install -y build-essential libssl-dev libffi-dev python3-dev
python3 -m pip install cryptography

Two other gotchas in your snippet:

  • You define push_file_to_server but never call it. Make sure you end with push_file_to_server().
  • Ensure the remote directory exists and your user has write permissions, otherwise put() will fail even after the import issue is fixed.

If pysftp still gives you trouble, you can upload the file directly with Paramiko (same underlying library), which avoids an extra wrapper and makes errors easier to diagnose:

import paramiko

ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.connect('address', username='user', password='xxx')
sftp = ssh.open_sftp()
sftp.put('testme.txt', '/home/testme.txt')
sftp.close()
ssh.close()

Finally, to avoid cross-interpreter confusion in the future, consider using a virtual environment:

python3 -m venv .venv && source .venv/bin/activate
python -m pip install cryptography paramiko pysftp

Perhaps you need the cryptography module Click Here ?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.