I am looking for a specific file within a folder on FTP. There are several folders and my code loops through each folder to find the file. Once, I find the file I would like to download it.
import ftplib
import os, sys, os.path
ftp = ftplib.FTP("xxxxxxxx")
ftp.login("dbaxyz", "password123")
files = []
try:
files = ftp.nlst()
except ftplib.error_perm, resp:
if str(resp) == "550 No files found":
print "No files in this directory"
else:
raise
for f in files:
filess = [],
filess=ftp.nlst(f)
for i in filess:
if len(i)==34 and i[8:11]=="ACO" and i[12:17]=="CCLF9" and i[3:7]=="1263" :
print i
local_filename = os.path.join('C:\\Users\\zubair.zahiruddin\\Desktop\\test', i)
file = open(local_filename, 'wb')
ftp.retrbinary('RETR '+ i, file.write)
file.close()
ftp.close()
#ftp.quit()
However, I get an error: perm file not found.
Traceback (most recent call last):
File "ftp.py", line 28, in <module>
ftp.retrbinary('RETR '+ i, file.write)
File "C:\Python27\lib\ftplib.py", line 414, in retrbinary
conn = self.transfercmd(cmd, rest)
File "C:\Python27\lib\ftplib.py", line 376, in transfercmd
return self.ntransfercmd(cmd, rest)[0]
File "C:\Python27\lib\ftplib.py", line 339, in ntransfercmd
resp = self.sendcmd(cmd)
File "C:\Python27\lib\ftplib.py", line 249, in sendcmd
return self.getresp()
File "C:\Python27\lib\ftplib.py", line 224, in getresp
raise error_perm, resp
ftplib.error_perm: 550 The system cannot find the file specified.
PS C:\Users\zubair.zahiruddin\Desktop\test>
Related
I have problem to download files from my private chat.
I've added a bot as administrator to my private chat. To upload on telegram with a python script I have no problems, for example I use successfully this code
import os
import telegram
# Enter your bot's token here
TOKEN = "58819**********************....."
# Enter your private chat ID here
CHAT_ID = -100****...
# Enter the path to the document here
DOCUMENT_PATH = "C:\\temp\\telegram\\snow.epub"
# Create a Bot object using the token
bot = telegram.Bot(token=TOKEN)
# Open the document in binary mode
with open(DOCUMENT_PATH, "rb") as f:
# Send the document to the specified chat
bot.send_document(chat_id=CHAT_ID, document=f)
print("Document sent successfully!")
Problem is download this file (an epub file) from my private chat
i try with this code but nothing happens, powershell returns me this message
PS C:\temp\telegram> python scaricare2.py
The last sent message is not a document.
I test with this code
import os
import os.path
import telegram
# Enter your bot's token here
TOKEN = "588199*****************..."
# Enter your private chat ID here
CHAT_ID = -1001******...
# Create a Bot object using the token
bot = telegram.Bot(token=TOKEN)
# Download the latest file sent in the chat
updates = bot.get_updates(offset=-1, limit=1)
if updates:
# Checks if the Message object contains a document attribute
if hasattr(updates[0].message, "document"):
file_id = updates[0].message.document.file_id
else:
print("The last sent message is not a document.")
exit()
file_info = bot.get_file(file_id)
file = bot.download_file(file_info.file_path)
# Create the path to the directory where to save the file
download_path = "C:/temp/telegram/filexx/"
# Create the full path to the file using the file name
file_path = os.path.join(download_path, file_info.file_name)
# Open the file in binary write mode
with open(file_path, "wb") as f:
# Write the contents of the file to the specified path
f.write(file)
print("File downloaded successfully!")
else:
print("The last sent message is not a document.")
Any idea to solve ?
Download from bot returns this error
PS C:\temp\telegram> python scaricare2.py
Traceback (most recent call last):
File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 402, in _make_request
six.raise_from(e, None)
File "<string>", line 2, in raise_from
File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 398, in _make_request
httplib_response = conn.getresponse()
File "C:\Program Files\Python310\lib\http\client.py", line 1374, in getresponse
response.begin()
File "C:\Program Files\Python310\lib\http\client.py", line 318, in begin
version, status, reason = self._read_status()
File "C:\Program Files\Python310\lib\http\client.py", line 279, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "C:\Program Files\Python310\lib\socket.py", line 705, in readinto
return self._sock.recv_into(b)
File "C:\Program Files\Python310\lib\ssl.py", line 1273, in recv_into
return self.read(nbytes, buffer)
File "C:\Program Files\Python310\lib\ssl.py", line 1129, in read
return self._sslobj.read(len, buffer)
TimeoutError: The read operation timed out
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Program Files\Python310\lib\site-packages\telegram\utils\request.py", line 259, in _request_wrapper
resp = self._con_pool.request(*args, **kwargs)
File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\request.py", line 68, in request
return self.request_encode_body(method, url, fields=fields,
File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\request.py", line 148, in request_encode_body
return self.urlopen(method, url, **extra_kw)
File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\poolmanager.py", line 244, in urlopen
response = conn.urlopen(method, u.request_uri, **kw)
File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 665, in urlopen
retries = retries.increment(method, url, error=e, _pool=self,
File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\util\retry.py", line 347, in increment
raise six.reraise(type(error), error, _stacktrace)
File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\packages\six.py", line 686, in reraise
raise value
File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 614, in urlopen
httplib_response = self._make_request(conn, method, url,
File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 404, in _make_request
self._raise_timeout(err=e, url=url, timeout_value=read_timeout,
File "C:\Program Files\Python310\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 321, in _raise_timeout
raise exc_cls(*args)
telegram.vendor.ptb_urllib3.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='api.telegram.org', port=443): Read timed out. (read timeout=5.0)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\temp\telegram\scaricare2.py", line 24, in <module>
file_info = bot.get_file(file_id)
File "C:\Program Files\Python310\lib\site-packages\telegram\bot.py", line 134, in decorator
result = func(*args, **kwargs)
File "C:\Program Files\Python310\lib\site-packages\telegram\bot.py", line 2510, in get_file
result = self._post('getFile', data, timeout=timeout, api_kwargs=api_kwargs)
File "C:\Program Files\Python310\lib\site-packages\telegram\bot.py", line 299, in _post
return self.request.post(
File "C:\Program Files\Python310\lib\site-packages\telegram\utils\request.py", line 361, in post
result = self._request_wrapper(
File "C:\Program Files\Python310\lib\site-packages\telegram\utils\request.py", line 261, in _request_wrapper
raise TimedOut() from error
telegram.error.TimedOut: Timed out
I am currently trying to copy a file from a server to a local file. Below is my current code. I am currently generating the following error, [Errno 13] Permission denied. I believe this is associated with the remote path. Any ideas?
import os
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='de.ac.uk', username="hfseb", password="kjsvbkjcb")
sftp = ssh.open_sftp()
localpath = '/Users/abc/def'
remotepath = '/home/abc/def/game.log'
sftp.put(localpath, remotepath)
sftp.close()
ssh.close()
Error generated
Traceback (most recent call last):
File "C:\Users\abc\python\ssh1.py", line 15, in
sftp.put(localpath, remotepath)
File "C:\Users\abc\python\paramiko\sftp_client.py", line 759, in put
return self.putfo(fl, remotepath, file_size, callback, confirm)
File "C:\Users\abc\python\paramiko\sftp_client.py", line 714, in putfo
with self.file(remotepath, "wb") as fr:
File "C:\Users\abc\python\paramiko\sftp_client.py", line 372, in open
t, msg = self._request(CMD_OPEN, filename, imode, attrblock)
File "C:\Users\abc\python\paramiko\sftp_client.py", line 813, in _request
return self._read_response(num)
File "C:\Users\abc\python\paramiko\sftp_client.py", line 865, in _read_response
self._convert_status(msg)
File "C:\Users\abc\python\paramiko\sftp_client.py", line 896, in _convert_status
raise IOError(errno.EACCES, text)
Probably the remote def directory have wrong permissions.
I am able to connect the sftp with pysftp successfully, but getting error while downloading file as FileNotFoundError: [Errno 2] No such file. I also observed that the file is just creating at local path adding '?' along with extension. Below are more details.
File at ftp as Test_03132018080105.csv.
File creating at Local path as Test_03132018080105.csv? with zero bytes
Code:
def get_move_on_ftp(ftpsource,localsource):
if (os.stat(envvar.validfiles).st_size == 0) and (os.stat(envvar.invalidfiles).st_size == 0):
print("There are no Source files on FTP.")
else:
srcinfo={'host':envvar.src_ftphost,'port':envvar.src_ftpport,'username':envvar.src_uname,'password':envvar.src_passwd}
sftp = pysftp.Connection(**srcinfo)
sftp.cwd(ftpsource)
''' Downloading Files '''
avail_files=open(envvar.validfiles,'r')
for filename in avail_files:
print(sftp.getcwd())
#sftp.get(filename, preserve_mtime=True)
print(filename) # for debug
sftp.get(filename)
sftp.close()
Error:
Traceback (most recent call last):
File "my.py", line 96, in <module>
main()
File "my.py", line 92, in main
config_file_read(config_file)
File "my.py", line 85, in config_file_read
get_move_on_ftp(ftpsource,localsource)
File "my.py", line 61, in get_move_on_ftp
sftp.get(filename)
File "/home/username/miniconda3/lib/python3.6/site-packages/pysftp/__init__.py", line 249, in get
self._sftp.get(remotepath, localpath, callback=callback)
File "/home/username/miniconda3/lib/python3.6/site-packages/paramiko/sftp_client.py", line 770, in get
size = self.getfo(remotepath, fl, callback)
File "/home/username/miniconda3/lib/python3.6/site-packages/paramiko/sftp_client.py", line 746, in getfo
file_size = self.stat(remotepath).st_size
File "/home/username/miniconda3/lib/python3.6/site-packages/paramiko/sftp_client.py", line 460, in stat
t, msg = self._request(CMD_STAT, path)
File "/home/username/miniconda3/lib/python3.6/site-packages/paramiko/sftp_client.py", line 780, in _request
return self._read_response(num)
File "/home/username/miniconda3/lib/python3.6/site-packages/paramiko/sftp_client.py", line 832, in _read_response
self._convert_status(msg)
File "/home/username/miniconda3/lib/python3.6/site-packages/paramiko/sftp_client.py", line 861, in _convert_status
raise IOError(errno.ENOENT, text)
FileNotFoundError: [Errno 2] No such file
Just add "/" in front of ftpsource. i.e. "/2020/Jan/10/". It should work
I was trying this FTP file transfer code. The thing is that when I had run this code on an online environment(a workspace that I created on Cloud 9) then it worked fine and uploaded the file but when I run this on my PC I get an ERROR. How can I resolve it?
from ftplib import FTP
ftp=FTP('**domain**')
ftp.login(user='username',passwd='password')
ftp.cwd('/')
def grabFile():
filename='fileName.txt'
localfile=open(filename, 'wb')
ftp.retrbinary('RETR '+filename, localfile.write, 1024)
ftp.quit()
localfile.close()
def placeFile():
filename= 'Strinzy.txt'
ftp.storbinary('STOR '+filename, open(filename,'rb'))
ftp.quit()
placeFile()
ERROR:
Traceback (most recent call last):
File "ftp_trial.py", line 19, in <module>
placeFile()
File "ftp_trial.py", line 16, in placeFile
ftp.storbinary('STOR '+filename, open(filename,'rb'))
File "/usr/lib/python2.7/ftplib.py", line 468, in storbinary
conn = self.transfercmd(cmd, rest)
File "/usr/lib/python2.7/ftplib.py", line 373, in transfercmd
return self.ntransfercmd(cmd, rest)[0]
File "/usr/lib/python2.7/ftplib.py", line 332, in ntransfercmd
conn = socket.create_connection((host, port), self.timeout)
File "/usr/lib/python2.7/socket.py", line 571, in create_connection
raise err
socket.error: [Errno 113] No route to host
If you are using vsftpd then make sure your vsftpd service is running in your machine and /etc/vsftpd.userlist has username in it.
I am trying to download all images of a particular wikipedia page. Here is the code snippet
from bs4 import BeautifulSoup as bs
import urllib2
import urlparse
from urllib import urlretrieve
site="http://en.wikipedia.org/wiki/Pune"
hdr= {'User-Agent': 'Mozilla/5.0'}
outpath=""
req = urllib2.Request(site,headers=hdr)
page = urllib2.urlopen(req)
soup =bs(page)
tag_image=soup.findAll("img")
for image in tag_image:
print "Image: %(src)s" % image
urlretrieve(image["src"], "/home/mayank/Desktop/test")
While after running the program I see error with following stack
Image: //upload.wikimedia.org/wikipedia/commons/thumb/0/04/Pune_Montage.JPG/250px-Pune_Montage.JPG
Traceback (most recent call last):
File "download_images.py", line 15, in <module>
urlretrieve(image["src"], "/home/mayank/Desktop/test")
File "/usr/lib/python2.7/urllib.py", line 93, in urlretrieve
return _urlopener.retrieve(url, filename, reporthook, data)
File "/usr/lib/python2.7/urllib.py", line 239, in retrieve
fp = self.open(url, data)
File "/usr/lib/python2.7/urllib.py", line 207, in open
return getattr(self, name)(url)
File "/usr/lib/python2.7/urllib.py", line 460, in open_file
return self.open_ftp(url)
File "/usr/lib/python2.7/urllib.py", line 543, in open_ftp
ftpwrapper(user, passwd, host, port, dirs)
File "/usr/lib/python2.7/urllib.py", line 864, in __init__
self.init()
File "/usr/lib/python2.7/urllib.py", line 870, in init
self.ftp.connect(self.host, self.port, self.timeout)
File "/usr/lib/python2.7/ftplib.py", line 132, in connect
self.sock = socket.create_connection((self.host, self.port), self.timeout)
File "/usr/lib/python2.7/socket.py", line 571, in create_connection
raise err
IOError: [Errno ftp error] [Errno 111] Connection refused
please help on what is causing this error?
// is shorthand for the current protocol. It seems like Wikipedia is using the shorthand, so you have to explicitly specify HTTP instead of FTP (which Python is assuming for some reason):
for image in tag_image:
src = 'http:' + image