Python (+Beem) scripts on your phone | Python-Scripts (+Beem) auf deinem Händi [EN | DE]

in Programming & Dev2 years ago

EnglishLanguage.png

Hello Hivian,

Isn't it mind-blowing what phones can do these days. Today, virtually all of us are carrying computers with us every day that can compete with the performance of a modern desktop PC.
Just a few years ago, mobile phones were still on the level of pocket calculators in terms of computing power. And when my enthusiasm for programming computers began (1986/87), a mobile phone with the power of a desktop PC would have weighed many tons. The battery of this fictitious device would probably even send a small cargo ship to the bottom of the sea.

Since I recently became aware of the power of my mobile communication computer again, when I was thinking about a more energy-saving alternative to my home server (old desktop PC), I got the idea to use my mobile phone for this purpose.
My home server just had to run fairly simple tasks anyway. Such as a monitoring tool for Git repositories, a household management server, backup scripts, and other minor tasks such as a couple of Hive bots. Most of these tasks were defined in Python scripts. Some of these scripts make use of the Beem package for Python, which allows you to use the Hive API services with Python.
None of this tasks would require computational power that could break the little guy's heart.

How I successfully managed to turn my Android phone into a mini but nice and Linux powered, Python(+Beem) capable home server, I would like to tell you about in this post.

NO ROOT REQUIRED !!!

GermanLanguage.png

Hallo Hivianer,

Wahnsinn, was Telefone heutzutage alles können. Fast jeder von uns führt heute täglich einen Computer mit sich, der sich mit der Leistungsfähigkeit eines Desktop-PCs messen lässt.
Noch vor ein paar Jahren, waren Mobil-Telefone in Sachen Rechenleistung noch auf Taschenrechner-Niveau. Und als ich damals anfing Computer zu programmieren (1986/87), wäre ein Mobil-Telefon mit der Leistungsfähigkeit eines heutigen Desktop-PCs, noch mehrere Tonnen schwer gewesen. Der Akku, dieses fiktiven Gerätes, würde wohl sogar ein kleines Frachtschiff versenken.

Da mir die Kraft meines mobilen Kommunikations-Computers neulich mal wieder so richtig bewusst wurde, als ich mir Gedanken über eine stromsparendere Alternative zu meinem Heimserver (alter Desktop-PC) machte, kam mir die Idee, kurzerhand mein Mobil-Telefon dazu zu verwenden.
Auf meinem Heimserver liefen ohnehin nur recht einfache Aufgaben, wie z.B. ein Monitoring-Werkzeug für Git Repositories, ein Haushaltsverwaltung-Server, Backup-Scripts und einige kleinere Aufgaben, wie z.B. ein paar Hive-Bots. Die meisten dieser Aufgaben sind in Python-Scripts definiert und einige nutzen das Beem-Paket für Python, mit welchem man die Hive-API Dienste unter Python nutzen kann.
Nichts davon würde Rechenkraft erfordern, die dem kleinen Kerl das Herz zerreisen könnte.

Wie ich es erfolgreich anstellte, aus meinem Android-Telefon einen kleinen aber feinen, Linux betriebenen, Python(+Beem) fähigen, Heimserver zu machen, möchte ich dir gerne in diesem Beitrag erzählen.

KEIN ROOT ERFORDERLICH !!!


Cover image | Titelbild

The cover image was created by myself in Blender.
Das Titelbild wurde von mir in Blender gemacht.

EnglishLanguage.png

Running Linux on Android? O_o

It' s well known to the nerds and tech geeks among us - Android runs on Linux on the phone, basically.
Yes, really!
Linux represents the lowest layer of the operating system on Android devices. This is followed by the so-called hardware abstraction layer, or HAL for short. HAL provides the overlying OS layer with routines for handling the hardware.
Above that, in another layer, there are some native runtime libraries and the Android runtime environment, which is also just a piece of software that runs on Linux.
One layer above that is the Java API, i.e. public Android functions that are used by Android apps.

Normal Android users usually do not notice anything from the Linux brain of their device. Of course, this is intentional. After all, Android is designed to be a simple operating system that can be used by everyone. Even people without any technical knowledge.
Maybe that's why Android devices don't come with apps that could unlock the potential of the Linux base.

But there are some well working terminal emulators for the operating system. For example Termux.
Termux is an Android terminal emulator and app for using a Linux environment.
It works straight out of the box with no rooting or setup required. A minimal base system comes with the app. Additional packages can be installed via a package manager.

How to install and set up Termux

  1. First, of course, the Termux app must be downloaded. I recommend using the FOSS app catalog F-Droid as a source for this.
  2. Once the app is downloaded, install it on your device.
  3. Open the app. Right after the app is started, you will see this on your screen:
    image.png
    You can find some information about the package manager on it. We're going to work with this tool in the lines below.
    First of all, tell the package manager to update all packages:
    pkg update && pkg upgrade.
  4. Install Python3.x by typing the command as shown below into the command line.
    pkg install python
  5. To be able to also run Hive-related Python scripts, you can install the Beem Python package. Usually you can just install it via PIP and then start using it. However, your device most likely does not have OpenSSL installed yet, which is required by the Cryptography package that Beem depends on. So OpenSSL must be installed first. Otherwise, PIP will spit out some error messages when installing Beem.
    OpenSSL can be installed using the command line below.
    pkg install openssl
    Now the Cryptography package can be installed.
    pip3 install -U cryptography
    Beem is now ready for installation.
    pip3 install -U beem
    Congratulations! You are now able to run Python3 scripts on your "phone" and even use the Hive API in Python via Beem.
  6. One of the most essential services on my home server was the cronjob service. An automated, time-controlled way to start all my Python scripts.
    You do not need to miss this useful service in Termux. To install it you can use the command line below.
    pkg install cronie termux-services
    It may happen that the Crontab service cannot be activated yet during the current session. Just start a new session. You just have to swipe from the left edge of the terminal area to the right to the center. A UI panel will open. Press the "New session" button there.
    In this new session you can now start the cronjob service by using the command line below.
    sv-enable crond
    More about the crontab service and how to create your own cronjobs can be found in the Manpages.
  7. Of course, the Crontab service can only run as long as a Termux session is active and the app is only as active as the CPU of the device it is running on. To prevent Android from sending the CPU in sleep mode, you need to make sure that Termux keeps it from doing so. To do this, open your phone's notification tray and click the small arrow on the Termux entry. After that the button "Acquire wakelock" will be visible. Press this button to make Termux prevent the CPU from falling asleep.
    image.png
    8.No doubt you will also want to be able to copy files from the Android environment to the Termux environment and access files in the Termux environment.
    To access the shared storage (/sdcard or /storage/emulated/0), Termux must have a storage access permission. It is not granted by default and is not requested when the application is started, as it is not required for standard operation. However, this can be done by entering the command below on the prompt line:
    termux-setup-storage.
    Usually a dialog window will open asking you to confirm the required permission. Here you can safely press "Grant permission".
    Check if you have access to shared storage by entering the command below:
    ls ~/storage/shared.
    If you are denied access, something has gone wrong in the permission granting process. This is a known problem. In this case, remove the "Storage" permission using the app settings and assign it again.

GermanLanguage.png

Linux unter Android? O_o

Die Nerds und Technik-Geeks unter uns wissen es - Android läuft quasi unter Linux auf dem Telefon.
Ja, wirklich!
Linux bildet auf Android-Geräten die unterste Schicht des Betriebssystems. Darauf folgt der sogenannte Hardware-Abstraction-Layer, kurz HAL. HAL bietet der überliegenden Betriebsystem-Schicht Routinen zum Umgang mit der Hardware.
Darüber liegen in einer weiteren Schicht, die nativen Laufzeit-Bibliotheken und die Android-Laufzeitumgebung, welches letztlich auch nur eine Software ist, die unter einem Linux läuft.
Eine Schicht darüber, liegt die Java API, also öffentliche Android-Funktionen, die von den Android-Apps verwendet werden.

Als normaler Android-Benutzer, bekommt man vom Linux-Gehirn seines Gerätes gar nichts mit. Das ist natürlich gewollt. Denn Android soll ja schließlich ein einfaches Betriebssystem darstellen, das von jedem Menschen verwendet werden kann. Auch ohne technische Vorbildung.
Eventuell werden Android-Geräte daher auch nicht mit Apps ausgeliefert, welche das potential des Linux-Unterbaus freilegen könnten.

Aber es gibt einige gut funktionierende Terminal-Emulatoren für das Betriebssystem. Z.B. Termux.
Termux ist ein Android-Terminalemulator und eine App zur Verwendung einer Linux-Umgebung.
Sie funtioniert direkt und ohne dass ein Rooting oder eine Einrichtung erforderlich ist. Mit der App kommt ein minimales Basissystem. Zusätzliche Pakete können über einen Paketmanager bezogen werden.

Termux installieren und einrichten

  1. Zuerst muss natürlich die Termux-App herunter geladen werden. Ich empfehle hierzu als Quelle den FOSS-App Katalog F-Droid.
  2. Sobald die App herunter geladen wurde, installiere sie auf deinem Gerät.
  3. Öffne die App. Direkt nach dem Start der App, siehst du folgendes auf deinem Bildschirm:
    image.png
    Du findest darauf einige Informationen zum Paketmanager. Wir werden im Laufe der folgenden Zeilen mit diesem Tool arbeiten.
    Weise nun zu allererst den Paketmanager an, alle Paket auf den neuesten Stand zu bringen:
    pkg update && pkg upgrade
  4. Installiere Python3.x, indem du folgendes Kommando in die Kommandozeile eingibst.
    pkg install python
  5. Um auch Python-Scripts mit Hive-Bezug ausführen zu können, kannst du das Python-Paket Beem installieren. Normalerweise kann man das einfach per PIP installieren und drauf los nutzen. Allerdings ist auf deinem Gerät höchstwahrscheinlich noch kein OpenSSL installiert, welches vom Cryptography-Paket vorausgesetzt wird, von dem Beem abhängt. Also muss zunächst OpenSSL installiert werden. Ansonsten spuckt PIP bei der Installation von Beem ein paar Fehlermeldungen aus.
    OpenSSL kann mit folgender Befehlszeile installiert werden.
    pkg install openssl
    Nun kann das Cryptography-Paket installiert werden.
    pip3 install -U cryptography
    Bemm ist nun bereits zur Installation.
    pip3 install -U beem
    Gratulation! Du kannst nun Python3-Scripts auf deinem "Telefon" ausführen und sogar die Hive API in Python via Beem nutzen.
  6. Ein essentieller Dienst auf meinem Heimserver, war der Cronjob-Dienst, mit welchem ich all meine Python-Scripts Zeit gesteuert, automatisiert starten lassen konnte.
    Auf diesen nützlichen Dienst muss man auch unter Termux nicht verzichten. Du kannst ihn mit folgender Befehlszeile installieren.
    pkg install cronie termux-services
    Es kann vorkommen, dass der Crontab-Dienst noch nicht unter der aktuellen Sitzung aktiviert werden kann. Starte einfach eine neue Sitzung. Wische einfach vom linken Rand des Terminal-Bereichs nach rechts zur Mitte. Ein UI-Panel öffnet sich. Drücke dort auf die Schaltfläche "New session".
    In dieser neuen Sitzung kannst du nun den Cronjob-Dienst mit folgender Befehlszeile starten.
    sv-enable crond
    Mehr über den Crontab-Dienst und wie man eigene Cronjobs erstellt, findest du in den Manpages.
  7. Selbstverständlich läuft der Crontab-Dienst nur solange eine Termux-Sitzung aktiv ist und die App ist nur so aktiv wie die CPU des Gerätes auf dem sie läuft. Damit Android die CPU nicht in den Schlafmodus versetzen kann, muss man dafür sorgen, dass Termux dies verhindert. Öffne hierzu die die Notification-Tray deines Telefons und klicke auf den kleinen Pfeil am Termux Eintrag. Anschließend wird die Schaltfläche "Acquire wakelock" sichtbar. Drücke auf diese Schaltfläche, um Termux zu veranlassen, die CPU am Einschlafen zu hindern.
    image.png
  8. Du wirst auch sicher gerne Dateien aus der Android-Umgebung in die Termux-Umgebung kopieren und auf Dateien in der Termux-Umgebung zugreifen können.
    Um auf den gemeinsamen Speicher (/sdcard oder /storage/emulated/0) zugreifen zu können, muss Termux eine Speicherzugriffsberechtigung besitzen. Sie wird nicht standardmäßig erteilt und beim Start der Anwendung nicht angefordert, da sie für den normalen Betrieb der Anwendung nicht erforderlich ist. Dies kann aber über die Eingabe von folgendem Kommando in die Befehlszeile nachgeholt werden:
    termux-setup-storage
    Normalerweise öffnet sich dann ein Dialog-Fenster, welches dich bittet, die entsprechende Berechtigung zu bestätigen. Hier kannst du getrost auf "Berechtigung erteilen"(Grant permission) drücken.
    Prüfe, ob du auf den gemeinsamen Speicher Zugriff hast, mithilfe der Eingabe des folgenden Kommandos:
    ls ~/storage/shared
    Wenn dir der Zugriff verwehrt wird, ist bei der Berechtigungsvergabe etwas schiefgegangen. Ein bekanntes Problem. In diesem Fall, entferne die "Storage" Berechtigung mithilfe der App-Einstellungen und vergebe sie erneut.

EnglishLanguage.png

Summary und inspirations

Now you not only have the power to run Python scripts on your phone, but you also have the power to run scripts that perform tasks in the Hive. Moreover, you can even schedule your scripts to run.

But that's not all you can do with Termux on your phone.
Of course, you can install a web server like Nginx using the package manager and use it to host websites on your phone.
pkg install nginx

You don't have to miss GIT either.
pkg install git

How about SSH to perform operations on other machines across a network?
pkg install openssh

Have fun with Linux on your phone! :-)

GermanLanguage.png

Résumé und Ausblick

Nun hast nicht nur die Möglichkeit Python-Scripts auf deinem Telefon auszuführen, sondern damit auch noch Aufgaben im Hive erledigen zu lassen. Obendrein, kannst du deine Scripts sogar Zeit gesteuert ausführen lassen.

Aber das muss nicht alles sein, was du aus deinem Telefon noch machen kannst.
Selbstverständlich kannst du auch einen Webserver, wie Nginx mithilfe des Paketmanagers installieren und damit auf deinem Telefon Webseiten hosten.
pkg install nginx

Auch auf GIT musst du nicht verzichten.
pkg install git

Wie wärs mit SSH, um auf anderen Rechnern über ein Netzwerk Operationen durchführen zu können?
pkg install openssh

Viel Spaß mit Linux auf deinem Telefon! :-)


Best regards | Viele Grüße
QuantumG


╭━━⋞ ☙ My NFT artworks ≻≺ ♖ My dCity ⋟━━╮
╰━━━━⋞ ♫ My Rising Star(s) ⋟━━━━╯

Sort:  

Well, well, well....you do impress. I will forward this to my son. He is not a smartphone advocate (he calls them spy phones😄), but he speaks your computer language. He will likely appreciate everything you said. As for me, I feel I've been stargazing for the last few minutes: awestruck.

More tools for clever people. Thank you @quantumg.

Hi @agmoore 👐

Oh, I couldn't agree more with your son. :-D In smartphones I do not trust.
I even killed the microphone on my previous smartphone and wanted to do the same with my current phone, but haven't managed to open it without breaking it into pieces. As often as possible, I leave it at home. It's just an online tool that I have to use for many purposes other than making phone calls. But I also enjoy spending time without it whenever possible.

Thank you so much for stopping by. I'm always happy when you visit my posts :-)
A thousand thanks for the tip!


The rewards earned on this comment will go directly to the people(@macchiata) sharing the post on Twitter as long as they are registered with @poshtoken. Sign up at https://hiveposh.com.

Web server on the cell phone. I had the idea some time ago, but I didn't feel like gathering all the necessary information. Maybe I'll give it a try after all. Thanks for your suggestions. 😁

Hey @quantumg ein toller Guide, welcher auch für mich als Laie super verständlich ist. Ich wusste zwar, dass Android im Kern auf Linux läuft, aber wie man das nutzen kann war mir nicht klar.
Vielen Dank für den Einblick.

!PIZZA

Hallo @captainloken. Freut mich sehr, dass du den Beitrag verständlich findest.
Vielen Dank fürs Reinschauen. :-)

!BEER

PIZZA!

PIZZA Holders sent $PIZZA tips in this post's comments:
@captainloken(1/5) tipped @quantumg (x1)

Please vote for pizza.witness!

Dear @quantumg, we need your help!

The Hivebuzz proposal already got an important support from the community. However, it lost its funding few days ago and only needs a few more HP to get funded again.

May we ask you to support it so our team can continue its work this year?
You can do it on Peakd, ecency,

Hive.blog / https://wallet.hive.blog/proposals
or using HiveSigner.
https://peakd.com/me/proposals/199

Your support would be really helpful and you could make the difference! Thank you!