Permissions denied renaming file with pysftp module - python

I'm new to Python and I writing a script that uses the pysftp module. There is one function in the pysftp module that I'm having trouble with -- it's the rename function.
Here is the call
srv = pysftp.Connection(host = 'xxx.com', username = 'xxx', password = 'xxx')
y = srv.rename('ftptest.txt', 'renamedfile.txt')
The error I'm getting is
Traceback (most recent call last):
File "./ftp.py", line 49, in <module>
y = srv.rename('ftptest.txt', 'renamedfile.txt')
File "/usr/local/lib/python2.7/dist-packages/pysftp.py", line 740, in rename
self._sftp.rename(remote_src, remote_dest)
File "/usr/local/lib/python2.7/dist-packages/paramiko/sftp_client.py", line 365, in rename
self._request(CMD_RENAME, oldpath, newpath)
File "/usr/local/lib/python2.7/dist-packages/paramiko/sftp_client.py", line 729, in _request
return self._read_response(num)
File "/usr/local/lib/python2.7/dist-packages/paramiko/sftp_client.py", line 776, in _read_response
self._convert_status(msg)
File "/usr/local/lib/python2.7/dist-packages/paramiko/sftp_client.py", line 804, in _convert_status
raise IOError(errno.EACCES, text)
IOError: [Errno 13] Permission denied
I have verified that the file exists and it has the 777 for permissions.

With SFTP protocol (which lacks concept of a current working directory), using an absolute paths is recommended. With a relative path, the result is server implementation specific. So you cannot be sure what files you are actually trying to rename.
On *nix systems, to rename a file, you need write permissions to a containing folder. The permissions to the file you are renaming do not matter.

Related

CherryPy Python error "No such file or directory"

Im trying to run a python Server using CherryPy for a WebSite but when I run it this error pops up.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/local/lib/python3.10/dist-packages/cherrypy/_cprequest.py", line 638, in respond
self._do_respond(path_info)
File "/usr/local/lib/python3.10/dist-packages/cherrypy/_cprequest.py", line 694, in _do_respond
self.hooks.run('before_handler')
File "/usr/local/lib/python3.10/dist-packages/cherrypy/_cprequest.py", line 95, in run
self.run_hooks(iter(sorted(self[point])))
File "/usr/local/lib/python3.10/dist-packages/cherrypy/_cprequest.py", line 117, in run_hooks
hook()
File "/usr/local/lib/python3.10/dist-packages/cherrypy/_cprequest.py", line 65, in __call__
return self.callback(**self.kwargs)
File "/usr/local/lib/python3.10/dist-packages/cherrypy/_cptools.py", line 280, in _lock_session
cherrypy.serving.session.acquire_lock()
File "/usr/local/lib/python3.10/dist-packages/cherrypy/lib/sessions.py", line 550, in acquire_lock
self.lock = zc.lockfile.LockFile(path)
File "/usr/local/lib/python3.10/dist-packages/zc/lockfile/__init__.py", line 117, in __init__
super(LockFile, self).__init__(path)
File "/usr/local/lib/python3.10/dist-packages/zc/lockfile/__init__.py", line 87, in __init__
fp = open(path, 'a+')
FileNotFoundError: [Errno 2] No such file or directory: '/var/www/html/cncsessions\\/session-73ab2ecbe9bd50153b4f20828fcc08bff6e9cd6e.lock'
It's my first time using this module and I don't know what's wrong.
I'm using Ubuntu 22, Python 3.10.6
Hard to say without seeing your exact code that this is calling.
Judging by the Error you are trying to use Sessions.
The sessions are looking for
/var/www/html/cncsessions
To place the session files in
But it gives an error. It looks like the path might be wrong. There's a double backslash at the end there and a forward slash.
\\/
If you haven't given up on this/figured it out already I would try changing this path to just this
/var/www/html/cncsessions
Also be sure you do not store your session data in your web root. Looks like from that path you might be doing that! Anything in a webroot will be served via public webserver. There's little to no chance anyone would guess the file names though.

executable generated from pyinstaller it's not working

I'm doing a program responsible for managing a bookstore and I'm at the end of it. I'm creating the executable from it, but it's giving an error when running I don't know what it is.
Error:
Traceback (most recent call last):
File "main.py", line 3494, in <module>
File "db_manager.py", line 278, in titulo_livros
File "pandas\io\parsers.py", line 605, in read_csv
File "pandas\io\parsers.py", line 457, in _read
File "pandas\io\parsers.py", line 814, in __init__
File "pandas\io\parsers.py", line 1045, in _make_engine
File "pandas\io\parsers.py", line 1862, in __init__
File "pandas\io\parsers.py", line 1357, in _open_handles
File "pandas\io\common.py", line 642, in get_handle
FileNotFoundError: [Errno 2] No such file or directory: 'livros.csv'
[432] Failed to execute script main
The command I am using to generate the exe file is "pyinstaller --onefile main.py".
And that is my tree folder:
my tree folder project
Please help me, i have no idea of what is going on.
Thank you very much in advance.
somewhere you are doing pandas.read_csv(fname) where fname='livros.csv'
you need to give it the right path to the csv (or bundle the csv into the executable ... but that probably doesnt make sense, im not sure why you would ever bundle the csv into the executable)
after alot of back and forth I think this is what you want
import os
import pandas
import sqlalchemy
from sqlalchemy import create_engine
db_path = os.path.expanduser('~/my_file.db')
engine = create_engine('sqlite:///'+db_path, echo=False)
try:
existing = pandas.read_sql('SELECT title, author FROM books', engine)
except:
existing = pandas.DataFrame({'title':['Title 1','Title 2'],'author':['Bob Roberts','Sam Spade']})
print("DBPATH:",db_path)
# ... do some stuff (add/edit/remove items from your dataframe)
existing.to_sql("books",engine)

“git.exc.GitCommandNotFound: [WinError 2] The system cannot find the file specified” error in Python 3.5

I am trying to lemmatize a Latin text using Python 3.5 in Pycharm 5.0.4 with the CLTK library, but there seems to be a problem with Git. I get the error git.exc.GitCommandNotFound: [WinError 2] The system cannot find the file specified among other errors I believe are related—see below for the full output. I have tried adding a Git repository to the project folder and adding the git.exe path to version control but that seems to have done nothing. What can I do to get Git to work properly—please keep in mind that I am a complete neophyte when it comes to Python in particular and not very experienced with programming in general.
Code:
from cltk.stem.lemma import LemmaReplacer
from cltk.stem.latin.j_v import JVReplacer
from cltk.corpus.utils.importer import CorpusImporter
corpus_importer = CorpusImporter('latin')
corpus_importer.import_corpus('latin_text_latin_library')
corpus_importer.import_corpus('latin_models_cltk')
#corpus_importer.import_corpus('phi5', '~/PHI5/')
#t.convert_corpus(corpus='phi5')
j = JVReplacer()
lemmatizer = LemmaReplacer('latin')
In = open("CIC.txt","rt")
Out = open("CIC4.txt","wt")
text = In.read()
text = text.lower()
text = j.replace(text)
Out.write(str(lemmatizer.lemmatize(text)))
In.close()
Out.close()
Output:
C:\Users\Rune\AppData\Local\Programs\Python\Python35-32\python.exe "C:\Program Files (x86)\JetBrains\PyCharm 5.0.4\helpers\pydev\pydevd.py" --multiproc --qt-support --client 127.0.0.1 --port 58508 --file C:/Users/Rune/PycharmProjects/untitled/Pucker.py
pydev debugger: process 14648 is connecting
Connected to pydev debugger (build 143.1919)
--- Logging error ---
Traceback (most recent call last):
File "C:\Users\Rune\AppData\Local\Programs\Python\Python35-32\lib\site-packages\git\cmd.py", line 604, in execute
**subprocess_kwargs
File "C:\Users\Rune\AppData\Local\Programs\Python\Python35-32\lib\subprocess.py", line 950, in __init__
restore_signals, start_new_session)
File "C:\Users\Rune\AppData\Local\Programs\Python\Python35-32\lib\subprocess.py", line 1220, in _execute_child
startupinfo)
File "C:\Program Files (x86)\JetBrains\PyCharm 5.0.4\helpers\pydev\pydev_monkey.py", line 387, in new_CreateProcess
return getattr(_subprocess, original_name)(appName, patch_arg_str_win(commandLine), *args)
FileNotFoundError: [WinError 2] The system cannot find the file specified
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Rune\AppData\Local\Programs\Python\Python35-32\lib\site-packages\cltk\corpus\utils\importer.py", line 134, in import_corpus
Repo.clone_from(git_uri, target_dir, depth=1)
File "C:\Users\Rune\AppData\Local\Programs\Python\Python35-32\lib\site-packages\git\repo\base.py", line 885, in clone_from
return cls._clone(git, url, to_path, GitCmdObjectDB, progress, **kwargs)
File "C:\Users\Rune\AppData\Local\Programs\Python\Python35-32\lib\site-packages\git\repo\base.py", line 826, in _clone
v=True, **add_progress(kwargs, git, progress))
File "C:\Users\Rune\AppData\Local\Programs\Python\Python35-32\lib\site-packages\git\cmd.py", line 450, in <lambda>
return lambda *args, **kwargs: self._call_process(name, *args, **kwargs)
File "C:\Users\Rune\AppData\Local\Programs\Python\Python35-32\lib\site-packages\git\cmd.py", line 878, in _call_process
return self.execute(make_call(), **_kwargs)
File "C:\Users\Rune\AppData\Local\Programs\Python\Python35-32\lib\site-packages\git\cmd.py", line 607, in execute
raise GitCommandNotFound(str(err))
git.exc.GitCommandNotFound: [WinError 2] The system cannot find the file specified
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Rune\AppData\Local\Programs\Python\Python35-32\lib\logging\__init__.py", line 980, in emit
msg = self.format(record)
File "C:\Users\Rune\AppData\Local\Programs\Python\Python35-32\lib\logging\__init__.py", line 830, in format
return fmt.format(record)
File "C:\Users\Rune\AppData\Local\Programs\Python\Python35-32\lib\logging\__init__.py", line 567, in format
record.message = record.getMessage()
File "C:\Users\Rune\AppData\Local\Programs\Python\Python35-32\lib\logging\__init__.py", line 330, in getMessage
msg = msg % self.args
TypeError: not enough arguments for format string
Call stack:
File "C:\Program Files (x86)\JetBrains\PyCharm 5.0.4\helpers\pydev\pydevd.py", line 2411, in <module>
globals = debugger.run(setup['file'], None, None, is_module)
File "C:\Program Files (x86)\JetBrains\PyCharm 5.0.4\helpers\pydev\pydevd.py", line 1802, in run
launch(file, globals, locals) # execute the script
File "C:\Program Files (x86)\JetBrains\PyCharm 5.0.4\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Users/Rune/PycharmProjects/untitled/Pucker.py", line 5, in <module>
corpus_importer.import_corpus('latin_text_latin_library')
File "C:\Users\Rune\AppData\Local\Programs\Python\Python35-32\lib\site-packages\cltk\corpus\utils\importer.py", line 136, in import_corpus
logger.error("Git clone of '%s' failed: '%s'", (git_uri, e))
Message: "Git clone of '%s' failed: '%s'"
Arguments: (('https://github.com/cltk/latin_text_latin_library.git', GitCommandNotFound('[WinError 2] The system cannot find the file specified',)),)
Process finished with exit code 0
You can manually download the corpus from https://github.com/cltk/latin_models_cltk and place it in the
~/cltk_data/latin/model/ folder (so ~/cltk_data/latin/model/latin_models_cltk/lemmata/ is an existing folder afterwards). Then you should be able to run the following just fine:
from cltk.stem.lemma import LemmaReplacer
LemmaReplacer('latin').lemmatize('some_latin_here')
For the same in Greek, just replace the 'latin' by 'greek' everywhere in these instructions. I imagine (but haven't tried) that it works the same for other languages too.
I am pretty sure that CLTK does not work with any Python version below 3.6, at least as of August 2017. I had a devil of a time getting 3.6 installed on Ubuntu (Ubuntu linus running dual boot from my PC laptop) but eventually got it to work. Also I specifically solved the problem that OP articulates above by following the instructions at https://disiectamembra.wordpress.com/2016/07/01/current-state-of-the-cltk-latin-lemmatizer/. Good luck!

Python SFTP File Not Found Errors

I'm attempting to download all the files in an SFTP directory to a local folder using the pysftp library. My code looks like this:
import pysftp
sftp = pysftp.Connection('server', username = 'name', password = 'password')
sftp.get_d('Daily_Reports', '/home/jchrysostom/Documents/SupplyChain/Daily_Reports/')
Daily_Reports is a folder that exists on the SFTP server - I have verified this. I have also verified that /home/jchrysostom/Documents/SupplyChain/Daily_Reports/ exists. I can cd to it in terminal with no problems.
However, when I run this python script, I get the following error: IOError: [Errno 2] File not found.
Any ideas what may be causing this?
UPDATE: A little investigation shows that the files actually have downloaded. In fact, all of them have downloaded just fine. However, I'm unable to run the rest of the script, because it's erroring out for some reason. Is this just a bug in the library?
UPDATE 2 - Full Traceback, as requested:
Traceback (most recent call last):
File "supplychain.py", line 20, in <module>
sftp.get_d('Daily_Reports','/home/jchrysostom/Documents/SupplyChain/Daily_Reports/')
File "/usr/local/lib/python2.7/dist-packages/pysftp.py", line 255, in get_d
preserve_mtime=preserve_mtime)
File "/usr/lib/python2.7/contextlib.py", line 24, in __exit__
self.gen.next()
File "/usr/local/lib/python2.7/dist-packages/pysftp.py", line 497, in cd
self.cwd(original_path)
File "/usr/local/lib/python2.7/dist-packages/pysftp.py", line 510, in chdir
self._sftp.chdir(remotepath)
File "/usr/local/lib/python2.7/dist-packages/paramiko/sftp_client.py", line 580, in chdir
if not stat.S_ISDIR(self.stat(path).st_mode):
File "/usr/local/lib/python2.7/dist-packages/paramiko/sftp_client.py", line 413, in stat
t, msg = self._request(CMD_STAT, path)
File "/usr/local/lib/python2.7/dist-packages/paramiko/sftp_client.py", line 729, in _request
return self._read_response(num)
File "/usr/local/lib/python2.7/dist-packages/paramiko/sftp_client.py", line 776, in _read_response
self._convert_status(msg)
File "/usr/local/lib/python2.7/dist-packages/paramiko/sftp_client.py", line 802, in _convert_status
raise IOError(errno.ENOENT, text)
IOError: [Errno 2] File not found
As best as I can tell, this is a bug in pysftp. The files are being copied successfully, but (at least according to the traceback here) the library is blowing up when it tries to change back to the original remote working directory on the FTP server.
Workaround is to iterate over the files in the directory and get() each individually...
for filename in sftp.listdir('Daily_Reports'):
sftp.get('Daily_Reports/' + filename, localpath = '/home/jchrysostom/Documents/SupplyChain/Daily_Reports/' + filename)

Shelve.open failing on creation

I'm having trouble using shelve on my dev server. My local machine will create a new file just fine when I call shelve.open(). But when I push the file to the remote server, an error happens. It looks like it is trying to find the file first and it's failing because it isn't there. I'm not changing the file extension. My local machine is Ubuntu 14 and my remote is CentOS 6. Here is the python stack trace. Python 2.6.
File "/var/lib/jenkins/................/translation.py", line 51, in _market
lang_db = shelve.open(market + "_pydb")
File "/usr/lib64/python2.6/shelve.py", line 239, in open
return DbfilenameShelf(filename, flag, protocol, writeback)
File "/usr/lib64/python2.6/shelve.py", line 223, in __init__
Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback)
File "/usr/lib64/python2.6/anydbm.py", line 83, in open
return mod.open(file, flag, mode)
File "/usr/lib64/python2.6/dbhash.py", line 19, in open
return bsddb.hashopen(file, flag, mode)
File "/usr/lib64/python2.6/bsddb/__init__.py", line 361, in hashopen
d.open(file, db.DB_HASH, flags, mode)
DBNoSuchFileError: (2, 'No such file or directory')
For the record, I changed the default to dumbdbm and it's still giving me an IO error (file not found).
import anydbm
anydbm._defaultmod = __import__('dumbdbm')
I found out that when I was pushing to the repository, git wasn't including the directory I was looking in because it was empty. If you try to use shelve.open with an argument that is in a directory that doesn't exist, it will give you an IO error. I simply forced the creation of the directory and now it works.

Categories