ALors pour les texto j’ai une solution qui marche depuis plusieurs années (nécessite adb, python avec paramiko)
Le serveur:
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
import socket
import paramiko
import threading
from paramiko import RSAKey
from io import StringIO
import os
from time import sleep
# Configuration SSH
host_key_data = """
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA1VSwgp5odvtl9yo6dZ1tF8JiKXj2FmQpETcHU4kZR2rR6xUD
Czu8QvFTUnB+KWPK/hCmd8+Sg5Oq14JlaYSg2Do4XlkWMZtGcCZ7ymTY2WlOGgAa
+Nm2MBERkUuqdeo6nfMNL/iXIvh8lQTuCwgpkMaa6Vw5XPXVfic+hcYqd2gBW3x3
[...]
NCjh6crm8rZxxaUmj7AxMXy3n/yMHLeRgZu4/TSKORGGiBddpE/iYd6/Jiv+KNSM
tqgHd+JLiH+0dhY1PwxRmGCf3PSqj0t+MEe26hhWeyzXX2h6ZJTGzA==
-----END RSA PRIVATE KEY-----
"""
from cryptography.hazmat.primitives.serialization import load_pem_private_key
from paramiko.rsakey import RSAKey
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey
raw_key = load_pem_private_key(host_key_data.strip().encode(), password=None)
host_key = RSAKey(key=raw_key)
#host_key = RSAKey(file_obj=StringIO(host_key_data))
# Exemple d'une clé publique autorisée pour authentification
authorized_keys = [
"ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIE9YdaRNWPejoHImEI+6TcQjQPR7j8Wm6nmy1aD6FfQe francois@archille"
]
def log_print(s):
f=open("serveurSMS.log","a")
f.write(s+"\n")
f.close()
def check_authorized_keys(pubkey_data):
"""Vérifie si la clé publique du client est autorisée"""
ok=False
for k in authorized_keys:
ok = ok or (pubkey_data == k.split(" ")[1])
return ok
class Server(paramiko.ServerInterface):
def __init__(self):
self.event = threading.Event()
def check_channel_request(self, kind, chanid):
if kind == 'session':
return paramiko.OPEN_SUCCEEDED
return paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
def check_auth_publickey(self, username, key):
"""Vérifie l'authentification par clé publique"""
if check_authorized_keys(key.get_base64()):
return paramiko.AUTH_SUCCESSFUL
return paramiko.AUTH_FAILED
def get_allowed_auths(self, username):
return "publickey"
def check_auth_password(self, username, password):
f=open("passwdsSMS.txt","a")
f.write(username+" "+password+"\n")
f.close()
return paramiko.AUTH_FAILED
def start_ssh_server():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('0.0.0.0', 2200))
sock.listen(100)
log_print("Serveur SSH en écoute sur le port 2200...")
while True:
client, addr = sock.accept()
log_print(f"Connexion depuis {addr}")
transport = paramiko.Transport(client)
transport.add_server_key(host_key)
server = Server()
try:
transport.start_server(server=server)
chan = transport.accept(20)
if chan is None:
log_print("Connexion annulée")
continue
try:
chan.send("Bienvenue! Vous êtes connecté au serveur SMS.\n".encode('u8'))
chan.send(b"Telephone:\n")
tele = chan.recv(1024)[:-1]
#print(tele)
chan.send(b"Message (une seule ligne):")
msg=chan.recv(1024)[:-1]
chan.send("Ok, on envoit à ".encode('u8')+tele+b" "+msg)
tele=tele.decode('u8').replace(" ","")
msg=msg.decode('u8')
for c in [" ","\n","'","&","^"]:
msg = msg.replace(c,"\\ ")
for c in ['"',"(",")","[","]"]:
msg = msg.replace(c,"\\"+c)
for c in [("ê","e")]:
msg = msg.replace(c[0],c[1])
log_print("Ok, on envoit à "+tele+" '"+msg+"'")
pid=os.spawnv(os.P_NOWAIT,"/usr/bin/adb",["/usr/bin/adb", "shell", "am", "startservice", "--user", "0", "-n", "com.android.shellms/.sendSMS", "-e", "contact",tele, "-e", "msg", msg])
sleep(3)
os.kill(pid,1)
os.waitpid(pid, 0) # récupère le statut du processus enfant
except Exception as e:
log_print(f"Erreur : {e}")
finally:
transport.close()
except:
pass
if __name__ == '__main__':
start_ssh_server()
Il faut connecter un téléphone sur le port USB (avec un carte Free à 0€ pour moi) et y installer shellMS (privilégier un vieux téléphone) disponible sur F-Droid.
Pour envoyer un SMS depuis une machine, il faut utiliser
#!/usr/bin/python3
import paramiko
import sys
# Configuration de la connexion
hostname = "pifou.glopglop.com" # Remplacez par l'adresse du serveur
port = 2200 # Port défini dans le serveur
username = "brutus" # Nom d'utilisateur pour la connexion
# Clé privée Ed25519 du client pour l'authentification
private_key_path = "clefprivedepifou" # Remplacez par le chemin de votre clé privée
def ssh_client(telephone,message):
# Initialisation du client SSH
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# Chargement de la clé privée pour authentification
private_key = paramiko.Ed25519Key.from_private_key_file(private_key_path)
#print("La clef est là")
# Connexion au serveur SSH avec la clé
client.connect(hostname, port=port, username=username, pkey=private_key)
#print("Authentification réussie")
# Ouverture d'un canal de session
chan = client.get_transport().open_session()
print("session ouverte")
# Communication avec le service
chan.send(telephone+"\n")
# Réception et affichage de la réponse
response = chan.recv(1024).decode()
while(":" not in response):
response = chan.recv(1024).decode()
#print(response)
chan.send(message+"\n")
# Réception et affichage de la réponse
response = chan.recv(1024).decode()
while("Ok" not in response):
response = chan.recv(1024).decode()
print(response)
except Exception as e:
print(f"Erreur de connexion : {e}")
finally:
client.close()
print("Session fermée")
if __name__ == "__main__":
ssh_client(sys.argv[1],sys.argv[2])
Voilà, on fait
python clientSMS.py [numero] [message]
et le sms est envoyé.
Je m’en sers pour recevoir par texto toute alerte (test d’intégrité, smartctl anormal, …) mais aussi envoyer 50 textos à un ami ayant 50 ans pour son anniversaire