PermissionError: [Errno 13] Permission denied while running a server-side CGI scripts coded in Python - python-3.x

I am trying to run a server-side cgi script coded in python but I am getting the following error while running it.
Traceback (most recent call last):
File "webserver.py", line 16, in <module>
srvrobj = HTTPServer(srvraddr,CGIHTTPRequestHandler)
File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 449, in __init__
self.server_bind()
File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/server.py", line 137, in server_bind
socketserver.TCPServer.server_bind(self)
File "/usr/local/Cellar/python/3.7.0/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socketserver.py", line 463, in server_bind
self.socket.bind(self.server_address)
PermissionError: [Errno 13] Permission denied
Here is the script that I am trying to run.
"""
Implement an HTTP web server in Python that knows how to run server-side
CGI scripts coded in Python; serves files and scripts from current working
dir; Python scripts must be stored in webdir\cgi-bin or webdir\htbin;
"""
import os,sys
from http.server import HTTPServer, CGIHTTPRequestHandler
webdir = '.'
port = 80 #default http://localhost/, else use http://localhost:xxxx/
os.chdir(webdir)
srvraddr = ("",port)
srvrobj = HTTPServer(srvraddr,CGIHTTPRequestHandler)
srvrobj.serve_forever()
Any help will be appreciated. Thanks in advance.

Use this
chmod 777 script_name,
then execute the script if it fails again then use
sudo python script_name
or check how to run script using administrator privileges on your respective operating system.

Related

Install ssl certificates for discord.py in an app

I am making a python-based mac app that uses discord.py to do stuff with discord. As I knew from previous experience making discord bots, running discord bots requires that you run Install Certificates.command in your version of python. However, if another users uses this app, I don't want to require them to install python. I took a snippet of code from Install Certificates.command, thinking it would put the certificate in the right place on a user's computer. However, a tester got this error running the app on their computer:
Traceback (most recent call last):
File "Interface.py", line 136, in <module>
File "installCerts.py", line 25, in installCerts
FileNotFoundError: [Errno 2] No such file or directory: '/Library/Frameworks/Python.framework/Versions/3.8/etc/openssl'
[2514] Failed to execute script 'Interface' due to unhandled exception: [Errno 2] No such file or directory: '/Library/Frameworks/Python.framework/Versions/3.8/etc/openssl'
[2514] Traceback:
Traceback (most recent call last):
File "Interface.py", line 136, in <module>
File "installCerts.py", line 25, in installCerts
FileNotFoundError: [Errno 2] No such file or directory: '/Library/Frameworks/Python.framework/Versions/3.8/etc/openssl'
It's pretty clear what this error is saying: They don't have python (3.8) installed, so it can't put the ssl certificates anywhere (this is because the app is running in a python 3.8 environment).
By the way, the path mentioned in the error is the directory name of the path given by ssl.get_default_verify_paths().openssl_cafile.
I'm not super well-versed in the finer points of web connections and stuff like that, so I don't know the exact role of these certificates. Here's my question:
Is it possible to get this to work without the user installing python on their computer?
I.e. Can I add the ssl certificates to the app's local python version (as far as I can tell, in my app, python is simply a large bundled exec file)? Is there somewhere deep in the file system where I can put the certificates to let the connection to discord happen? . Pretty much any solution would be appreciated.
Additional Info:
My Code to Install Certificates:
STAT_0o775 = (stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
| stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP
| stat.S_IROTH | stat.S_IXOTH)
openssl_dir, openssl_cafile = os.path.split(
ssl.get_default_verify_paths().openssl_cafile)
os.chdir(openssl_dir) #Error happens here
relpath_to_certifi_cafile = os.path.relpath(certifi.where())
print(" -- removing any existing file or link")
try:
os.remove(openssl_cafile)
except FileNotFoundError:
pass
print(" -- creating symlink to certifi certificate bundle")
os.symlink(relpath_to_certifi_cafile, openssl_cafile)
print(" -- setting permissions")
os.chmod(openssl_cafile, STAT_0o775)
print(" -- update complete")
The error that discord.py throws when the user doesn't have correct certificates installed:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/aiohttp/connector.py", line 969, in _wrap_create_connection
return await self._loop.create_connection(*args, **kwargs) # type: ignore # noqa
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/base_events.py", line 1050, in create_connection
transport, protocol = await self._create_connection_transport(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/base_events.py", line 1080, in _create_connection_transport
await waiter
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/sslproto.py", line 529, in data_received
ssldata, appdata = self._sslpipe.feed_ssldata(data)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/asyncio/sslproto.py", line 189, in feed_ssldata
self._sslobj.do_handshake()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ssl.py", line 944, in do_handshake
self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1125)
If you need more info, let me know.
Ok. This was very tough, but I got to an answer after much research. ssl in python is basically just a set of bindings for openSSL. When you do import ssl, it builds an openSSL environment (I don't think I'm using the exact right words here). As you could see, it was defaulting to the openSSL folder in Python because from python's perspective, that is where openSSL keeps its certs. Turns out, ssl.DefaultVerifyPaths objects have other attributes, namely cafile. This was how I made the path to the cert whatever I wanted. You see, when openSSL builds, it looks for an environment variable SSL_CERT_FILE. As long as I set that variable with os.environ before I imported ssl, it would work, because ssl would find the certificate. I simplified installCerts down to the following:
import os
import stat
import certifi
def installCerts():
os.environ['SSL_CERT_FILE'] = certifi.where()
import ssl
# ssl build needs to happen after enviro var is set
STAT_0o775 = (stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
| stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP
| stat.S_IROTH | stat.S_IXOTH)
cafile = ssl.get_default_verify_paths().cafile
os.chmod(cafile, STAT_0o775)
And it seems to work fine on other people's computers now without them needing to install python.
This question helped me:
How to change the 'cafile' argument in the ssl module in Python3?

FileNotFoundError while using crontab to run Python script

I'm totally lost here. I'm trying to create a scheduler to run python script on my Mac, but I'm getting the following error:
Traceback (most recent call last):
File "/Users/Root/Desktop/Project/Data/script.py", line 148, in <module>
run(
File "/Users/Root/Desktop/Project/Data/script.py", line 121, in run
config = get_config("config")
File "/Users/Root/Desktop/Project/Data/config/__init__.py", line 3, in get_config
with open(f"config/{config_type}.json", "r") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'config/config.json'
So crontab convinces me that there is no such file or a directory, which is not true. I can run my script manually without errors.
My crontab is:
00 19 21 1-12 * /Library/Frameworks/Python.framework/Versions/3.9/bin/python3/ /Users/Root/Desktop/Project/Data/script.py >> /Users/Root/Desktop/Project/Data/cron.txt 2>&1
What am I doing wrong?
I'd be grateful for any help!
And is this possible without changing the relative path to an absolute path? I am aware of this solution
I assume crontab's cwd (Current Working Directory) is not same as where the script is stored.
this would solve your problem:
import os
script_dir = os.path.dirname(os.path.realpath(__file__))
os.chdir(script_dir)
You can get the directory where you script is by calling "os.path.dirname(os.path.realpath(file))"
if you change the current working directory "os.chdir(...dir...)" you can access you config/config.json by relative path,
Otherwise you will have to use a absolute path
Try running this and check your output file:
import os
script_dir = os.path.dirname(os.path.realpath(__file__))
print (os.getcwd())
print(script_dir)
os.chdir(script_dir)
print (os.getcwd())
Try to open with full path to the json file.

Permission denied while downloading dataset from Kaggle API

I am using Google cloud services and I want to download kaggle dataset. I have followed the standard ways for authentication but still, I am getting "Permission denied" error
My approach:
I have tried the following method:
(1) Installing kaggle using pip
(2) placing the kaggle.json file in /.kaggle directory
(3) ''' chmod 600 /home/rushirajparmar23000/.kaggle/kaggle.json '''
(4) ''' echo '{"username":"USERNAME","key":"KEY"}' >/root/.kaggle/kaggle.json '''
error : -bash: /root/.kaggle/kaggle.json: Permission denied
(5) kaggle competitions download -c facebook-recruiting-iii-keyword-extraction
error: raise ValueError('Error: Missing %s in configuration.' % item)
ValueError: Error: Missing username in configuration.
Maybe this discussion in the kaggle forum might answer your question:
https://www.kaggle.com/general/51898
It has a script you can run to do what you want.
When I wanted to download a dataset, I got this error. (I think it's related to your question)
Traceback (most recent call last):
File "/home/matin/.local/bin/kaggle", line 5, in <module>
from kaggle.cli import main
File "/home/matin/.local/lib/python3.9/site-packages/kaggle/__init__.py", line 19, in <module>
from kaggle.api.kaggle_api_extended import KaggleApi
File "/home/matin/.local/lib/python3.9/site-packages/kaggle/api/__init__.py", line 22, in <module>
from kaggle.api.kaggle_api_extended import KaggleApi
File "/home/matin/.local/lib/python3.9/site-packages/kaggle/api/kaggle_api_extended.py", line 84, in <module>
class KaggleApi(KaggleApi):
File "/home/matin/.local/lib/python3.9/site-packages/kaggle/api/kaggle_api_extended.py", line 102, in KaggleApi
os.makedirs(config_dir)
File "/home/matin/miniconda3/lib/python3.9/os.py", line 225, in makedirs
mkdir(name, mode)
PermissionError: [Errno 13] Permission denied: '/kaggle.json'
Solution
sudo mkdir /.kaggle
sudo cp kaggle.json /.kaggle
sudo chmod 600 /.kaggle/kaggle.json
sudo chown `whoami`: /.kaggle/kaggle.json
export KAGGLE_CONFIG_DIR='/.kaggle/'
Explanation
In KaggleApi source code, it's trying to find a directory from the environment.
config_dir = os.environ.get('KAGGLE_CONFIG_DIR') or os.path.join(
expanduser('~'), '.kaggle')
if not os.path.exists(config_dir):
os.makedirs(config_dir)
So if you add KAGGLE_CONFIG_DIR to your environment, it doesn't try to make a directory!
If you got ValueError: Error: Missing username in configuration., you should just change the owner by using chown command.
This worked for me
removed the .kaggle directory that was created when installing the kaggle API:
rm -r .kaggle/
created a new .kaggle directory in the home directory:
mkdir .kaggle
downloaded the kaggle.json file from my kaggle account:
copied the kaggle.json to .kaggle/:
cp ~/Downloads/kaggle.json .kaggle/
chmod 600 .kaggle/kaggle.json

Permission Error Permission Denied In simple basic Flask Application

I'm running this script on vagrant based Linux system, It's a simple basic code for running flask app, I'm getting this error:
raise child_exception_type(errno_num, err_msg)
PermissionError: [Errno 13] Permission denied
Here is the script:
#!/usr/bin python3
from flask import Flask
app = Flask(__name__)
#app.route('/')
#app.route('/hello')
def helloworld():
return 'Hello and Welcome to flask'
if __name__ == '__main__':
app.debug = True
app.run(host='0.0.0.0', port=5000)
And the error I got:
vagrant#vagrant:/vagrant$ python3 project.py
* Serving Flask app "project" (lazy loading)
* Environment: production
WARNING: Do not use the development server in a production environment.
Use a production WSGI server instead.
* Debug mode: on
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
* Restarting with stat
Traceback (most recent call last):
File "project.py", line 14, in <module>
app.run(host='0.0.0.0', port=5000)
File "/usr/local/lib/python3.5/dist-packages/flask/app.py", line 943, in run run_simple(host, port, self, **options)
File "/usr/local/lib/python3.5/dist-packages/werkzeug/serving.py", line 988, in run_simple
run_with_reloader(inner, extra_files, reloader_interval, reloader_type)
File "/usr/local/lib/python3.5/dist-packages/werkzeug/_reloader.py", line 332, in run_with_reloader
sys.exit(reloader.restart_with_reloader())
File "/usr/local/lib/python3.5/dist-packages/werkzeug/_reloader.py", line 176, in restart_with_reloader
exit_code = subprocess.call(args, env=new_environ, close_fds=False)
File "/usr/lib/python3.5/subprocess.py", line 557, in call
with Popen(*popenargs, **kwargs) as p:
File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child
raise child_exception_type(errno_num, err_msg)
PermissionError: [Errno 13] Permission denied
I had the same problem, it turns out that the port needs to be greater than 5000:
from flask import Flask, request, abort, jsonify
app = Flask(__name__)
#app.route('/getSquare', methods=['POST'])
def get_square():
pass
return jsonify({'answer': num ** 2})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5001, debug=True) # make sure port is > 5000
Maybe it's a permission error since Vagrant is trying to run your flask application and doesn't have the necessary executable permission?
I say this because of this part of your stack trace:
PermissionError: [Errno 13] Permission denied
and appears to be failing on this line of code: app.run(host='0.0.0.0', port=5000)
Perhaps you could give executable permissions on your directory containing your flask project and see if that helps resolve your issue:
chmod -R 755 /path/to/directory
Hopefully that helps!
Since you're playing in a VM that you built using Vagrant, you must have done something like
vagrant#vagrant:/vagrant$ sudo pip3 install flask
first. Possibly you installed some other packages. Depending on what base OS you're using, using pip (or pip3) to install at the system level (even in a VM) can cause problems.
After wrestling with my base install getting mangled a few time, I now always use virtualenv inside of VMs so that all of the package installs are local.
I'll bet that
vagrant#vagrant:/vagrant$ sudo apt-get install -y python-virtualenv
vagrant#vagrant:/vagrant$ virtualenv --python=python3 venv
vagrant#vagrant:/vagrant$ venv/bin/pip install flask
vagrant#vagrant:/vagrant$ ven/bin/python project.py
will give you a better result.

Python Selenium "Can not connect to the Service %s" % self.path in linux server

Traceback (most recent call last):
File "testing.py", line 20, in <module>
driver = webdriver.Chrome(executable_path="/home/cavema11/public_html/testing.py")
File "/opt/python-3.6.4/lib/python3.6/site-packages/selenium/webdriver/chrome/webdriver.py", line 68, in __init__
self.service.start()
File "/opt/python-3.6.4/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 104, in start
raise WebDriverException("Can not connect to the Service %s" % self.path)
selenium.common.exceptions.WebDriverException: Message: Can not connect to the Service /home/cavema11/public_html/testing.py
I have 127.0.0.1 localhost in my /etc/hosts but still getting this errors.
Please help me.
Thank you
Through the argument executable_path you need to pass the absolute path of the ChromeDriver instead of any other file. So you need to change:
driver = webdriver.Chrome(executable_path="/home/cavema11/public_html/testing.py")
To:
driver = webdriver.Chrome(executable_path='/path/to/chromedriver')
Update
Ensure that you have downloaded the exact format of the ChromeDriver binary from the download location pertaining to your underlying OS among:
chromedriver_linux64.zip: For Linux OS
chromedriver_mac64.zip: For Mac OSX
chromedriver_win32.zip: For Windows OS
Ensure that /etc/hosts file contains the following entry:
127.0.0.1 localhost
Ensure that ChromeDriver binary have executable permission for the non-root user.
Ensure that you have passed the proper absolute path of ChromeDriver binary through the argument executable_path. (chmod 777)
Execute your Test as a non-root user.

Resources