# Appimage erstellen

# Installation der Bauumegebung

### Beschreibung:

Eine installation von Appimagekit. Es ist eine einfache ausführbare Datei die keinerlei Installationsabbhängigkeiten braucht.

### Download:

Unter [https://github.com/AppImage/AppImageKit/releases](https://github.com/AppImage/AppImageKit/releases)

können die Release Binarys für die verschiedenen Plattformen heruntergeladen werden.

Für Linux x64 [https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-x86\_64.AppImage](https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-x86_64.AppImage)  
Für ander architekturen die dem enstprechende binary wählen.  
  
Diese dann mittels

```
chmod +x appimagetool-x86_64.AppImage
mv appimagetool-x86_64.AppImage appimagetool.AppImage
```

ausführbar machen. Das Tool kann dan auch mittels Appimage Launcher ins system integriert werden.  
[hier klicken für den Launcher](https://wiki.hacker-net.de/books/appimage/page/appimagelauncher "AppimageLauncher")

# Ein Python Script als Appimage bauen

### Beschreibung:

Es gibt situationen, da möchte man gerne ein python script mit all seinen abhängigkeiten gerne als eine einzige Executable haben. Mit App image und env ist dies machbar. Es können sogar Parameter an das pythonscript übergeben werden.

### Erstellung:

#### Verzeichnis erstellen

Als erstes unser Project VErzeichnis erstellen. MyApp natürlich mit dem namen des Projektes oder dateinamen des scriptes ersetzen. Ich nenne das prject nextcloudimport

```
mkdir MyApp.AppDir
```

#### Python environment erstellen und Abbhängigkeiten für das Script installieren

Nun in das Verzeichnis gehen und ein ENV erstellen. Ein ENV ist eine Virtualumegebung für python.

```
cd MyApp.AppDir
virtualenv --no-download AppRun
source AppRun/bin/activate

Beispiel:

cd nextcloudimport.AppDir
virtualenv --no-download python_env
source python_env/bin/activate
```

Nun alle abhängigkeiten installieren die unser script braucht

```
pip install --upgrade pip
pip install <Ihre benötigten Pakete>

Beispiel: 
pip install --upgrade pip
pip install requests
pip install BeautifulSoup4
pip install tabulate
pip install qrcode
pip install reportlab

```

Nun die apprun wieder deaktivieren

```
deactivate
```

#### Script kopieren

Nun das eigentliche Script reinkopieren.  
In diesem Fall kommt der importer von [https://github.com/t-markmann/nc-userimporter](https://github.com/t-markmann/nc-userimporter)

Die datei <span class="css-truncate css-truncate-target d-block width-fit">[nc-userimporter.py](https://github.com/t-markmann/nc-userimporter/blob/master/nc-userimporter.py "nc-userimporter.py") ins AppDir Verzeichnis kopieren.</span>

#### <span class="css-truncate css-truncate-target d-block width-fit">Launcher Script erstellen</span>

```
nano AppRun
```

<span class="css-truncate css-truncate-target d-block width-fit">Inhalt:</span>

```
#!/bin/bash
DIR="$(dirname "$(readlink -f "$0")")"
$DIR/python_env/bin/python $DIR/your_script.py "$@"


Beispiel:

#!/bin/bash
DIR="$(dirname "$(readlink -f "$0")")"
$DIR/python_env/bin/python $DIR/nc-userimporter.py "$@"
```

<span class="css-truncate css-truncate-target d-block width-fit">AppRun ausführbar machen</span>

```
chmod +x AppRun
```

#### <span class="css-truncate css-truncate-target d-block width-fit">Icon und .desktop-Datei hinzufügen</span>

<span class="css-truncate css-truncate-target d-block width-fit">Eine .desktop erstellen, die muss im auch im Hauptverzeichnsi von myapp.AppDIr liegen.  
Wnn ein icon gewüncht ist eine png mit 32x32 pixeln, wir nehmen hier das Nextcloud icon </span>[Papirus-Team-Papirus-Apps-Nextcloud.32.png](https://wiki.hacker-net.de/attachments/31)

diese dann in nextcloudimport.png umbenennen.  
  
Für dien Schlüssel können hier diese Nachgeschlagen werden, welche zur Verfügung stehen :   
[https://specifications.freedesktop.org/menu-spec/menu-spec-1.0.html#category-registry](https://specifications.freedesktop.org/menu-spec/menu-spec-1.0.html#category-registry)

Dies sind die gängigsten : `Utility`, `Development`, `Graphics`, `AudioVideo`

DerName ist auch gleichzeitg der Dateiname ohne Leerzeichnen

```
[Desktop Entry]
Type=Application
Name=MyApp
Icon=MyApp
Exec=AppRun
Categories=<Ihre Category>

Beispiel:

[Desktop Entry]
Type=Application
Name=Nextcloud CSV import
Icon=nextcloudimport
Exec=AppRun
Categories=Utility
```

<span class="css-truncate css-truncate-target d-block width-fit">Nun eine Verzeichnissebene zurück gehen und das appimage bauen.  
Die Architektur davor angeben.  
</span>

```bash
ARCH=i386    (32bit)
ARCH=x86_64  (64bit)
```

```
cd ..
ARCH=x86_64 ./appimagetool.AppImage MyApp.AppDir

Beispiel:
cd ..
ARCH=x86_64 ./appimagetool.AppImage
appimagetool nextcloudimport.AppDir
```

So sieht dann unsere Datei aus, mit Icon

[![Auswahl_258.png](https://wiki.hacker-net.de/uploads/images/gallery/2023-10/scaled-1680-/kYqMH87fXzcHPPPc-auswahl-258.png)](https://wiki.hacker-net.de/uploads/images/gallery/2023-10/kYqMH87fXzcHPPPc-auswahl-258.png)

Da dies ein Terminal python script ist was wir in ein appimage gesteckt haben probieren wir dieses jetzt im Terminal aus

### Pfad von Dateien im Scriptverzeichnis außerhalb des AppImages verweisen wie config files etc.

Sollte das script auf dateien die im AppImage liegen aber eigentlich außerhalb des appimage änderbar sein sollen wie zum beispiel config Dateien.  
  
Beispiel: das python script wenn es so laufen würde sucht in seinem pfad nach einer Datei config.xml  
Wenn es so aufgerufen wird, also ohne ein Appimage können wir die datei ja einfach editieren.  
In einem Appimge würde die config.xml ja im AppImage liegen.  
Also müssten wir jedes mal das Appimage neubauen, wenn wir die config ändern.  
Nicht sehr flexibel.

Deshalb ändern wir das Python script ab, wo es die config.xml finden soll.  
In unserem Script Beispiel sind es zwei dateien eine config.xml und eine users.csv

Das Original script:

<details id="bkmrk-%23%21%2Fusr%2Fbin%2Fenv-pytho"><summary>unser pythoc script komplett</summary>

\#!/usr/bin/env python3  
import os  
import os.path  
import sys  
import time  
import requests  
import certifi  
import csv  
import string  
import urllib.parse  
import qrcode  
import random  
import codecs  
import html  
from reportlab.lib.enums import TA\_JUSTIFY  
from reportlab.lib.pagesizes import A4  
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image, PageBreak  
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle  
from tabulate import tabulate  
from bs4 import BeautifulSoup  
from datetime import datetime

\# This tool creates Nextcloud users from a CSV file, which you exported from some other software.  
\# There is also an extra EduDocs mode, which takes into account the special default settings  
\# and security-related peculiarities when importing users in the school sector.

\# Copyright (C) 2019-2020 Torsten Markmann  
\# Mail: info@uplinked.net   
\# WWW: edudocs.org uplinked.net

\# This program is free software: you can redistribute it and/or modify  
\# it under the terms of the GNU General Public License as published by  
\# the Free Software Foundation, either version 3 of the License, or  
\# any later version.

\# This program is distributed in the hope that it will be useful,  
\# but WITHOUT ANY WARRANTY; without even the implied warranty of  
\# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the  
\# GNU General Public License for more details.

\# You should have received a copy of the GNU General Public License  
\# along with this program. If not, see &lt;https://www.gnu.org/licenses/&gt;.

print("")  
print("")  
print("###################################################################################")  
print("# NEXTCLOUD-USER-IMPORTER #")  
print("###################################################################################")  
print("")  
print("Copyright (C) 2019-2020 Torsten Markmann (t-markmann), edudocs.org &amp; uplinked.net")  
print("Contributors: Johannes Schirge (Shen), Nicolas Stuhlfauth (nicostuhlfauth)")  
print("This program comes with ABSOLUTELY NO WARRANTY")  
print("This is free software, and you are welcome to redistribute it under certain conditions.")  
print("For details look into LICENSE file (GNU GPLv3).")  
print("")

\# Useful resources for contributors:  
\# Nextcloud user API https://docs.nextcloud.com/server/latest/admin\_manual/configuration\_user/instruction\_set\_for\_users.html  
\# Nextcloud group API https://docs.nextcloud.com/server/latest/admin\_manual/configuration\_user/instruction\_set\_for\_groups.html  
\# CURL to Python request converter https://curl.trillworks.com/

\# determine if running in a build package (frozen) or from seperate python script  
frozen = 'not'  
if getattr(sys, 'frozen', False):  
 # we are running in a bundle  
 appdir = os.path.dirname(os.path.abspath(sys.executable))  
 ## print("Executable is in frozen state, appdir set to: " + appdir) # for debug  
else:  
 # we are running in a normal Python environment  
 appdir = os.path.dirname(os.path.abspath(\_\_file\_\_))  
 ## print("Executable is run in normal Python environment, appdir set to: " + appdir) # for debug

\# read config from xml file  
configfile = codecs.open(os.path.join(appdir,'config.xml'),mode='r', encoding='utf-8')  
config = configfile.read()  
configfile.close()

\# load config values into variables  
config\_xmlsoup = BeautifulSoup(config, "html.parser") # parse  
config\_ncUrl = config\_xmlsoup.find('cloudurl').string  
config\_adminname = config\_xmlsoup.find('adminname').string  
config\_adminpass = urllib.parse.quote(config\_xmlsoup.find('adminpass').string)  
config\_csvfile = config\_xmlsoup.find('csvfile').string  
config\_csvDelimiter = config\_xmlsoup.find('csvdelimiter').string  
config\_csvDelimiterGroups = config\_xmlsoup.find('csvdelimitergroups').string  
config\_GeneratePassword = config\_xmlsoup.find('generatepassword').string  
config\_sslVerify = eval(config\_xmlsoup.find('sslverify').string)  
config\_language = config\_xmlsoup.find('language').string  
config\_pdfOneDoc = config\_xmlsoup.find('pdfonedoc').string  
config\_EduDocs = config\_xmlsoup.find('edudocs').string  
config\_schoolgroup = config\_xmlsoup.find('schoolgroup').string

\# EduDocs info-text  
if config\_EduDocs == 'yes':  
 print("")  
 print("###################################################################################")  
 print("# EDUDOCS-MODUS (www.edudocs.org) #")  
 print("# Willkommen zum EduDocs-Nutzerimport. #")  
 print("# Dieser Modus ist für den Import schulischer Nutzeraccounts vorgesehen und #")  
 print("# berücksichtigt die besonderen datenschutzrechtlichen Vorgaben. #")  
 print("# #")  
 print("# Bitte stellen Sie sicher, dass die Import-Datei nur EINE Gruppe von Personen #")  
 print("# enthält. Das heißt, entweder Lehrkräfte ODER Schüler ODER Schulpersonal. #")  
 print("# Ein zeitgleicher Import verschiedener Personengruppen ist nicht möglich. #")  
 print("# #")  
 print("# Prüfen Sie die Vorschau des Nutzerimports sehr genau, bevor Sie den #")  
 print("# Importprozess starten. #")  
 print("###################################################################################")  
 print("")  
 print("")  
 print("Wenn Sie sicher sind, dass Ihre Einstellungen in der config.xml korrekt sind,")  
 print("drücken Sie eine beliebige Taste, um fortzufahren.")  
 input("Andernfalls brechen Sie den Prozess mit \[STRG + C\] ab.")  
 print("")  
 print("Sie haben sich entschieden, fortzufahren. Eine Nutzerimport-Vorschau wird generiert.")  
 print("")

else:  
 print("")  
 print("###################################################################################")  
 print("# Welcome to the Nextcloud user import. #")  
 print("# Please check the preview of the user import very carefully before you start #")  
 print("# the import process. #")  
 print("###################################################################################")  
 print("")  
 print("")  
 print("When you are sure that your settings in the config.xml are correct,")  
 print("press \[ANY KEY\] to continue.")  
 input("Otherwise, press \[CONTROL + C\] to abort the process.")  
 print("")  
 print("They have decided to continue. A user import preview is generated.")  
 print("")

\# check if user-import-csv-filme exists  
if not os.path.isfile(config\_csvfile):  
 if config\_EduDocs == 'yes':  
 print("FEHLER!")  
 print("Die csv-Datei (" + config\_csvfile + "), die Sie in der config.xml eingetragen haben, existiert nicht. Bitte speichern Sie die Datei '" + config\_csvfile + "' im Hauptverzeichnis des Scripts oder bearbeiten Sie die config.xml")  
 input("Drücken Sie eine beliebige Taste, um zu bestätigen und den Prozess zu beenden.")  
 else:  
 print("ERROR!")  
 print("The csv-file (" + config\_csvfile + ") you specified in you config.xml does not exist. Please save '" + config\_csvfile + "' in main-directory of the script or edit your config.xml")  
 input("Press \[ANY KEY\] to confirm and end the process.")   
 sys.exit(1)

\# cut http and https from ncUrl, because people often just copy &amp; paste including protocol  
config\_ncUrl = config\_ncUrl.replace("http://", "")  
config\_ncUrl = config\_ncUrl.replace("https://", "")

\# TODO optional: read config from input() if config.xml empty  
\# print('Username of creator (admin?):')   
\# config\_adminname = input()  
\# print('Password of creator:')  
\# config\_adminpass = input()

config\_protocol = "https" # use a secure connection!  
config\_apiUrl = "/ocs/v1.php/cloud/users" # nextcloud API path (users), might change in the future  
config\_apiUrlGroups = "/ocs/v1.php/cloud/groups" # nextcloud API path (groups), might change in the future

\# Headers for CURL request, Nextcloud specific  
requestheaders = {  
 'OCS-APIRequest': 'true',  
}

\# set/create output-directory  
output\_dir = 'output'  
if not os.path.exists(output\_dir):  
 os.makedirs(output\_dir)

\# set/create temporary-directory  
tmp\_dir = 'tmp'  
if not os.path.exists(tmp\_dir):  
 os.makedirs(tmp\_dir)

\# adds date and time as string to variable  
today = datetime.now().strftime('%Y-%m-%d\_%H-%M-%S')

\# Mapping for umlauts and and special characters. The listed umlauts and special characters are automatically converted to a compatible spelling for the user name.  
mapping = {  
 ord(u"Ä"): u"Ae",  
 ord(u"ä"): u"ae",  
 ord(u"Ë"): u"E",  
 ord(u"ë"): u"e",  
 ord(u"Ï"): u"I",  
 ord(u"ï"): u"i",  
 ord(u"Ö"): u"Oe",  
 ord(u"ö"): u"oe",   
 ord(u"Ü"): u"Ue",  
 ord(u"ü"): u"ue",  
 ord(u"Ÿ"): u"Y",  
 ord(u"ÿ"): u"y",  
 ord(u"ß"): u"ss",  
 ord(u"À"): u"A",  
 ord(u"Á"): u"A",  
 ord(u"Â"): u"A",  
 ord(u"Ã"): u"A",  
 ord(u"Å"): u"A",  
 ord(u"Æ"): u"Ae",  
 ord(u"Ç"): u"C",  
 ord(u"È"): u"E",  
 ord(u"É"): u"E",  
 ord(u"Ê"): u"E",  
 ord(u"Ì"): u"I",  
 ord(u"Í"): u"I",  
 ord(u"Î"): u"I",  
 ord(u"Ð"): u"D",  
 ord(u"Ñ"): u"N",  
 ord(u"Ò"): u"O",  
 ord(u"Ó"): u"O",  
 ord(u"Ô"): u"O",  
 ord(u"Õ"): u"O",  
 ord(u"Ø"): u"Oe",  
 ord(u"Œ"): u"Oe",  
 ord(u"Ù"): u"U",  
 ord(u"Ú"): u"U",  
 ord(u"Û"): u"U",  
 ord(u"Ý"): u"Y",  
 ord(u"Þ"): u"Th",  
 ord(u"à"): u"a",  
 ord(u"á"): u"a",  
 ord(u"â"): u"a",  
 ord(u"ã"): u"a",  
 ord(u"å"): u"a",  
 ord(u"æ"): u"ae",  
 ord(u"ç"): u"c",  
 ord(u"è"): u"e",  
 ord(u"é"): u"e",  
 ord(u"ê"): u"e",  
 ord(u"ì"): u"i",  
 ord(u"í"): u"i",  
 ord(u"î"): u"i",  
 ord(u"ð"): u"d",  
 ord(u"ñ"): u"n",  
 ord(u"ò"): u"o",  
 ord(u"ó"): u"o",  
 ord(u"ô"): u"o",  
 ord(u"õ"): u"o",  
 ord(u"ø"): u"oe",  
 ord(u"œ"): u"oe",  
 ord(u"ù"): u"u",  
 ord(u"ú"): u"u",  
 ord(u"û"): u"u",  
 ord(u"ý"): u"y",  
 ord(u"þ"): u"Th",  
 ord(u"Š"): u"S",  
 ord(u"š"): u"s",  
 ord(u"Č"): u"C",  
 ord(u"č"): u"c"  
 }

\# QR-Code class  
qr = qrcode.QRCode(  
 version=1,  
 error\_correction=qrcode.constants.ERROR\_CORRECT\_L,  
 box\_size=10,  
 border=4,  
)

\# Function: Generate random password  
\# This will generate a random password with 1 random uppercase letter, 3 random lowercase letters,  
\# 3 random digits, and 1 random special character--this can be adjusted as needed.  
\# Then it combines each random character and creates a random order.  
def pwgenerator():  
 PWUPP = random.SystemRandom().choice(string.ascii\_uppercase)  
 PWLOW1 = random.SystemRandom().choice(string.ascii\_lowercase)  
 PWLOW2 = random.SystemRandom().choice(string.ascii\_lowercase)  
 PWLOW3 = random.SystemRandom().choice(string.ascii\_lowercase)  
 PWDIG1 = random.SystemRandom().choice(string.digits)  
 PWDIG2 = random.SystemRandom().choice(string.digits)  
 PWDIG3 = random.SystemRandom().choice(string.digits)  
 PWSPEC = random.SystemRandom().choice('!@\*(§')  
 PWD = None  
 PWD = PWUPP + PWLOW1 + PWLOW2 + PWLOW3 + PWDIG1 + PWDIG2 + PWDIG3 + PWSPEC  
 PWD = ''.join(random.sample(PWD,len(PWD)))  
 return(PWD)

\# display expected results before executing CURL  
 # display expected results for EduDocs-users  
if config\_EduDocs == 'yes':   
 usertable = \[\["Nutzername","Anzeigename","Passwort","E-Mail","Gruppen","Gruppen-Admin für","Speicherplatz"\]\]  
 with codecs.open(os.path.join(appdir, config\_csvfile),mode='r', encoding='utf-8') as csvfile:  
 readCSV = csv.reader(csvfile, delimiter=config\_csvDelimiter)  
 next(readCSV, None) # skip the headers  
 for row in readCSV:  
 if (len(row) != 7): # check if number of columns is consistent  
 print("FEHLER: Die Zeiles des Nutzers",html.escape(row\[0\]),"hat",len(row),"Spalten. Es müssen 7 sein. Bitte korrigieren Sie dies in der csv-Datei.")  
 input("Drücken Sie eine beliebige Taste, um den Prozess zu beenden.")  
 sys.exit(1)  
 pass\_anon = html.escape(row\[2\])  
 if len(pass\_anon) &gt; 0:  
 pass\_anon = "\*" \* (len(pass\_anon)) # replace password for display on CLI  
 line = html.escape(row\[0\])  
 row\[0\] = line.translate(mapping) # convert special characters and umlauts  
 if row\[4\]:  
 grouplist = html.escape(row\[4\]).split(config\_csvDelimiterGroups) # Groups in the CSV-file are split by semicolon --&gt; load into list  
 if grouplist: # if grouplist contains group SchuelerInnen or Lehrkraefte, remove it  
 if "SchuelerInnen" in grouplist:  
 grouplist.remove('SchuelerInnen')  
 if "Lehrkraefte" in grouplist:  
 grouplist.remove('Lehrkraefte')  
 grouplist.append(config\_schoolgroup) # and add group which is set in config-file (config\_schoolgroup)  
 if not config\_schoolgroup == 'SchuelerInnen': # if you import students in an EduDocs-instance, it is not possible to set groupadmins  
 if row\[5\]:  
 groupadminlist = html.escape(row\[5\]).split(config\_csvDelimiterGroups) # Groupadmin Values in the CSV-file are split by semicolon --&gt; load into list  
 else:  
 groupadminlist = \[\]  
 else:  
 groupadminlist = \[\]  
 currentuser = \[html.escape(row\[0\]),html.escape(row\[1\]),pass\_anon,html.escape(row\[3\]),grouplist,groupadminlist,html.escape(row\[6\])\]  
 usertable.append(currentuser)  
 print(tabulate(usertable,headers="firstrow"))

 # ask EduDocs-user to check values and continue  
 print("\\nÜberprüfen Sie genau, ob die oben aufgeführten Nutzerdaten und Gruppenzuordnungen korrekt sind.")  
 if not config\_GeneratePassword == 'yes':  
 print ("ACHTUNG: Sie haben festgelegt, dass Nutzer, bei denen kein Passwort eingetragen wurde, eine E-Mail erhalten, um sich selbst ein Passwort zu setzen. Bitte überprüfen Sie unbedingt, dass bei jedem Nutzer, bei dem kein Passwort vorgegeben ist, eine korrekte E-Mailadresse eingetragen ist!")  
 print("Wenn alles korrekt ist, drücken Sie eine beliebige Taste, um den Import-Prozess zu starten.")  
 input("Wenn nicht, drücken Sie \[Strg + C\], um abzubrechen.")  
 print("")  
 print("\\nSie haben den Import-Prozess gestartet. Die Nutzer und Gruppen werden nun angelegt. Dies kann viel Zeit in Anspruch nehmen...\\n")

 # display expected results for nextcloud-users  
else:   
 usertable = \[\["Username","Display name","Password","Email","Groups","Group admin for","Quota"\]\]  
 with codecs.open(os.path.join(appdir, config\_csvfile),mode='r', encoding='utf-8') as csvfile:  
 readCSV = csv.reader(csvfile, delimiter=config\_csvDelimiter)  
 next(readCSV, None) # skip the headers  
 for row in readCSV:  
 if (len(row) != 7): # check if number of columns is consistent  
 print("ERROR: row for user",html.escape(row\[0\]),"has",len(row),"columns. Should be 7. Please correct your csv-file.")  
 input("Press \[ANY KEY\] to confirm and end the process.")  
 sys.exit(1)  
 pass\_anon = html.escape(row\[2\])  
 if len(pass\_anon) &gt; 0:  
 pass\_anon = "\*" \* (len(pass\_anon)) # replace password for display on CLI  
 line = html.escape(row\[0\])  
 row\[0\] = line.translate(mapping) # convert special characters and umlauts  
 currentuser = \[html.escape(row\[0\]),html.escape(row\[1\]),pass\_anon,html.escape(row\[3\]),html.escape(row\[4\]),html.escape(row\[5\]),html.escape(row\[6\])\]  
 usertable.append(currentuser)  
 print(tabulate(usertable,headers="firstrow"))

 # ask user to check values and continue  
 print("\\nPlease check if the users and groups above are as expected and should be created like that.")  
 if not config\_GeneratePassword == 'yes':  
 print ("ATTENTION: You have specified that users for whom no password has been entered will receive an e-mail to set a password for themselves. Please make absolutely sure that a correct e-mail address is entered for every user for whom no password has been set!")  
 input("If everything is fine, press \[ANY KEY\] to continue. If not, press \[CONTROL + C\] to cancel.")  
 print("\\nYou confirmed. I will now create the users and groups. This can take a long time...\\n")

\# prepare pdf-output (if pdfOneDoc == yes)  
if config\_pdfOneDoc == 'yes':  
 if config\_EduDocs == 'yes':  
 output\_filename = config\_schoolgroup + "\_" + today + ".pdf"  
 else:  
 output\_filename = "userlist\_" + today + ".pdf"  
 output\_filepath = os.path.join( output\_dir, output\_filename )   
 doc = SimpleDocTemplate(output\_filepath,pagesize=A4,  
 rightMargin=72,leftMargin=72,  
 topMargin=72,bottomMargin=18)  
\# prepare pdf-content  
Story=\[\]

\# read rows from CSV file  
with codecs.open(os.path.join(appdir, config\_csvfile),mode='r', encoding='utf-8') as csvfile:  
 readCSV = csv.reader(csvfile, delimiter=config\_csvDelimiter)  
 next(readCSV, None) # skip the headers  
 for row in readCSV:  
 line = html.escape(row\[0\])  
 row\[0\] = line.translate(mapping) # convert special characters and umlauts  
 if config\_GeneratePassword == 'yes':  
 if not row\[2\]:  
 row\[2\] = pwgenerator()  
 if config\_EduDocs == 'yes':   
 if row\[4\]:  
 grouplist = html.escape(row\[4\]).split(config\_csvDelimiterGroups) # Groups in the CSV-file are split by semicolon --&gt; load into list  
 if grouplist: # if grouplist contains group SchuelerInnen or Lehrkraefte, remove it  
 if "SchuelerInnen" in grouplist:  
 grouplist.remove('SchuelerInnen')  
 if "Lehrkraefte" in grouplist:  
 grouplist.remove('Lehrkraefte')  
 grouplist.append(config\_schoolgroup) # and add group which is set in config-file (config\_schoolgroup)  
 if not config\_schoolgroup == 'SchuelerInnen': # if you import students in an EduDocs-instance, it is not possible to set groupadmins  
 if row\[5\]:  
 groupadminlist = html.escape(row\[5\]).split(config\_csvDelimiterGroups) # Groupadmin Values in the CSV-file are split by semicolon --&gt; load into list  
 else:  
 groupadminlist = \[\]  
 else:  
 groupadminlist = \[\]  
 print("Nutzername:",html.escape(row\[0\]),"| Anzeigename:",html.escape(row\[1\]),"| Passwort: ","\*" \* len(row\[2\]) +   
 "| E-Mail:",html.escape(row\[3\]),"| Gruppen:",grouplist,"| Gruppen-Admin für:",groupadminlist,"| Speicherplatz:",html.escape(row\[6\]),)  
 else:  
 print("Username:",html.escape(row\[0\]),"| Display name:",html.escape(row\[1\]),"| Password: ","\*" \* len(row\[2\]) +   
 "| Email:",html.escape(row\[3\]),"| Groups:",html.escape(row\[4\]),"| Group admin for:",html.escape(row\[5\]),"| Quota:",html.escape(row\[6\]),)  
 # build the dataset for the request  
 data = \[  
 ('userid', html.escape(row\[0\])),  
 ('displayName', html.escape(row\[1\])),   
 ('password', html.escape(row\[2\])),  
 ('email', html.escape(row\[3\])),  
 ('quota', html.escape(row\[6\])),  
 ('language', config\_language)  
 \]

 # if value exists: append single groups to data array/list for CURL  
 if not config\_EduDocs == 'yes':   
 if row\[4\]:  
 grouplist = html.escape(row\[4\]).split(config\_csvDelimiterGroups) # Groups in the CSV-file are split by semicolon --&gt; load into list  
 else:  
 grouplist = \[\]  
 # check if group exists   
 for group in grouplist:  
 try:  
 groupresponse = requests.get(config\_protocol + '://' + config\_adminname + ':' + config\_adminpass + '@' +   
 config\_ncUrl + config\_apiUrlGroups + '?search=' + group.strip(), headers=requestheaders, verify=config\_sslVerify)  
 except requests.exceptions.RequestException as e: # handling errors  
 print(e)  
 print("The CURL request could not be performed.")  
 input("Press \[ANY KEY\] to confirm and end the process.")  
 sys.exit(1)

 response\_xmlsoup = BeautifulSoup(groupresponse.text, "html.parser")

 # if group does not exists, create group  
 if not response\_xmlsoup.find('element'):  
 try:  
 groupdata = {  
 'groupid':group.strip()  
 }  
 groupresponse = requests.post(config\_protocol + '://' + config\_adminname + ':' + config\_adminpass + '@' +   
 config\_ncUrl + config\_apiUrlGroups, headers=requestheaders, data=groupdata, verify=config\_sslVerify)  
 except requests.exceptions.RequestException as e: # handling errors  
 print(e)  
 print("The CURL request could not be performed.")  
 input("Press \[ANY KEY\] to confirm and end the process.")  
 sys.exit(1)  
 response\_xmlsoup = BeautifulSoup(groupresponse.text, "html.parser")

 # catch wrong config (create group)  
 if groupresponse.status\_code != 200:  
 print("HTTP Status: " + str(groupresponse.status\_code))  
 print("Your config.xml is wrong or your cloud is not reachable.")  
 input("Press \[ANY KEY\] to confirm and end the process.")  
 sys.exit(1)

 # show detailed info of response (create group)  
 response\_xmlsoup = BeautifulSoup(groupresponse.text, "html.parser")  
 print('Create group "' + group.strip() + '": ' + response\_xmlsoup.find('status').string + ' ' + response\_xmlsoup.find('statuscode').string +   
 ' = ' + response\_xmlsoup.find('message').string)

 data.append(('groups\[\]', group.strip())) # groups is parameter NC API

 # if value exists: append group admin values to data array/list for CURL  
 if not config\_EduDocs == 'yes': # if you import students in an EduDocs-Instance, it is not possible to set groupadmins  
 if row\[5\]:  
 groupadminlist = html.escape(row\[5\]).split(config\_csvDelimiterGroups) # Groupadmin Values in the CSV-file are split by semicolon --&gt; load into list  
 try:  
 for groupadmin in groupadminlist:   
 data.append(('subadmin\[\]', groupadmin.strip())) # subadmin is parameter NC API  
 except NameError:  
 print("groupadminlist is not defined")

 # perform the request  
 try:  
 response = requests.post(config\_protocol + '://' + config\_adminname + ':' + config\_adminpass + '@' +   
 config\_ncUrl + config\_apiUrl, headers=requestheaders, data=data, verify=config\_sslVerify)  
 except requests.exceptions.RequestException as e: # handling errors  
 print(e)  
 print("The CURL request could not be performed.")  
 input("Press \[ANY KEY\] to confirm and end the process.")  
 sys.exit(1)

 # catch wrong config  
 if response.status\_code != 200:  
 print("HTTP Status: " + str(response.status\_code))  
 print("Your config.xml is wrong or your cloud is not reachable.")  
 input("Press \[ANY KEY\] to confirm and end the process.")  
 sys.exit(1)

 # show detailed info of response  
 response\_xmlsoup = BeautifulSoup(response.text, "html.parser")  
 print(response\_xmlsoup.find('status').string + ' ' + response\_xmlsoup.find('statuscode').string +   
 ' = ' + response\_xmlsoup.find('message').string)

 # append detailed response to logfile in output-folder  
 logfile = codecs.open(os.path.join(output\_dir,'output.log'),mode='a', encoding='utf-8')  
 logfile.write("\\nUSER: " + html.escape(row\[0\]) + "\\nTIME: " + time.strftime("%d.%m.%Y %H:%M:%S",time.localtime(time.time())) +   
 "\\nRESPONSE: " + response\_xmlsoup.find('status').string + ' ' + response\_xmlsoup.find('statuscode').string +   
 ' = ' + response\_xmlsoup.find('message').string + "\\n")  
 logfile.close()

 # A QR code and a PDF file are only generated if the user has been successfully created.

 if response\_xmlsoup.find('statuscode').string == "100":  
 # generate qr-code  
 qr.add\_data("nc://login/user:" + html.escape(row\[0\]) + "&amp;password:" + html.escape(row\[2\]) + "&amp;server:https://" + config\_ncUrl)  
 img = qr.make\_image(fill\_color="black", back\_color="white")  
 img.save(os.path.join( tmp\_dir, html.escape(row\[0\]) + ".jpg" ))  
 qr.clear()

 # prepare pdf-output (if pdfOneDoc == no)  
 if config\_pdfOneDoc == 'no':  
 if config\_EduDocs == 'yes':  
 output\_filename = config\_schoolgroup + "\_" + html.escape(row\[0\]) + "\_" + today + ".pdf"  
 else:  
 output\_filename = html.escape(row\[0\]) + "\_" + today + ".pdf"  
   
 output\_filepath = os.path.join( output\_dir, output\_filename )  
   
 doc = SimpleDocTemplate(output\_filepath,pagesize=A4,  
 rightMargin=72,leftMargin=72,  
 topMargin=52,bottomMargin=18)

 if config\_EduDocs == 'yes':  
 nclogo = "assets/EduDocs\_Logo.jpg" # EduDocs-logo (if in EduDocs-mode)  
 else:  
 nclogo = "assets/Nextcloud\_Logo.jpg" # nextcloud-logo (if in normal mode)  
 ncuserlogin = html.escape(row\[0\]) # loginname  
 ncusername = html.escape(row\[1\]) # username  
 ncpassword = html.escape(row\[2\]) # password  
 nclink = config\_protocol + "://" + config\_ncUrl # adds nextcloud-url  
 # adds nextcloud-logo to pdf-file   
 if config\_EduDocs == 'yes':  
 im = Image(nclogo, 150, 87)  
 else:  
 im = Image(nclogo, 150, 106)  
 Story.append(im)  
 Story.append(Spacer(1, 12))

 styles=getSampleStyleSheet()  
 styles.add(ParagraphStyle(name='Justify', alignment=TA\_JUSTIFY))  
 # adds text to pdf-file  
 if config\_EduDocs == 'yes':  
 ptext = '&lt;font size=14&gt;Hallo %s,&lt;/font&gt;' % ncusername  
 else:  
 ptext = '&lt;font size=14&gt;Hello %s,&lt;/font&gt;' % ncusername  
 Story.append(Paragraph(ptext, styles\["Justify"\]))  
 Story.append(Spacer(1, 12))

 if config\_EduDocs == 'yes':  
 if config\_schoolgroup == 'SchuelerInnen':  
 ptext = '&lt;font size=14&gt;Für dich wurde ein Edu-Docs-Account angelegt.&lt;/font&gt;'  
 else:  
 ptext = '&lt;font size=14&gt;Für Sie wurde ein Edu-Docs-Account angelegt.&lt;/font&gt;'  
 else:  
 ptext = '&lt;font size=14&gt;a Nextcloud-account has been generated for you.&lt;/font&gt;'  
 Story.append(Paragraph(ptext, styles\["Justify"\]))  
 Story.append(Spacer(1, 12))

 if config\_EduDocs == 'yes':  
 if config\_schoolgroup == 'SchuelerInnen':  
 ptext = '&lt;font size=14&gt;Du kannst dich mit folgenden Nutzerdaten einloggen:&lt;/font&gt;'  
 else:  
 ptext = '&lt;font size=14&gt;Sie können sich mit folgenden Nutzerdaten einloggen:&lt;/font&gt;'  
 else:  
 ptext = '&lt;font size=14&gt;You can login with the following user data:&lt;/font&gt;'  
 Story.append(Paragraph(ptext, styles\["Normal"\]))  
 Story.append(Spacer(1, 36))

 if config\_EduDocs == 'yes':  
 if config\_schoolgroup == 'SchuelerInnen':  
 ptext = '&lt;font size=14&gt;Link zu deiner EduDocs-Instanz:&lt;/font&gt;'  
 else:  
 ptext = '&lt;font size=14&gt;Link zu Ihrer EduDocs-Instanz:&lt;/font&gt;'  
 else:  
 ptext = '&lt;font size=14&gt;Link to your Nextcloud:&lt;/font&gt;'  
 Story.append(Paragraph(ptext, styles\["Normal"\]))  
 Story.append(Spacer(1, 12))

 ptext = '&lt;font size=14&gt;%s&lt;/font&gt;' % nclink  
 Story.append(Paragraph(ptext, styles\["Normal"\]))  
 Story.append(Spacer(1, 24))

 if config\_EduDocs == 'yes':  
 ptext = '&lt;font size=14&gt;Nutzername:&lt;/font&gt;'  
 else:  
 ptext = '&lt;font size=14&gt;Username:&lt;/font&gt;'  
 Story.append(Paragraph(ptext, styles\["Normal"\]))  
 Story.append(Spacer(1, 12))

 ptext = '&lt;font size=14&gt;%s&lt;/font&gt;' % ncuserlogin  
 Story.append(Paragraph(ptext, styles\["Normal"\]))  
 Story.append(Spacer(1, 24))

 if config\_EduDocs == 'yes':  
 ptext = '&lt;font size=14&gt;Passwort:&lt;/font&gt;'  
 else:  
 ptext = '&lt;font size=14&gt;Password:&lt;/font&gt;'  
 Story.append(Paragraph(ptext, styles\["Normal"\]))  
 Story.append(Spacer(1, 12))

 ptext = '&lt;font size=14&gt;%s&lt;/font&gt;' % ncpassword  
 Story.append(Paragraph(ptext, styles\["Normal"\]))  
 Story.append(Spacer(1, 24))

 if config\_EduDocs == 'yes':  
 if config\_schoolgroup == 'SchuelerInnen':  
 ptext = '&lt;font size=14&gt;Alternativ kannst du mithilfe der Nextcloud-App folgenden QR-Code scannen:&lt;/font&gt;'  
 else:  
 ptext = '&lt;font size=14&gt;Alternativ können Sie mithilfe der Nextcloud-App folgenden QR-Code scannen:&lt;/font&gt;'  
 else:  
 ptext = '&lt;font size=14&gt;Alternatively, you can scan the following QR-Code in the Nextcloud app:&lt;/font&gt;'  
 Story.append(Paragraph(ptext, styles\["Normal"\]))  
 Story.append(Spacer(1, 24))   
 # adds qr-code to pdf-file  
 im2 = Image(os.path.join( tmp\_dir, html.escape(row\[0\]) + ".jpg" ), 200, 200)  
 Story.append(im2)  
 del im2  
 if config\_pdfOneDoc == 'no':  
 # create pdf-file (single documents)  
 doc.build(Story)   
 else:  
 Story.append(PageBreak())  
 # create pdf-file (one document)  
if config\_pdfOneDoc == 'yes':  
 doc.build(Story)

\# Clean up tmp-folder  
filelist = \[ f for f in os.listdir(tmp\_dir) \]  
for f in filelist:  
 os.remove(os.path.join(tmp\_dir, f))

if config\_EduDocs == 'yes':  
 print("")  
 print("###################################################################################")  
 print("# Kontrollieren Sie den Status-Code der Nutzergenerierung oben oder in #")  
 print("# der output.log-Datei im Verzeichnis des Import-Scripts. #")  
 print("# Die erfolgreich importierten Nutzer sollten zudem nun in Ihrer EduDocs-Instanz #")  
 print("# zu sehen sein. #")  
 print("# #")  
 print("# Es wurde für jeden Nutzer eine PDF-Seite mit Infos zur Anmeldung generiert. #")  
 print("# #")  
 print("# Löschen Sie zu Ihrer Sicherheit unbedingt die Zugangsdaten aus der config.xml. #")  
 print("###################################################################################")  
 print("")  
 input("Drücken Sie eine beliebige Taste, um den Prozess zu beenden.")  
else:  
 print("")  
 print("###################################################################################")  
 print("# Control the status codes of the user creation above or in the output.log. #")  
 print("# You should as well see the users in your Nextcloud now. #")  
 print("# #")  
 print("# A PDF-File with login-info and qr-code has been generated for every user. #")  
 print("# #")  
 print("# For security reasons: please delete your credentials from config.xml #")  
 print("###################################################################################")  
 print("")  
 input("Press \[ANY KEY\] to confirm and end the process.")

</details>---

stelle raussuchen wo die config.xml uns die users.csv deklariert sind

```
# read config from xml file
configfile = codecs.open(os.path.join(appdir,'config.xml'),mode='r', encoding='utf-8')
config = configfile.read()
configfile.close()
...

ändern in


...
#wichtig ganz am anfang des script wenn nicht schon vorhanden import os angeben
# Der Pfad zur AppImage-Datei
appimage_path = os.environ.get("APPIMAGE", "")

# Das Verzeichnis, aus dem die AppImage-Datei ausgeführt wird
appimage_dir = os.path.dirname(appimage_path)

# read config from xml file
configfile = codecs.open(os.path.join(appimage_dir, "config.xml"),mode='r', encoding='utf-8')
config = configfile.read()
configfile.close()
...

In diesem Python script wird die CSV Datei bzw der Pfad dazu aus der config.xml geladen

```

Aber generell gillt für jedes script:

```
#wichtig ganz am anfang des script wenn nicht schon vorhanden import os angeben
# Der Pfad zur AppImage-Datei
appimage_path = os.environ.get("APPIMAGE", "")

# Das Verzeichnis, aus dem die AppImage-Datei ausgeführt wird
appimage_dir = os.path.dirname(appimage_path)

# der neue os.path teil:
#wenn der Dateiname als string übergeben wird
os.path.join(appimage_dir, "config.xml") 
wenn der Dateiname als variable übergeben wird
os.path.join(appimage_dir, configfile)
```

# Appimage für Java 8 zum starten von jlnp Dateien

Beschreibung:

Wer ein altes ipmi hat und die Remote console braucht, muss Java 8 installiert haben.  
Allerdings wird Java 8 schon lange nicht mehr supported, also bauen wir uns ein Appimage

Vorbereitung:

Unter [https://adoptium.net/](https://adoptium.net/)

java 8 LTS auswählen und downloaden dann haben wir ein tar gz Datei

Diese entpacken wir via Terminal, vorher Verzeichnis erstellen

```
mkdir jre8
tar -xzf OpenJDK8U-jdk_x64_linux_hotspot_8u422b05.tar.gz -C jre8
```

Nun Erstellen wir uns unser Appimage Verzeichnis mit folgender Struktur

```
mkdir AppDir
```

In diesem verzeichnis kommen diese Dateien / Verzeichnis

```
AppDir/
|-- AppRun
|-- jre8/
|-- myapp.desktop
|-- myapp.png (optional)

```

- **`AppRun`**: Eine ausführbare Datei, die den Start des AppImages steuert.
- **`jre8/`**: Verschiebe das entpackte JRE-Verzeichnis hierhin.
- **`myapp.desktop`**: Eine Desktop-Datei, die Metainformationen über die App enthält.
- **`myapp.png`**: Icon für die App, ist Pflicht (maximal 256x256 Pixel groß.

Inhalt der AppRun,

Diese Datei sorgt dafür, dass `javaws` aus der Java 8 Runtime mit den übergebenen Parametern aufgerufen wird.

```
#!/bin/bash
HERE="$(dirname "$(readlink -f "${0}")")"
"${HERE}/jre8/bin/javaws" "$@"

```

Datei ausführbar machen

```
chmod +x AppRun
```

Nun die myapp.desktop anlegen

```
nano myapp.desktop
```

Inhalt

Desktop Entry ( icon, die Grafik Datei muss dann myapp.png heißen und darf maxiimal 256x 256 Pixel groß sein.)

```
[Desktop Entry]
Name=Java 8 Runtime
Exec=AppRun %F
Icon=myapp
Type=Application
Categories=Utility;
```

Nun noch das jre8 verzeichnis in AppDir verschieben

Nun Verzeichnisberechtigungen setzten

```
chmod -R 755 AppDir/
```

Appimage erstellen, wir haben ein x64 System.  
Wir übergeben Das Verzeichnis

```
ARCH=x86_64 ./appimagetool.AppImage AppDir
```

Wenn kein Icon Datei vorhanden gibts diese Meldung, da das Icon nicht existiert.  
Dazu in der AppDir eine Icon Datei erstellen, mit dem Namen myapp.png  
Diese darf maximal 256x256 Pixel beinhalten. Für unser Java Programm hab ich das Icon mal angehängt.

Ausgabe:

```
ARCH=x86_64 ./appimagetool.AppImage AppDir
appimagetool, continuous build (commit 5735cc5), build <local dev build> built on 2023-03-08 22:52:04 UTC
Using architecture x86_64
/home/duffy/Downloads/AppDir should be packaged as Java_8_Runtime-x86_64.AppImage
myapp{.png,.svg,.xpm} defined in desktop file but not found
For example, you could put a 256x256 pixel png into
/home/duffy/Downloads/AppDir/myapp.png

```

Ausgabe wenns geklappt hat:

```
ARCH=x86_64 ./appimagetool.AppImage AppDir
appimagetool, continuous build (commit 5735cc5), build <local dev build> built on 2023-03-08 22:52:04 UTC
Using architecture x86_64
/home/duffy/Downloads/AppDir should be packaged as Java_8_Runtime-x86_64.AppImage
Deleting pre-existing .DirIcon
Creating .DirIcon symlink based on information from desktop file
WARNING: AppStream upstream metadata is missing, please consider creating it
         in usr/share/metainfo/myapp.appdata.xml
         Please see https://www.freedesktop.org/software/appstream/docs/chap-Quickstart.html#sect-Quickstart-DesktopApps
         for more information or use the generator at http://output.jsbin.com/qoqukof.
Generating squashfs...
Parallel mksquashfs: Using 16 processors
Creating 4.0 filesystem on Java_8_Runtime-x86_64.AppImage, block size 131072.
[===========================================================================================|] 1910/1910 100%

Exportable Squashfs 4.0 filesystem, gzip compressed, data block size 131072
	compressed data, compressed metadata, compressed fragments,
	compressed xattrs, compressed ids
	duplicates are removed
Filesystem size 101505.87 Kbytes (99.13 Mbytes)
	50.82% of uncompressed filesystem size (199752.02 Kbytes)
Inode table size 9238 bytes (9.02 Kbytes)
	42.01% of uncompressed inode table size (21991 bytes)
Directory table size 5162 bytes (5.04 Kbytes)
	49.62% of uncompressed directory table size (10404 bytes)
Number of duplicate files found 20
Number of inodes 494
Number of files 407
Number of fragments 48
Number of symbolic links  3
Number of device nodes 0
Number of fifo nodes 0
Number of socket nodes 0
Number of directories 84
Number of ids (unique uids + gids) 1
Number of uids 1
	root (0)
Number of gids 1
	root (0)
Embedding ELF...
Marking the AppImage as executable...
Embedding MD5 digest
Success

Please consider submitting your AppImage to AppImageHub, the crowd-sourced
central directory of available AppImages, by opening a pull request
at https://github.com/AppImage/appimage.github.io

```

Nun liegt in diesem Fall bei im Verzeichnis Downloads da.

[![Auswahl_1271.png](https://wiki.hacker-net.de/uploads/images/gallery/2024-09/scaled-1680-/Uyl3SK3jJQW1vYHd-auswahl-1271.png)](https://wiki.hacker-net.de/uploads/images/gallery/2024-09/Uyl3SK3jJQW1vYHd-auswahl-1271.png)