Forums

Sample code for FTP access to Python Anywhere

Hi...does anyone have any sample python code to simply upload a file from a laptop (mac) to Python Anywhere that they can share? I tried ftplib, then paramiko and then pysftp but always ran into errors. If someone can help me avoid trying to 'reinvent the wheel', I'd be very grateful....thank you....

What are the errors that you run into?

Hi....The last attempt was:

import pysftp
IP = 'ssh.pythonanywhere.com'
UID = <myusername>
PSW = <mypassword>
with pysftp.Connection(host=IP, username=UID, password=PSW) as sftp:
    directory_structure = sftp.listdir_attr()
    for attr in directory_structure:
        print(attr.filename)

The error message was: No hostkey for host ssh.pythonanywhere.com found

[edited by admin: formatting]

This has to do with how ssh works. Check this out. By default ssh checks the ssh.pythonanywhere host against known hostkeys, and you have not added that to your known hosts yet.

so you can either add it manually (by manually ssh-ing), or you could say get the hostkey and load it every time (probably the correct way), or you could override it and say don't check hostkeys.

Thx...I finally got the following code to work (Thank you to Conor Hughes on Stack Overflow!):

import paramiko
ssh_client = paramiko.SSHClient() 
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
ssh_client.connect(hostname='ssh.pythonanywhere.com',port=22,username='<myid>',password='<mypwd>') 
s = ssh_client.open_sftp()
s.put(localfilepath,remotefilepath)

Note for anyone who might want to use this: localfilepath is the full path of the file on my laptop that I want to upload to PythonAnywhere, e.g, '/users/sunil/documents/config.csv' and remotefilepath is the full path of the resulting file after it is uploaded, e.g., '/home/<accountname>/targetfolder/config.csv' (the 'targetfolder' destination folder needs to already exist.)

Excellent, thanks for posting that! BTW I think the ssh_client object you have there will have a mkdir method too if you want to create a folder before uploading a file to it -- full documentation here.

I tried the following code partiall, just to establish the connection:

import paramiko
ssh_client = paramiko.SSHClient() 
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
ssh_client.connect(hostname='ssh.pythonanywhere.com',port=22,username='<myid>',password='<mypwd>')

but I received the following error:

TimeoutError: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

Any help will be appreciated.

I have just restarted my PC and everything goes well without any error. Sorry for any disturbance.