Uploading Files with Sftp

Uploading a file via website to SFTP server

I assume you use (or can use) PHP. You didn't specify, what technology you are using.

Start with reading:

  • POST method uploads - for transferring a file from the client's machine to your website
  • PHP SFTP Simple File Upload or How do i use phpseclib to upload file from my php server -> someOther server? - for transferring a file from your website to the SFTP

That combined together gets you a code like:

include('Net/SFTP.php');

$uploaded_file = $_FILES["attachment"]["tmp_name"];

$sftp = new Net_SFTP("example.com");
if (!$sftp->login('username', 'password'))
{
die("Connection failed");
}

$sftp->put(
"/remote/path/".$_FILES["attachment"]["name"],
file_get_contents($uploaded_file));

This is a very simplified code, lacking lots of validation and error checking.

The code uses the phpseclib library.

Upload file to SFTP server accessible via another SSH/SFTP server only

Use an SSH tunnel, aka local port forwarding, to open an SSH/SFTP connection to C via B. Then you can directly upload the file to C from your local machine (A), without uploading it first to B:

Session sessionB = jsch.getSession("usernameB", "hostB", 22);
// ...
sessionB.connect();

int forwardedPort = 2222; // any port number which is not in use on the local machine
sessionB.setPortForwardingL(forwardedPort, "hostC", 22);

Session sessionC = jsch.getSession("usernameC", "localhost", forwardedPort);
// ...
sessionC.connect();

Channel channel = sessionC.openChannel("sftp");
channel.connect();
ChannelSftp channelSftp = (ChannelSftp)channel;

channelSftp.put("C:\\local\\path\\file.txt", "/remote/path/on/C/file.txt");

Obligatory note: Do not use StrictHostKeyChecking=no. You are losing security by doing so. See How to resolve Java UnknownHostKey, while using JSch SFTP library?

Upload file to SFTP directly without storing it into local system

Encrypt

Encrypt and send file to remote server (encrypt_and_send.py):

from cryptography.fernet import Fernet
from io import BytesIO
import pysftp
from time import sleep

secret_key = b'fj6IO3olXODT7Z2xWjFoJkzg0qztYIkPtf-wDXwnwpY='

fernet = Fernet(secret_key)

with open('data.txt', 'rb') as file:
original_data = file.read()

print('Data to encode:')
print(original_data.decode('utf-8'))

encrypted_data = fernet.encrypt(original_data)

print('Encrypted data:')
print(encrypted_data.decode('utf-8'))

file_like_object = BytesIO(encrypted_data)

with pysftp.Connection(host="192.168.1.18", username="root", password="password", log="/tmp/pysftp.log") as sftp:
file_like_object.seek(0)
sftp.putfo(file_like_object, 'output.txt')

print('sent')

Output:

Data to encode:
a
b
c
d
e
f

Encrypted data:
gAAAAABhE4sAq5iHkZ36H_vbVuBdlGrtLrQNpAXe-utbZT_JOHxnb1FipftlLiZcCO7AnkX_CEF4bz1oZk-CC57ubStE7u6k-w==
sent

Decrypt

Read data on remote machine (decrypt.py)

from cryptography.fernet import Fernet

secret_key = b'fj6IO3olXODT7Z2xWjFoJkzg0qztYIkPtf-wDXwnwpY='

fernet = Fernet(secret_key)

with open('output.txt', 'rb') as enc_file:
encrypted = enc_file.read()

print(fernet.decrypt(encrypted).decode('utf-8'))

Output:

a
b
c
d
e
f

Additional info

when I run this script using pysftp==0.2.9 exception appear:

Exception ignored in: <function Connection.__del__ at 0x102941f70>
Traceback (most recent call last):
File "/.../lib/python3.9/site-packages/pysftp/__init__.py", line 1013, in __del__
File "/.../lib/python3.9/site-packages/pysftp/__init__.py", line 795, in close
ImportError: sys.meta_path is None, Python is likely shutting down

Looks like library problem.

pysftp==0.2.8 transfer data without any problems.



Related Topics



Leave a reply



Submit