I'm fairly new to python. Some googling has got me to this module https://pypi.python.org/pypi/python-crontab. I've setup my env and installed python-crontab==1.9.3. But I keep getting errors. What am I doing wrong? Any help would be greatly appreciate. I'm trying to use examples but they don't seem to be working for me.
What I would like to do is the following:
add a cron job to the cron tab
Terminal Error Output:
Traceback (most recent call last):
File "test5.py", line 5, in <module>
users_cron = CronTab(user='testuser')
File "/Users/testuser/Desktop/sample1/prj-env/lib/python2.7/site-packages/crontab.py", line 187, in __init__
self.read(tabfile)
File "/Users/testuser/Desktop/sample1/prj-env/lib/python2.7/site-packages/crontab.py", line 231, in read
raise IOError("Read crontab %s: %s" % (self.user, err))
IOError: Read crontab testuser: crontab: must be privileged to use -u
users_cron = CronTab(user='testuser')
It appears like you are trying to create a cronjob for the user 'testuser'.
IOError: Read crontab testuser: crontab: must be privileged to use -u
The error is telling you that you need to be a privileged user to be able to do that. Try running your script with 'sudo':
sudo python my_python_script.py
Reference
You're trying to access a specific user's crontab, you can't do that on the base system (which is what the python module is trying to use) without root access. If you want to get your own crontab do the following:
users_cron = CronTab(user=True)
You can also use plan which is an easier way to write cron job for crontab from python:
from plan import Plan
cron = Plan()
cron.command('ls /tmp', every='1.day', at='12:00')
cron.command('pwd', every='2.month')
cron.command('date', every='weekend')
if __name__ == '__main__':
cron.run()
See more in the docs
Related
I tried to make a function that checks if my Ubuntu Server has a specific package installed via apt list, when the condition isn't met it, in theory, the program should install any necessary dependencies for the other piece of software to work. Here's a function I wrote:
# Docker Configuration Tool
def DCT():
cache = apt.Cache()
if cache['docker-ce'].is_installed:
print("Docker and Docker-compose are installed on this system...")
print("If you don't have MySQL Server installed on your system use Docker to prepare and configure your Server")
__run_file = [ BASH COMMANDS ]
OS_MCE(__run_file)
else:
print("Docker and Docker-compose are not installed on this system!")
print("Preparing Environment for the Installation...\n")
__install_docker = [ BASH COMMANDS ]
OS_MCE(__install_docker)
An error when trying to run this function:
Traceback (most recent call last):
File "MIM.py", line 304, in <module>
NSWIT(True)
File "MIM.py", line 297, in NSWIT
Menu()
File "MIM.py", line 257, in Menu
DCT()
File "MIM.py", line 117, in DCT
if cache['docker-ce'].is_installed:
File "/usr/lib/python3/dist-packages/apt/cache.py", line 305, in __getitem__
raise KeyError('The cache has no package named %r' % key)
KeyError: "The cache has no package named 'docker-ce'"
Try changing your if expression to check that the docker-ce key is in the cache map before trying to access it. If there isn't a key with that name, it makes sense to assume that the package isn't installed. So like this:
# Docker Configuration Tool
def DCT():
cache = apt.Cache()
if 'docker-ce' in cache and cache['docker-ce'].is_installed:
print("Docker and Docker-compose are installed on this system...")
print("If you don't have MySQL Server installed on your system use Docker to prepare and configure your Server")
__run_file = [ BASH COMMANDS ]
OS_MCE(__run_file)
else:
print("Docker and Docker-compose are not installed on this system!")
print("Preparing Environment for the Installation...\n")
__install_docker = [ BASH COMMANDS ]
OS_MCE(__install_docker)
Error messages are your friend. Read them carefully. In this case, the error was telling you precisely what was wrong, and with that, it is obvious how to fix it once you've been doing this for a while.
This is a good opportunity to learn about and understand short-circuited evaluation of logical expressions. The first clause of your conditional expression insures that the second clause isn't evaluated if it will throw the error you were seeing (well, Duh!, right?)...but if you don't fully understand why that is, it's a good thing to clearly understand. Maybe see: https://pythoninformer.com/python-language/intermediate-python/short-circuit-evaluation/
So my issue is that I have an AWS EC2 instance running Ubuntu server 18.04 and Apache2, when a button is pressed it posts some variables which are passed to a function which then uses shell_exec() to execute a Python script. The Python script then takes these variables (direction and angle) as command line arguments, it will then attempt to write then to a file called cmds.txt. When doing this however I get this error reported back to me:
Traceback (most recent call last):
File "/home/server/cmdWriter.py", line 45, in
main()
File "/home/server/cmdWriter.py", line 41, in main
servoCmds(direction, angle)
File "/home/server/cmdWriter.py", line 28, in servoCmds
cmdFile = open("cmds.txt", "a")
PermissionError: [Errno 13] Permission denied: 'cmds.txt'
After some looking I think this is because PHP executes as user "www-data" which doesn't have write privileges, so after looking at other questions I tried settung up permissions so that www-data has read and write privilages to the folder and the python file. For whatever reason this does not work! I've been pulling my hair out trying to get this to work, trying suggestions from several other questions, can anyone help me here?
You are getting the error with respect to 'opening' the file. You have to make sure that the permissions on the .txt file are at 755 or higher. If the server you are using is Linux, then you have two alternatives to modify the permissions:
If you have cPanel, you can use the cPanel interface and just change permissions by going to the file, click on Change Permissions and then set the permissions to 777.
or
From the linux command line, use chmod command - like this:
chmod 777 cmds.txt
I can't speak to the security issues associated with same without knowing more.
The other possibility is that you are using the 'a' mode, but the file does not already exist. If you are not certain the file exists when the command is executed, you may try 'a+' as that will create the file if one does not already exist.
Does that work?
So I'm trying to read a config file which needs to be "sudo'd" into but I'm trying to read its contents using python only without using terminal. when I use the code below I get the error as shown:
with open('/etc/motion/motion.conf','rb') as file:
data = file.readlines()
IOError: [Errno 13] Permission denied: '/etc/motion/motion.conf'
Is there anything I could try to read the contents of the file strictly with python?
You should call your python file from a shell script, change the owner of this script to be root and then set the SUID bit of this script. The user will be able to run the script but the owner of the script will be root:
http://www.codecoffee.com/tipsforlinux/articles/028.html
http://www.linuxnix.com/2011/12/suid-set-suid-linuxunix.html
etc.
Of course you must be aware of security issues that may be involved by such a thing but for local use with a simple script doing one thing, it's OK.
Permission denied means that you have no permission to read that file.
If you're on Linux, you should change the file's permission use chmod command. Or you can use sudo comand run python like this:
sudo python filename.py
or login as root then run python:
su - root
python filename.py
And if you want run the program as root every times, you can use os.execlpe() function like this:
import os
import sys
euid = os.geteuid()
if euid != 0:
args = ['sudo', sys.executable] + sys.argv + [os.environ]
os.execlpe('sudo',*args)
with open('/etc/motion/motion.conf','rb') as file:
data = file.readlines()
print data
This solution is from here:
authentication in python script to run as root
and is courtesy of #samplebias
I'm trying to run wlst script form .py file but it can not be done
Content of .py file :
connect('weblogic','weblogic','t3://localhost:8001')
sca_undeployComposite('http://localhost:8001','Hello','1.0','user='weblogic',partition='myPartition')
sca_deletePartition('myPartition')
sca_createPartition('myPartition')
sca_deployComposite('http://localhost:8001','C:\WLST\Test\Application.zip',user='weblogic',configplan='myPlan.xml', partition='myPartition')
exit()
when i run cmd file to execute script, Only connect() method is execute success. any command bellow it can not be execute. And error message appear: Problem invoking WLST - Traceback (innermost last): File "c:\WLS\script\filname.py", line 2, in ?
Name Error: sca_undeployComposite
Please help me to resolve it. Thanks !
The commands after the connect() line which are not regular WLST commands. They requires sca related libraries into CLASSPATH. if you look into your wlst.cmd or .sh file that is actually calling the environment setup file that could be setWLSEnv.sh/.cmd. If you run that from where you are having the this python script. That script will work, it is simple java CLASSPATH funda nothing else!
Probably you might be running wlst.cmd after navigating to the common bin folder like
cd /oracle/fmwhome/Oracle_SOA1/common/bin/.
instead you can run in your script like this
C:\WLS\script\>/oracle/fmwhome/Oracle_SOA1/common/bin/wlst.cmd filename.py
or
C:\WLS\script\>/oracle/fmwhome/Oracle_SOA1/common/bin/setWLSEnv.cmd
C:\WLS\script\>java weblogic.WLST filename.py
You can also refer for more sca related scripting: WLSTByExamples
I am trying to run a python script which uses a binary file (xFiles.bin.addr_patched) created by a postlinker. However, I am getting this error.
File "abc.py", line 74, in ParseCmd
shutil.copy(gOptions.inputX, gWorkingXFile)
File "/usr/lib/python2.6/shutil.py", line 89, in copy
copymode(src, dst)
File "/usr/lib/python2.6/shutil.py", line 66, in copymode
os.chmod(dst, mode)
OSError: [Errno 1] Operation not permitted: 'myPath/xFiles.bin.addr_patched'
When I checked the permissions of this xFiles.bin, by ls-l, it shows that
-rwxrwxrwx 1 nobody nogroup
I presume the error is because this file was created by some other application, the python script I am running does not have access to it. Since I am beginner wrt ubuntu, I don't really know how to fix it. Any suggestions on how to fix this?
SOLVED:
As one of the answers Suggested : chown username:groupname file name fixes this issue
You could try (from the command line, but I'm sure there's a syntax in python):
sudo chown your_username:your_groupname filename
Note: The group is usually just your username.
I feel like there's something wrong with those permissions though. Read Write Execute for everyone seems to be off. How was this file created? How did it get to be created by the user nobody?
Python code to change the permission:
from getpwnam import pwd
from getgrnam import grp
import os
uid = getpwnam("YOUR_USERNAME")[2]
gid = grp.getgrnam("YOUR_GROUPNAME")[2]
os.chown("myPath/xFiles.bin.addr_patched", uid, gid)
Run the script with sudo and you're done.
I had this problem when running a python script on my mac (10.14 Mojave) trying to access /Users/xxx/Pictures/Photos Library.photoslibrary.
The full solution can be found in http://osxdaily.com/2018/10/09/fix-operation-not-permitted-terminal-error-macos/
Summary:
Go to System Preferences > Security & Privacy > Privacy > Full Disk Access and add your IDE or python interpreter to the list.
My guess is that you should be looking at the permissions for myPath folder instead. Seems like you can't write to it, hence the problem. Try ls -l myPath/.. and see the permissions for myPath. If that's the problem, change the permissions on the folder with chmod.
P.S. Also, see Google top result on Linux file permissions.