I am new to Python and sorry for my bad english.
I'm trying to save a file "toto.txt" from my HDD "d:" to my Synology NAS.
So I'll use paramiko for this, here is the code :
import paramiko
import os
ip_address = "my nas ip"
username = "my username"
password = "mypass"
utilisateur = os.getenv("USERNAME") // to get Windows username
remote_path = f"{utilisateur}/test.txt" // the file downloaded
local_path = "d:/toto.txt" //the file stored on my pc
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(hostname=ip_address,username=username,password=password)
print("Connexion OK >", ip_address)
stdin, stdout, stderr = ssh_client.exec_command(f'mkdir {utilisateur}') //creating folder for the
user
sftp = ssh_client.open_sftp()
sftp.put(local_path,remote_path) // trying to send the file
sftp.close()
ssh_client.close()
i am not getting error but nothing is happening.
The folder is successful created but no file is sending in it.
Have someone an idea?
thanks a lot
If Paramiko does not throw any error, the upload was successful. The file just possibly ended in different location than you wanted/than you look to.
At least for a test, if not permanently, try an absolute absolute path. Make no guesses, use the exact path you see in your GUI SFTP client.
Another possibility is that the server automatically processes the uploaded file somehow and moves it away.
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.
Hi i have created a script , to send a file called office-data.txt on a ftp server , but I would like that this script, when the file is sended to a FTP server, must change its name randomly , only remotely ,for example office-data-12478.txt or office-data-22478.txt and the randomly generated name must never be the same each time the script starts , how can I modify this script to change the file name when it is sent to an FTP server ?
import ftplib
sftp = ftplib.FTP('ftp.example.com','userexample','passexample') # Connect
fp = open('office-data.txt','rb') # file to send
sftp.storbinary('STOR office-data.txt', fp) # Send the file
fp.close() # Close file and FTP
sftp.quit()
You can generate random names with UUID.
import uuid
sftp.storlines(filename + str(uuid.uuid4()), open(filename, 'r'))
You can use uuid or the current timestamp as milliseconds.
import ftplib
import uuid
unique_id = str(uuid.uuid4())
sftp = ftplib.FTP('ftp.exampple','userexample','passexample') # Connect
fp = open('office-data.txt','rb') # file to send
sftp.storbinary('STOR office-data-{0}.txt'.format(unique_id), fp) # Send the file
fp.close() # Close file and FTP
sftp.quit()
I am trying to download a file from FTP server. I am able to connect to the server. But not able to change the directory.
#! /user/bin/python33
import os
import ftplib
ftp = ftplib.FTP("ftp.sec.gov")
ftp.login("anonymous", "abcd#yahoo.com")
data = []
ftp.dir(data.append)
ftp.quit()
for line in data:
print( "-", line)
print(os.getcwd())
path= "/edgar/full-index/2013/"
print(path)
ftp.cwd(path)
it fails in the last line. can some one suggest what needs to be done"
thanks a lot in advance
Your cwd call fails because you previously called ftp.quit().
The docs for that method say:
Send a QUIT command to the server and close the connection. This is the “polite” way to close a connection, but it may raise an exception if the server responds with an error to the QUIT command. This implies a call to the close() method which renders the FTP instance useless for subsequent calls (see below).
(The "below" reference is to the next part of the documentation which says you can't do any operations on a closed FTP object.)
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"