I have made a script which copy file from local machine to FTP server. I referred this link to make script Upload folders from local system to FTP using Python script, but now I want to copy file from FTP to another remote FTP machine on different location using Python script. How to do this?
File copy can be done using rsync command, but I want to do this using Python script.
Code:
import ftplib
import os
server = 'host'
username = 'name'
password = 'pass'
ftp = ftplib.FTP(server, username, password)
Path = 'path'#source
val = "/des/"#destination
def copy(source,destination):
print(source)
print(destination)
os.chdir(source)
ftp.cwd(destination)
if "C:\\" in Path or "c:\\" in Path:
ftp_path = (source).split("\\")[-1]
else:
ftp_path = (source).split("/")[-1]
directory = destination+ftp_path
mkdir(directory)
ftp.cwd(directory)
read = os.listdir(source)
for file in read:
print(file)
if "C:\\" in Path or "c:\\" in Path:
Type = source + "\\" + file
else:
Type = source + "/" + file
print(Type)
print()
if os.path.isdir(Type):#If Type is Folder then it will create new
folder
copy(Type,directory+"/")
elif os.path.isfile(Type):#If Type is file then it will create file
print(Type)
current_dir = ftp.pwd() + "/"
f = Type
fh = open(f, 'rb')
ftp.storbinary('STOR %s' % current_dir + file, fh)
fh.close()
def mkdir(path):
#print(path)
ftp.mkd(path)
copy(Path,val)
ftp.close()
In general, you cannot transfer a file from one remote FTP server to another remote FTP server, if FTP protocol is the only way you can access the machines.
There's FXP protocol that allows that, but that's typically not allowed on most FTP servers.
If you have another access to one of the servers, like SSH, you can of course automatically login to the server and then run FTP client on it, to upload/download to/from the other server.
See also FTP copy a file to another place in same FTP.
I'm trying to write a html-file and then upload it to my website using the following code:
webpage = open('testfile.html',"w")
webpage.write(contents)
webpage.close
server = 'ftp.xxx.be'
username = 'userxxx'
password = 'topsecret'
ftp_connection = ftplib.FTP(server, username, password)
remote_path = "/"
ftp_connection.cwd(remote_path)
fh = open("testfile.html", 'rb')
ftp_connection.storbinary('STOR testfile.html', fh)
fh.close()
The problem is the .close command seems to be slower than the ftp connection and the file that is sent over ftp is empty. A few seconds after the ftp is executed I see the file correctly locally on my PC.
Any hints to be certain the .close is finished before the ftp starts (apart from using time.sleep())?
Running Python 3.xx on W7pro
Try blocking on the close call:
Blocking until a file is closed in python
By the way, are the parentheses missing on your close call?
I am trying to download a file from my FTP server to a specific folder, without a GUI. This is what I have so far, but it does nothing,
import urllib
urllib.urlretrieve('ftp://USERNAME:PASSWORD#ftp.SERVERNAME/File path/', 'FILENAME')
I edited my answer to be more simpler ..now we will need to use FtpLib
the code below is straightforward and it's elegant :D
import ftplib
path = 'pub/Health_Statistics/NCHS/nhanes/2001-2002/'
filename = 'L28POC_B.xpt'
ftp = ftplib.FTP("Server IP")
ftp.login("UserName", "Password")
ftp.cwd(path)
ftp.retrbinary("RETR " + filename ,open(filename, 'wb').write)
ftp.quit()
Just in case you need some explanation:
path is obviously the location of the file in the ftp server
filename is the name + extension of the file you want to download form server
ftp.login is where you'll put your credentials(username, password)
ftp.cwd will change the current working directory to where the file is located in order to download it :)
retrbinary simply will get the file from the server and store in your local machine using the same name it had on the server :)
Do not forget to change Server IP argument to your server's ip
and Voila that's it.
I am trying to upload a file to an FTP server, I wanted to write a Python script to simplify the process. Currently I ftp to the server and execute these commands:
quote allo file_size_in_bytes
put c:\path\to\file
This is what I have so far, I am not able to get the file to transfer using the put command.
from ftplib import FTP
import os
import time
from subprocess import call
ip = raw_input('Enter ip address: ') # User input for host
print ip # Prints host
filelocation = raw_input('Drag file here: ') # File to upload
print ('This is the local file '+filelocation) # Verify file location
filename = os.path.basename(filelocation) # If a File name is needed
filesize = os.path.getsize(filelocation) # Need file size in bytes for quote allo command
print ('This is the file size in bytes '+str(filesize)) # Verify correct size
time.sleep(2) # Pause to look at screen
ftp = FTP(ip) # Open ftp connection
ftp.login('user','pass') # Login
print ftp.getwelcome() # Verify proper connection
remotepath = ftp.pwd()+filename # If a remote path to ftp server is needed
print ('This is the file path on the processor '+remotepath) # Verify remote path
"\"quote\"" # Need this, not sure why
ftp.sendcmd('allo '+str(filesize)) # quote allo filesize, seems to work
#"\"put\"" # Experimenting, don't know if this is needed
call(['echo "put C:\filelocation" | ftp']) # This doesn't appear to work
time.sleep(5)
ftp.quit()
You are logging in with ftplib, yet you are trying to run an external ftp process for the upload itself. That cannot work as the external ftp process does not know about your ftplib FTP session.
To upload a file using the ftplib, use storbinary or storlines method.
See for example Python Script Uploading files via FTP.
I would like to make a script to upload a file to FTP.
How would the login system work? I'm looking for something like this:
ftp.login=(mylogin)
ftp.pass=(mypass)
And any other sign in credentials.
Use ftplib, you can write it like this:
import ftplib
session = ftplib.FTP('server.address.com','USERNAME','PASSWORD')
file = open('kitten.jpg','rb') # file to send
session.storbinary('STOR kitten.jpg', file) # send the file
file.close() # close file and FTP
session.quit()
Use ftplib.FTP_TLS instead if you FTP host requires TLS.
To retrieve it, you can use urllib.retrieve:
import urllib
urllib.urlretrieve('ftp://server/path/to/file', 'file')
EDIT:
To find out the current directory, use FTP.pwd():
FTP.pwd(): Return the pathname of the current directory on the server.
To change the directory, use FTP.cwd(pathname):
FTP.cwd(pathname): Set the current directory on the server.
ftplib now supports context managers so I guess it can be made even easier
from ftplib import FTP
from pathlib import Path
file_path = Path('kitten.jpg')
with FTP('server.address.com', 'USER', 'PWD') as ftp, open(file_path, 'rb') as file:
ftp.storbinary(f'STOR {file_path.name}', file)
No need to close the file or the session
You will most likely want to use the ftplib module for python
import ftplib
ftp = ftplib.FTP()
host = "ftp.site.uk"
port = 21
ftp.connect(host, port)
print (ftp.getwelcome())
try:
print ("Logging in...")
ftp.login("yourusername", "yourpassword")
except:
"failed to login"
This logs you into an FTP server. What you do from there is up to you. Your question doesnt indicate any other operations that really need doing.
Try this:
#!/usr/bin/env python
import os
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('hostname', username="username", password="password")
sftp = ssh.open_sftp()
localpath = '/home/e100075/python/ss.txt'
remotepath = '/home/developers/screenshots/ss.txt'
sftp.put(localpath, remotepath)
sftp.close()
ssh.close()
To avoid getting the encryption error you can also try out below commands
ftp = ftplib.FTP_TLS("ftps.dummy.com")
ftp.login("username", "password")
ftp.prot_p()
file = open("filename", "rb")
ftp.storbinary("STOR filename", file)
file.close()
ftp.close()
ftp.prot_p() ensure that your connections are encrypted
I just answered a similar question here
IMHO, if your FTP server is able to communicate with Fabric please us Fabric. It is far better than doing raw ftp.
I have an FTP account from dotgeek.com so I am not sure if this will work for other FTP accounts.
#!/usr/bin/python
from fabric.api import run, env, sudo, put
env.user = 'username'
env.hosts = ['ftp_host_name',] # such as ftp.google.com
def copy():
# assuming i have wong_8066.zip in the same directory as this script
put('wong_8066.zip', '/www/public/wong_8066.zip')
save the file as fabfile.py and run fab copy locally.
yeukhon#yeukhon-P5E-VM-DO:~$ fab copy2
[1.ai] Executing task 'copy2'
[1.ai] Login password:
[1.ai] put: wong_8066.zip -> /www/public/wong_8066.zip
Done.
Disconnecting from 1.ai... done.
Once again, if you don't want to input password all the time, just add
env.password = 'my_password'
You can use the below function. I haven't tested it yet, but it should work fine. Remember the destination is a directory path where as source is complete file path.
import ftplib
import os
def uploadFileFTP(sourceFilePath, destinationDirectory, server, username, password):
myFTP = ftplib.FTP(server, username, password)
if destinationDirectory in [name for name, data in list(remote.mlsd())]:
print "Destination Directory does not exist. Creating it first"
myFTP.mkd(destinationDirectory)
# Changing Working Directory
myFTP.cwd(destinationDirectory)
if os.path.isfile(sourceFilePath):
fh = open(sourceFilePath, 'rb')
myFTP.storbinary('STOR %s' % f, fh)
fh.close()
else:
print "Source File does not exist"