↓ Skip to main content

5 Minute Project : Remote CMD For Your Home Lab Using Telegram

·882 words·5 mins

“الحاجة أم الاختراع”
#

This arabic proverb literally translates to :

Necessity is the mother of invention
#

And it captures exactly why I am writing this blog.

I needed a way to remotely manage my homelab server, which which runs on an old laptop I no longer use, without connecting to it via SSH every time.

So I thought to myself, is there a way to create a “mobile SSH” interface?

I previously experimented with OpenClaw/Clawdbot, an AI agent capable of interacting with an entire OS as if it were running inside it.

What stood out to me was how naturally you could communicate with the agent, simply by sending messages via WhatsApp, Telegram or Discord, as if you were texting a friend.

Why not use the same approach to send commands to my server?

For this project, I chose Telegram because it is straightforward to implement and integrates easily with bots.

  1. First, install Telegram on your phone, set up your account, then click on the New Message icon and search for BotFather :
  1. Run /newbot :

  2. Set your bot name and username (username has to end in bot) :

  1. You will get a message link for your bot as well as the API token, make sure to store the token securely, as we will need it in the next steps.
  1. Now search for userinfobot and run /start, it will return your user ID, note it down for later.

  1. SSH into your server, and install python (if you dont have it already), and the Telegram bot library :
sudo apt update
sudo apt install python3 python3-pip -y
pip3 install python-telegram-bot

Note : If you get the following error when trying to install the library

Run : (system-wide package install but no headaches)

sudo apt install python3-python-telegram-bot
  1. Create bot.py in the directory of your choosing and copy-paste the following python code :
# cd ...
nano bot.py
# bot.py
import os
import asyncio
from subprocess import Popen, PIPE
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes

TOKEN = "YOUR_BOT_TOKEN" # TO REPLACE WITH YOUR OWN
AUTHORIZED_USER = 123456789 # TO REPLACE WITH YOUR OWN

sessions = {}  # chat_id -> {"proc": Popen, "cwd": str}

# Helper to run a command in the persistent session
def run_command(chat_id, command):
    sess = sessions.get(chat_id)
    if not sess:
        return "(no active shell session)"
    cwd = sess["cwd"]

    # Handle 'cd' specially
    if command.startswith("cd "):
        path = command[3:].strip()
        new_dir = os.path.abspath(os.path.join(cwd, path))
        if os.path.isdir(new_dir):
            sess["cwd"] = new_dir
            return f"Changed directory to: {new_dir}"
        else:
            return f"No such directory: {path}"

    # Run other commands
    proc = Popen(command, shell=True, stdout=PIPE, stderr=PIPE, cwd=cwd)
    stdout, stderr = proc.communicate(timeout=30)  # avoid hanging commands max 30s
    output = (stdout + stderr).decode(errors="replace").strip()
    return output or "(no output)"

async def new_shell(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.effective_user.id != AUTHORIZED_USER:
        return
    chat_id = update.effective_chat.id
    if chat_id in sessions:
        await update.message.reply_text("Shell already running. Use /close first.")
        return
    # Start session in home directory
    sessions[chat_id] = {"proc": None, "cwd": os.path.expanduser("~")}
    await update.message.reply_text(f"New shell started in {sessions[chat_id]['cwd']}")

async def close_shell(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.effective_user.id != AUTHORIZED_USER:
        return
    chat_id = update.effective_chat.id
    if chat_id not in sessions:
        await update.message.reply_text("No active shell.")
        return
    sessions.pop(chat_id)
    await update.message.reply_text("Shell closed.")

async def handle_text(update: Update, context: ContextTypes.DEFAULT_TYPE):
    if update.effective_user.id != AUTHORIZED_USER:
        return
    chat_id = update.effective_chat.id
    if chat_id not in sessions:
        await update.message.reply_text("No shell session. Use /new to start one.")
        return
    command = update.message.text
    # Run the command
    try:
        output = await asyncio.to_thread(run_command, chat_id, command)
    except Exception as e:
        output = f"Error: {e}"
    # Telegram limit ~4000 chars
    for i in range(0, len(output), 4000):
        await update.message.reply_text(output[i:i+4000])

def main():
    app = ApplicationBuilder().token(TOKEN).build()
    app.add_handler(CommandHandler("new", new_shell))
    app.add_handler(CommandHandler("close", close_shell))
    app.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), handle_text))
    app.run_polling()

if __name__ == "__main__":
    main()

I prompted an LLM for this script, you can use mines or make your own depending on your needs, just make sure to add your own credentials (API Token + Telegram User ID) in the TOKEN and AUTHORIZED_USER variables respectively.

With this script, the bot creates a persistent shell on the server controlled from the chat.

/new starts a minimal bash shell in a pseudo-terminal.

/close terminates it.

Any plain message is sent as a command to the shell. The output from the shell is captured, ANSI/terminal sequences are stripped, and the clean result is sent back by the bot.

  1. To test if it’s working, run :
python3 bot.py

Go back to BotFather chat and click on the bot chat link if you haven’t yet started a chat with your bot (t.me/bot_username)

Send /new.

Then, test some commands and view their output.

Use /close to terminate the session.

You should get something like this :

  1. Now let’s make a persistent service that starts automatically on boot, and restarts if it crashes :

Create the service file :

sudo nano /etc/systemd/system/telegram-bot.service

Copy-paste the following config :

[Unit]
Description=Telegram Server Bot
After=network.target

[Service]
ExecStart=/usr/bin/python3 /cmd-bot/bot.py # <- Replace this with the directory you have your bot.py in
Restart=always

[Install]
WantedBy=multi-user.target

Save and exit.

Next, reload systemd :

sudo systemctl daemon-reexec
sudo systemctl daemon-reload

Enable the service to start at boot :

sudo systemctl enable telegram-bot

Start the service :

sudo systemctl start telegram-bot

And that is it, you are all set now.

Feel free to tweak the script depending on your needs, adding or restricting features as you like.

Thank you for reading!

Bouatmani Younes
Author
Bouatmani Younes
Cybersecurity and Cloud Engineering student