Engineers Garage

  • Electronic Projects & Tutorials
    • Electronic Projects
      • Arduino Projects
      • AVR
      • Raspberry pi
      • ESP8266
      • BeagleBone
      • 8051 Microcontroller
      • ARM
      • PIC Microcontroller
      • STM32
    • Tutorials
      • Audio Electronics
      • Battery Management
      • Brainwave
      • Electric Vehicles
      • EMI/EMC/RFI
      • Hardware Filters
      • IoT tutorials
      • Power Tutorials
      • Python
      • Sensors
      • USB
      • VHDL
    • Circuit Design
    • Project Videos
    • Components
  • Articles
    • Tech Articles
    • Insight
    • Invention Stories
    • How to
    • What Is
  • News
    • Electronic Product News
    • Business News
    • Company/Start-up News
    • DIY Reviews
    • Guest Post
  • Forums
    • EDABoard.com
    • Electro-Tech-Online
    • EG Forum Archive
  • DigiKey Store
    • Cables, Wires
    • Connectors, Interconnect
    • Discrete
    • Electromechanical
    • Embedded Computers
    • Enclosures, Hardware, Office
    • Integrated Circuits (ICs)
    • Isolators
    • LED/Optoelectronics
    • Passive
    • Power, Circuit Protection
    • Programmers
    • RF, Wireless
    • Semiconductors
    • Sensors, Transducers
    • Test Products
    • Tools
  • Learn
    • eBooks/Tech Tips
    • Design Guides
    • Learning Center
    • Tech Toolboxes
    • Webinars & Digital Events
  • Resources
    • Digital Issues
    • EE Training Days
    • LEAP Awards
    • Podcasts
    • Webinars / Digital Events
    • White Papers
    • Engineering Diversity & Inclusion
    • DesignFast
  • Guest Post Guidelines
  • Advertise
  • Subscribe

Accessing Raspberry Pi terminal using MQTT

By engineersgarage December 21, 2021

In this article, we will learn how to access raspberry pi from anywhere in the world using MQTT. This will all be done with a python script.

Several applications are already available to access Linux-based terminals over remote/network, but they all require port forwarding, but MQTT allows without port forwarding.

We will not need any port forwarding. This will also be platform-independent because we will be using python to interact with the system to run it inside Linux, Windows even in OSX. 

Tools Required/ libraries required
MQTT based python library – paho
Python IDE
Linux / Windows System

Technical insights
We will be linking the MQTT protocol stack with the terminal using python. Python’s library “OS” is also capable of interacting with system processes and terminals.

So, we will be writing a python script that will communicate with an MQTT broker and transfer and receive data. All the incoming data will be piped (transferred) into the system terminal process.

The output of the system processes will also be redirected in an MQTT response/ message on a topic (MQTT uses topics to communicate).

Block diagram

Figure 1 MQTT terminal

The terminal script is subscribed to a topic – terminal
Publishing on topic – terminal/output

The clients are subscribed to a topic – terminal/output
Publishing on topic – terminal

Both are connected with broker – broker.hivemq.com
On port – 1883

How does the system work?
The system is installed with the python script, listening to a specific MQTT topic (terminal), and connected to a MQTT broker. Any client who wants to access the terminal is publishing commands on that topic (terminal). When a client sends a command to our terminal script, it will read it, and the command is filtered out from that message. That command is then sent to the terminal, the result of that command is combined on a string and published to that client on that topic.

Understanding the source code
We can write two scripts, one for the terminal itself another is for accessing it.

Terminal script
We will be dividing our source code into two categories to understand easily.

  1. Interacting with the system terminal
  2. MQTT communication

Interacting with the system terminal
Python is a high-level programming/scripting language. Python has several libraries available to do stuff. First of all, we will need a library, which can interact, with our system; also it must be independent of platform. So, there is a library called “OS” in built-in python to access the operating system. We will import the library on the top of our script. With this, you can do a lot of work easily.
Import os

Now we know that the script should be multi-tasking or threaded, because sometimes a command takes long time to complete and we do not want that in that period when we pass another command it gets rejected. That can be done using subprocess library so let import it too.

Import subprocess

Now that we have imported libraries we need to make a variable, which can hold the command and its output. Later we will see how to store commands to that variable from MQTT.
For saving command – data
For command output – stdout_value

All we need is done. We will be sending and receiving data on these variables. So, lets create a subprocess, which will directly send the command from “data” to the terminal and store the output to “stdout_value” variables.
The meaning of that line is now the following:
proc   = Is a variable that stores the complete sub-process, input-output, and errors.
subprocess.Popen = this means we are telling process that we will be piping (giving input and taking output) some data and taking some of it out.
stdout = Stores the output of the above process.
stderr = Stores the error if any
stdin = is for string input command input

Now that we have started the process, we need to take the command’s output out and the error if there is any.
stdout_value = proc.stdout.read() + proc.stderr.read()

Now we are stroring the output by reading the “proc.stdout.read()”.

The “stdout_value” is the variable which we will send to our client on MQTT for output. So, lets send it below and learn how MQTT communication is done.

MQTT communication
First of all, we will import libraries that are necessary for MQTT.
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish

now we will declare a variable named client with mqtt client.
client = mqtt.Client()

Now we will make two functions, which are callbacks 1. For receiving messages 2. Doing something on connection successful.
client.on_connect = on_connect
client.on_message = on_message

Finally, we will connect to MQTT broker on a port, and start the client inside a nonblocking loop
client.connect(“broker.hivemq.com”, 1883, 60)
client.loop_start()

After the connection is successful we can send messages using this publish method.
publish.single(topic, message_data, hostname=”broker.hivemq.com”)

or we can create a function / method to do that.
def send(msg,publish_t):

This method takes the input parameter “msg” as the message we need to send to the broker with the topic.

Now that we have a function which triggers on receiving any data from MQTT broker. We will store any incoming message from broker to a variable message, inside the “on_message” method.
message = str(msg.payload)

The incoming message syntax will be.
cmd:” command to execute”

Now we need to remove the “cmd:” string and store the remaining command

in the “data” variable to process the command.
data = message.replace(“cmd:”,””)

Now to send the output we call our send method with the output parameters and transmit the result.
send(stdout_value,toipc_publish_result)

Access script
The access script is just a function, which receives messages from MQTT broker and takes input form user to publish to script, which is self-explained inside the code.

So, this is how we can access the complete system using MQTT.

Note – Do not use common topics to create terminal access because you will be giving access of the whole system.

https://www.engineersgarage.com/wp-content/uploads/2021/12/demo.mp4

You may also like:

  • Raspberry Pi 4
    RPi Python Programming 01: Introduction to Raspberry Pi 4

  • GPRS Communication with PC Client over MQTT Protocol : IOT…

  • Understanding MQTT protocol : IoT Part 14

  • How to use Raspberry Pi camera module with Python

  • What is a Robot Operating System (ROS)?

  • MQTT for Sensor Networks (MQTT-SN) : IOT Part 39

Filed Under: Tutorials
Tagged With: MQTT, raspberrypi
 

Next Article

← Previous Article
Next Article →

EE TECH TOOLBOX

“ee
Tech Toolbox: Internet of Things
Explore practical strategies for minimizing attack surfaces, managing memory efficiently, and securing firmware. Download now to ensure your IoT implementations remain secure, efficient, and future-ready.

EE Learning Center

EE Learning Center
“engineers
EXPAND YOUR KNOWLEDGE AND STAY CONNECTED
Get the latest info on technologies, tools and strategies for EE professionals.

HAVE A QUESTION?

Have a technical question about an article or other engineering questions? Check out our engineering forums EDABoard.com and Electro-Tech-Online.com where you can get those questions asked and answered by your peers!


RSS EDABOARD.com Discussions

  • Voltage mode pushpull is a nonsense SMPS?
  • Input impedance matching network
  • High Side current sensing
  • The comparison of different Tcl script checkers
  • Reducing "shoot-through" in offline Full Bridge SMPS?

RSS Electro-Tech-Online.com Discussions

  • Is AI making embedded software developers more productive?
  • Back to the old BASIC days
  • Parts required for a personal project
  • PIC KIT 3 not able to program dsPIC
  • Failure of polypropylene motor-run capacitors

Featured – RPi Python Programming (27 Part)

  • RPi Python Programming 21: The SIM900A AT commands
  • RPi Python Programming 22: Calls & SMS using a SIM900A GSM-GPRS modem
  • RPi Python Programming 23: Interfacing a NEO-6MV2 GPS module with Raspberry Pi
  • RPi Python Programming 24: I2C explained
  • RPi Python Programming 25 – Synchronous serial communication in Raspberry Pi using I2C protocol
  • RPi Python Programming 26 – Interfacing ADXL345 accelerometer sensor with Raspberry Pi

Recent Articles

  • What is AWS IoT Core and when should you use it?
  • AC-DC power supply extends voltage range to 800 V DC
  • Infineon’s inductive sensor integrates coil system driver, signal conditioning circuits and DSP
  • Arm Cortex-M23 MCU delivers 87.5 µA/MHz active mode
  • STMicroelectronics releases automotive amplifiers with in-play open-load detection

EE ENGINEERING TRAINING DAYS

engineering

Submit a Guest Post

submit a guest post
Engineers Garage
  • Analog IC TIps
  • Connector Tips
  • Battery Power Tips
  • DesignFast
  • EDABoard Forums
  • EE World Online
  • Electro-Tech-Online Forums
  • EV Engineering
  • Microcontroller Tips
  • Power Electronic Tips
  • Sensor Tips
  • Test and Measurement Tips
  • 5G Technology World
  • Subscribe to our newsletter
  • About Us
  • Contact Us
  • Advertise

Copyright © 2025 WTWH Media LLC. All Rights Reserved. The material on this site may not be reproduced, distributed, transmitted, cached or otherwise used, except with the prior written permission of WTWH Media
Privacy Policy

Search Engineers Garage

  • Electronic Projects & Tutorials
    • Electronic Projects
      • Arduino Projects
      • AVR
      • Raspberry pi
      • ESP8266
      • BeagleBone
      • 8051 Microcontroller
      • ARM
      • PIC Microcontroller
      • STM32
    • Tutorials
      • Audio Electronics
      • Battery Management
      • Brainwave
      • Electric Vehicles
      • EMI/EMC/RFI
      • Hardware Filters
      • IoT tutorials
      • Power Tutorials
      • Python
      • Sensors
      • USB
      • VHDL
    • Circuit Design
    • Project Videos
    • Components
  • Articles
    • Tech Articles
    • Insight
    • Invention Stories
    • How to
    • What Is
  • News
    • Electronic Product News
    • Business News
    • Company/Start-up News
    • DIY Reviews
    • Guest Post
  • Forums
    • EDABoard.com
    • Electro-Tech-Online
    • EG Forum Archive
  • DigiKey Store
    • Cables, Wires
    • Connectors, Interconnect
    • Discrete
    • Electromechanical
    • Embedded Computers
    • Enclosures, Hardware, Office
    • Integrated Circuits (ICs)
    • Isolators
    • LED/Optoelectronics
    • Passive
    • Power, Circuit Protection
    • Programmers
    • RF, Wireless
    • Semiconductors
    • Sensors, Transducers
    • Test Products
    • Tools
  • Learn
    • eBooks/Tech Tips
    • Design Guides
    • Learning Center
    • Tech Toolboxes
    • Webinars & Digital Events
  • Resources
    • Digital Issues
    • EE Training Days
    • LEAP Awards
    • Podcasts
    • Webinars / Digital Events
    • White Papers
    • Engineering Diversity & Inclusion
    • DesignFast
  • Guest Post Guidelines
  • Advertise
  • Subscribe