Directory conventions for extra files [closed] - python

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I have written a (python) script which identifies all node on its subnet (NAT subnet) and send an email if the IP address doesn't exist within a record. For this size of project, I don't want to run a database. I think a text file delimited by new lines with an IP address on each would be suitable. What is the appropriate convention for the directory this file would be placed?

There are no real conventions and the answers to this question may be a little opinionated and a lot depends on the script's exact use case.
You have following choices:
datafile in current working directory
datafile in same directory as script
datafile in a folder (that will be created if not existant) relative to the home directory
like three but with an additional profile name
in a system folder like /var/run/toolname
explicit parameter to the script specifies file name
1.) Current working directory
Con:
It forces you to cd into the directory where you have your data, otherwise script won't work or create new data from scratch
Pro:
As the same user on the same machine you could have multiple projects each using its own data.
2.) datafile in same directory as script
Pro:
you don't have to cd anywhere. you know where to find the data.
Con:
you need write permissions to the directory where the script is located (might be a security concern if executed by a web server and if an exploit is found)
only one data file per script
no two users can execute the script with different data
3.) datafile in a folder (that will be created if not existant) relative to the home directory
Pro:
script in one directory but each user has its own data.
if script directory is removed, script is uninstalled and reinstalled the data will persist.
no special write permissions for script dir required.
Con:
you remove the script dir, data persists and might never be deleted.
one user cannot run multiple instances use the script for multiple projects
clean up of data required after uninstall of script
4.( like 3.) but with an additional profile/project name
Pro:
same as for 3.)
one can run multiple projects / profiles in parallel (firefox for example allows to be run with profiles, which are all stored in ~/.mozilla/firefox, but each profile creates its own sub directory ~/.mozilla/firefox/xxxx.profilename
Con:
same as for 3.)
5.) in a system folder like /var/run/toolname
Pro:
could be nice for tools, that run as service / server
Con:
require admin privileges (at least during installation)
6.)
Pro:
you can do whatever you want
Con:
you must specify an additional paramater (except you have the behaviour of the other suggestions as default and the option only if you want to have different behaviour.
All solutions should be fine for you.
For your kind of tool 5.) 3.) 2.) 6.) are probably the better options. I assume your script will be run as a cron job or something alike.

Related

How can I define an absolute path saved in one exe file?

I'm writing a software in python for windows which should be connected to a database. Using py2exe i want to make an executable file so that I don't have to install python in the machines the software is running. The problem is that I want the user to define where the database is located the very first time the software starts, but I don't know how to store this information so that the user doesn't have to tell everytime where is the database. I have no idea how to deal with it. (the code cannot be changed because it's just a .exe file). How would you do that?
I can think of some solutions:
You can assume the DB is in a fixed location - bad idea, might move or change name and then your program stop working
You can assume the DB is in the same folder as the .exe file and guide the user to run it in the same folder - better but still not perfect
Ask the user for the DB location and save the path in a configuration file. If the file doesn't exist or path doesn't lead to the file, the user should tell the program where is the DB, otherwise, read it from the config file - I think this is the best option.
import os
default_db_path = os.environ['LOCALAPPDATA'] + '/stuff.db'
setting_path = os.environ['LOCALAPPDATA'] + '/.stuff_db_path.txt'
try:
open(setting_path)
except:
with open(setting_path, 'wt') as f:
f.write(default_db_path)
db_path = open(setting_path).read().strip()
This way, the user is able to configure via the text file, and you're able to have a sensible default for the first time.
Edit: added a Windows friendly config path, which should work in most private and corporate environments. There are innumerous ways to improve this example, but my suggestion is you start out simple stupid and take it from there.

Allow a python file to add to a different file linux

I'm making a "wargame" like the ones on overthewire.org or smashthestack.org. When you finish the game, the user should get a python program that has extra permissions to edit a file in /var/www/html so that they can sign their name. I want to have a program like this so that they can add text to the html file without removing the text of other users and so that it filters offensive words.
How can I make a file editable by a specific program in Linux? And how can I make the program edit the file in python? Do I just use os.system?
I'm going to answer your question but also beg you to consider another approach.
The functionality you are looking for is usually handled by a database. If you don't want to use anything more complex, SQLite is often all you need. You would then need a simple web application that connects to the database, grabs the fields, and then injects them into HTML.
I'd use Flask for this as it comes with Jinja and that's a pretty simple stack to get started with.
If you really want to edit the HTML file directly in Python, you will need write permissions for whatever user is running the Python script. On Ubuntu, that folder is typically owned by www-data if you are running Apache.
Then you'd open the file in Python, perform file operations on it, and then close it.
with open("/var/www/html/somefile.txt", "a") as myfile:
myfile.write("l33t h4x0r has completed the challenge!\n")
That's an example of how you'd do a simple append operation in Python.

Python or Powershell - Import Folder Name & Text file Content in Folder into Excel [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have been looking at some python modules and powershell capabilities to try and import some data a database recently kicked out in the form of folders and text files.
File Structure:
Top Level Folder > FOLDER (Device hostname) > Text File (also contains the hostname of device) (with data I need in a single cell in Excel)
The end result I am trying to accomplish is have the first cell be the FOLDER (device name) and the second column contain the text of the text file within that folder.
I found some python modules but they all focus on pulling directly from a text doc...I want to have the script or powershell function iterate through each folder and pull both the folder name and text out.
This is definitely do-able in Powershell. If I understand your question correctly, you're going to want to use Get Child-Itemand Get Content then -recurse if necessary. As far as an export you're going to want to use Out-File which can be a hassle when exporting directly to xlsx. If you had some code to work with I could help better but until then this should get you started in the right direction. I would read up on the Getcommands because Powershell is very simple to write but powerful.
Well, Since you're asking in a general sense -- you can do this project simply in either choice of script languages. If it were me -- and I had to do this job once -- I'd probably just bang out a PoSH script to do it. If this script had to be run repeatedly, and potentially end up with more complex functions I'd probably then switch to Python (but that's just based on my personal preference as PoSH is pretty powerful in a Windows env). Really this seems like a 15 line recursive function in either choice.
You can look up "recursive function in powershell" and the same for python and get plenty of code examples, as File Tree Walks (FTW :) ) are one of the most solved problems on sites like this. You'd just replace whatever the other person is doing in their walk with a read of the file and write. You probably also want to output in CSV format because it's easier and imports into excell just fine.

How to create updates system for users?

I have project on github. Few people are using it. I want to create a system, that will allow those people to update to current version. I was thinking about creating script, that will fetch *.zip file of my project from github, unpack it and later open() every file and check every line (if x == line). In case of != i want to swap files.
My question is: is this the right way to do this? Or is it better to just grab *.zip and force-swap every project file?

How to check if a file can be created inside given directory on MS XP/Vista?

I have a code that creates file(s) in user-specified directory. User can point to a directory in which he can't create files, but he can rename it.
I have created directory for test purposes, let's call it C:\foo.
I have following permissions to C:\foo:
Traversing directory/Execute file
Removing subfolders and files
Removing
Read permissions
Change permissions
Take ownership
I don't have any of the following permissions to C:\foo:
Full Control
File creation
Folder creation
I have tried following approaches, so far:
os.access('C:\foo', os.W_OK) == True
st = os.stat('C:\foo')
mode = st[stat.ST_MODE]
mode & stat.S_IWRITE == True
I believe that this is caused by the fact that I can rename folder, so it is changeable for me. But it's content - not.
Does anyone know how can I write code that will check for a given directory if current user has permissions to create file in that directory?
In brief - I want to check if current user has File creation and Folder creation permissions for given folder name.
EDIT: The need for such code arisen from the Test case no 3 from 'Certified for Windows Vista' program, which states:
The application must not allow the Least-Privileged user to save any files to Windows System directory in order to pass this test case.
Should this be understood as 'Application may try to save file in Windows System directory, but shouldn't crash on failure?' or rather 'Application has to perform security checks before trying to save file?'
Should I stop bothering just because Windows Vista itself won't allow the Least-Privileged user to save any files in %WINDIR%?
I recently wrote a App to pass a set of test to obtain the ISV status from Microsoft and I also add that condition.
The way I understood it was that if the user is Least Priveledge then he won't have permission to write in the system folders. So I approached the problem the the way Ishmaeel described. I try to create the file and catch the exception then inform the user that he doesn't have permission to write files to that directory.
In my understanding an Least-Priviledged user will not have the necessary permissions to write to those folders, if he has then he is not a Least-Priveledge user.
Should I stop bothering just because Windows Vista itself won't allow the Least-Privileged user to save any files in %WINDIR%?
In my opinion? Yes.
I wouldn't waste time and LOCs on checking for permissions. Ultimate test of file creation in Windows is the creation itself. Other factors may come into play (such as existing files (or worse, folders) with the same name, disk space, background processes. These conditions can even change between the time you make the initial check and the time you actually try to create your file.
So, if I had a scenario like that, I would just design my method to not lose any data in case of failure, to go ahead and try to create my file, and offer the user an option to change the selected directory and try again if creation fails.
I agree with the other answers that the way to do this is to try to create the file and catch the exception.
However, on Vista beware of UAC! See for example "Why does my application allow me to save files to the Windows and System32 folders in Vista?": To support old applications, Vista will "pretend" to create the file while in reality it creates it in the so-called Virtual Store under the current user's profile.
To avoid this you have to specifically tell Vista that you don't want administrative privileges, by including the appropriate commands in the .exe's manifest, see the question linked above.
import os
import tempfile
def can_create_file(folder_path):
try:
tempfile.TemporaryFile(dir=folder_path)
return True
except OSError:
return False
def can_create_folder(folder_path):
try:
name = tempfile.mkdtemp(dir=folder_path)
os.rmdir(name)
return True
except OSError:
return False

Categories