Search code examples
pythonsocketstitleputty

Python change socket window title


When I connect to the server using PuTTY, the window says "DBA-LT2017 - PuTTY"

How can I change the title of the window of PuTTY? (not the console application)

This is the code I have so far

import socket
import threading
from thread import start_new_thread

connect = ""
conport = 8080

def clientThread(conn):
    while True:
        message = conn.recv(512)

        if message.lower().startswith("quit"):
            conn.close()

        if not message:
            break

def startClient():
    host = connect
    port = conport
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind((host, port))
    sock.listen(1)
    print("[+] Server Started")
    while True:
        conn, addr = sock.accept()

        start_new_thread(clientThread, (conn,))
    sock.close()

client = threading.Thread(target=startClient)
client.start()

I saw a script programmed in C, that uses TCP and can change the session title without telnet either

void *titleWriter(void *sock)
{
    int thefd = (int)sock;
    char string[2048];
    while(1)
    {
        memset(string, 0, 2048);
        sprintf(string, "%c]0;Test", '\033', '\007');
        if(send(thefd, string, strlen(string), MSG_NOSIGNAL) == -1) return;
        sleep(2);
    }
}

Solution

  • PuTTY understands ANSI escape sequences.

    An escape sequence for setting a console title is:

    ESC ] 0;this is the window title BEL
    

    In Python that is:

    def clientThread(conn):
        conn.send("\x1b]0;this is the window title\x07")
        ...
    

    enter image description here