Python or LibreOffice Save xlsx file encrypted with password - python

I am trying to save an Excel file encrypted with password. I have tried following the guide on https://help.libreoffice.org/Common/Protecting_Content_in - and works perfectly. However, this is in the GUI, but I am looking for a solution using the command line interface in headless mode.
I have looked at the man libreoffice, but I could not find anything in there.
Likewise I have looked at the documentation of the Python 3 library openpyxl, but I did not find anything useful there either.
Is it possible to save an Excel 2007+ file encrypted with a password on Ubuntu 14.04/16.04 using the command line (or Python library) that do not require any user interaction or X session?

There is solution using Jython and Apache POI. If you want like to use it from CPython/PyPy, you can use subprocess module to call external Jython script.
I assume that you have Java JRE/JDK installed
Create non-encrypted xlsx file with Excel/Calc or use xlsxwriter or openpyxl and save it as test1.xlsx
Download standalone Jython
Download Apache POI
Extract Apache POI in same dir where is standalone Jython jar
Save following Jython script as encrypt.py:
import os
import sys
from java.io import BufferedInputStream
from java.io import FileInputStream
from java.io import FileOutputStream
from java.io import File
from java.io import IOException
from org.apache.poi.poifs.crypt import EncryptionInfo, EncryptionMode
from org.apache.poi.poifs.crypt import CipherAlgorithm, HashAlgorithm
from org.apache.poi.poifs.crypt.agile import AgileEncryptionInfoBuilder
from org.apache.poi.openxml4j.opc import OPCPackage, PackageAccess
from org.apache.poi.poifs.filesystem import POIFSFileSystem
from org.apache.poi.ss.usermodel import WorkbookFactory
def encrypt_xlsx(in_fname, out_fname, password):
# read
in_f = File(in_fname)
in_wb = WorkbookFactory.create(in_f, password)
in_fis = FileInputStream(in_fname)
in_wb.close()
# encryption
out_poi_fs = POIFSFileSystem()
info = EncryptionInfo(EncryptionMode.agile)
enc = info.getEncryptor()
enc.confirmPassword(password)
opc = OPCPackage.open(in_f, PackageAccess.READ_WRITE)
out_os = enc.getDataStream(out_poi_fs)
opc.save(out_os)
opc.close()
# write
out_fos = FileOutputStream(out_fname)
out_poi_fs.writeFilesystem(out_fos)
out_fos.close()
if __name__ == '__main__':
in_fname = sys.argv[1]
out_fname = sys.argv[2]
password = sys.argv[3]
encrypt_xlsx(in_fname, out_fname, password)
Call it from console:
java -cp "jython-standalone-2.7.0.jar:poi-3.15/lib/commons-codec-1.10.jar:poi-3.15/lib/commons-collections4-4.1.jar:poi-3.15/poi-3.15.jar:poi-3.15/poi-ooxml-3.15.jar:poi-3.15/poi-ooxml-schemas-3.15.jar:poi-3.15/ooxml-lib/curvesapi-1.04.jar:poi-3.15/ooxml-lib/xmlbeans-2.6.0.jar" org.python.util.jython -B encrypt.py test1.xlsx test1enc.xlsx 12345678
Where:
encrypt.py - name of script
test1.xlsx - input filename
test1enc.xlsx - output filename
12345678 - password
Final encrypted xslx should be in test1enc.xlsx.

Related

GITLAB-API-PYTHON- how import package from gitlab - file.py?

My code is work but... i think about simple solution.
Maybe someone knows?
I can't find in API Gitlab how import package from GitLab - file .py
In database_connect.py i have function with connect to database (example)
For example
database_connect = project.files.get(file_path='FUNCTION/DATABASE/database_connect.py', ref='main')
import database_connect
My code ...
import gitlab
import base64
gl = gitlab.Gitlab('link',
private_token='API')
projects = gl.projects.list()
for project in projects[3:4]:
# print(project) # prints all the meta data for the project
print("Project: ", project.name)
print("Gitlab URL: ", project.http_url_to_repo)
database_connect = project.files.get(file_path='FUNCTION/DATABASE/database_connect.py', ref='main')
database_connect_content = base64.b64decode(database_connect.content).decode("utf-8")
database_connect_package = database_connect_content.replace('\\n', '\n')
exec(database_connect_package)

How Do I Make an API Call from Python v2.7.13 When the Requests Module Isn't Available

Good-day Folks,
I am writing a small Python script that will be used on a Ubiquiti EdgeRouter 12P to make an API Call, using Digest Authentication, against another router for some JSON data. This is my first attempt at writing a Python script and I have been able to do this using the Requests module, but only in a Python v3.x.y environment. As I was writing my script, I discovered that the Python version on the EdgeRouter is v2.7.13 and the Requests module isn't installed/loaded.
I have attempted to do a pip install requests but it fails with an invalid syntax error message. So with my limited knowledge, I can't figure out what my options are now. Googled around a bit and saw references to using UrlLib or UrlLib2 - but I'm struggling with figuring out how to use either to make my API Call using Digest Authentication.
I would very much like to stick to the Requests module, as it appears to be the simplest and cleanest approach. Below is a snippet of my code, any help would be really appreciated, thanks.
PS. My script is not yet finished, as I'm still learning how to parse the response data received.
HERE'S MY SCRIPT
#PYTHON MODULE IMPORTS
import sys #Import the Python Sys module - used later to detect the Python version
PythonVersion = sys.version_info.major #Needed to put this global variable up here, so I can use it early
import json #Import the JSON module - used to print the API Call response content in JSON format
if PythonVersion == 3: #Import the REQUESTS and HTTPDigestAuth modules - used to make API Calls if we detect Python version 3
import requests
from requests.auth import HTTPDigestAuth
if PythonVersion == 2: #Import the UrlLib module - used to make API Calls if we detect Python version 2
import urllib
#GLOBAL VARIABLES
NodeSerial = '1234'
NodeIP = '192.168.1.100'
BasePath = 'api/v0.1'
apiURL = f"http://{NodeIP}/{BasePath}/MagiNodes"
#Define the credentials to use
Username='admin'
Passwd='mypassword'
#MAIN ROUTINE
print("This is a test script")
if PythonVersion == 2:
print("Python Version 2 detected")
elif PythonVersion == 3:
print("Python Version 3 detected")
print(f"Now querying MagiLink-{NodeSerial}...")
Query1 = requests.get(f"{apiURL}/{NodeSerial}", auth=HTTPDigestAuth(Username, Passwd)) #Using an F string
pretty_Query1 = json.dumps(Query1.json(), indent=3) #Pretty printing the response content
print(pretty_Query1)

How can I call another python script, in a python script, based on a variable in a config file?

I have below py script to download the files from artifactory.
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import tarfile
import urllib
from urllib import urlretrieve
import ConfigParser
Config = ConfigParser.ConfigParser()
Config.read('/vivek/release.conf')
code_version = Config.get('main', 'app_version')
os.chdir('/tmp/')
arti_st_url='http://repo.com/artifactory/libs-release- local/com/name/tgz/abc.ear/{0}/abc.ear-{0}.tar.gz'.format(code_version)
arti_st_name='abc.ear-{0}.tar.gz'.format(code_version)
arti_sl_url='http://repo.com/artifactory/libs-release- local/com/name/tgz/def.ear/{0}/def.ear-{0}.tar.gz'.format(code_version)
arti_sl_name='def.ear-{0}.tar.gz'.format(code_version)
urllib.urlretrieve(arti_st_url, arti_st_name)
urllib.urlretrieve(arti_sl_url, arti_sl_name)
oneEAR = 'abc.ear-{0}.tar.gz'.format(code_version)
twoEAR = 'def.ear-{0}.tar.gz'.format(code_version)
tar = tarfile.open(oneEAR)
tar.extractall()
tar.close()
tar1 = tarfile.open(twoEAR)
tar1.extractall()
tar1.close()
os.remove(oneEAR)
os.remove(twoEAR)
This script works perfectly, thanks to stackoverflow.
Here's the next question. There's a variable "protocol" in release.conf. If it's equal to "localcopy", there's an existing py script that does something. If the "protocol" is equal to "artifactory",
above script should be called and executed. How can I achieve it?
Note: I am a beginner in Python, but my tasks are not. So, please help me out guys.
You could simply use:
import os
os.system("script_path")
to execute the script file. But there should be a line called shebang in the very top of that script file, you want to execute. If your python interpreter would be in /usr/bin/python this would be:
#!/usr/bin/python
Assuming you are a Linux user.
In Windows shebang isn't supported. It determines what program to use running *.py file itself.
//Edit:
To call that two scripts depending on a property config value you could just make another script called for example runthis.py which contains instruction like:
protocol = Config.get('main', 'protocol')
if protocol == 'localcopy':
os.system('path_to_localcopy_script)
if protocol == 'antifactory':
os.system('path_to_other_script')
Dont forgot to import needed modules in that new script.
Then you just run script you just made.
That is one way to do this.
If you dont want to create additional script, then put that code you wrote in a function, like:
def main():
...
Your code
...
And on the very bottom of your script file write:
if __name__ = '__main__':
protocol = Config.get('main', 'app_version')
if protocol == 'localcopy':
main()
if protocol == 'antifactory':
os.system('path_to_other_script')
if __name__ = '__main__' would execute only if you run that script by yourself (not by call from an other sctipt for example)

Python Gooey Run Directory

I'm using the latest Gooey library on Python 2.7 on Windows as a GUI for a simple argparse, but for some reason, the script keeps giving me the [Errno2] No File Exists.
I think it is because there is a space in the path of the Anaconda installation (i.e. C:\Users\FirstName LastName\Etc.) but I'm stumped.
I have tried str.replace all the \ with \\, but I keep getting the same error message. Any ideas of what to do?
Code:
from __future__ import print_function
import pandas as pd
import numpy as np
import glob
import sys
import os
import json
from argparse import ArgumentParser
from gooey import Gooey, GooeyParser
#Gooey(program_name="CPT Lookup")
def parse_args():
stored_args = {}
parser = GooeyParser(description='CPT Lookup')
#Eventually make into checkboxes
parser.add_argument('year',
action='store',
default=stored_args.get('year'),
widget='FileChooser',
help="CSV file with extracted year")
parser.add_argument('CPT',
action='store',
default=stored_args.get('CPT'),
widget='TextField',
help='CPT Code')
args = parser.parse_args()
return args
def loadCSV(year):
#DO I DO SOMETHING LIKE YEAR.REPLACE('\','\\')?
df = pd.read_csv(year)
return df
if __name__ == '__main__':
conf = parse_args()
print("Opening CSV file")
sales_df = loadCSV(conf.year)
This was an issue with the Gooey library itself (I'm the author). It wasn't quoting incoming file paths correctly.
If you pull down the latest release from PyPi (pip install -U gooey), your example script should run without issue.

Not able to import getpass in python

I have a requirement to input username and password from the console. For the password I am using
password = getpass.getpass('Enter password')
I have used import getpass But getting
ImportError : no module named getpass
Also tried setting the pythonpath using
export pythonpath=/usr/lib/python2.4/site-packages:/usr/lib/python2.4
Code:
#!/usr/bin/python2.4
import sys
import getpass
WL_USER = raw_input('Enter the username to login to BI EM:')
WL_PASSWD = getpass.getpass('Enter the password:')
HOST_NAME = raw_input('Enter the BI host URL')
WL_PORT = raw_input('Enter the admin port for BI')
error:
ImportError: no module named getpass
One important thing is that I am trying to run the script as a wlst script i.e. trying to edit the attribute of an Mbean. So the execution goes like this:
/home/wlserver_10.3/common/bin/wlst.sh test.py
I tried to execute the script as python test.py
It executes fine. So it looks like there is some issue with wlst.
Need assistance on this.
The argument getpass.getpass() was added in python 2.5. Check the old manual, http://docs.python.org/release/2.4/lib/module-getpass.html
A bit old but Your file is probably named "getpass.py"

Categories

Resources