Files
wevads-platform/kb-wevia/coding/01-cli-ssh-remote-dev.md

12 KiB

CODING À DISTANCE — CLI, SSH, REMOTE DEVELOPMENT

Knowledge Base WEVIA — WEVAL Consulting

Dernière mise à jour : 28 février 2026


1. SSH — SECURE SHELL

1.1 Fondamentaux

  • Protocole : SSH v2 (RFC 4253), port 22 par défaut
  • Authentification : clé publique (Ed25519 recommandé > RSA), mot de passe, certificats, FIDO2/U2F
  • Chiffrement : ChaCha20-Poly1305, AES-256-GCM, AES-256-CTR
  • Key Exchange : curve25519-sha256, diffie-hellman-group16-sha512

1.2 Commandes essentielles

# Génération de clé Ed25519 (recommandé 2025+)
ssh-keygen -t ed25519 -C "yacine@weval-consulting.com"

# Connexion avec port personnalisé
ssh -p 49222 root@157.180.25.208

# Tunnel SSH local (forward port local vers remote)
ssh -L 8080:localhost:5821 root@89.167.40.150

# Tunnel SSH reverse (exposer service local)
ssh -R 9090:localhost:3000 root@server

# SOCKS proxy dynamique
ssh -D 1080 root@server

# Jump host / bastion
ssh -J bastion@jump-host root@internal-server

# SCP transfert fichier
scp -P 49222 file.tar.gz root@157.180.25.208:/opt/

# Rsync via SSH (incremental, compression)
rsync -avz -e "ssh -p 22" /local/path/ root@server:/remote/path/

# SSH config (~/.ssh/config)
Host wevads
    HostName 89.167.40.150
    Port 5821
    User root
    IdentityFile ~/.ssh/id_ed25519
    ServerAliveInterval 60
    ServerAliveCountMax 3

1.3 SSH Tunneling avancé

  • Local Forward : -L local_port:target:target_port — accéder à un service distant via port local
  • Remote Forward : -R remote_port:target:target_port — exposer un service local sur le serveur
  • Dynamic SOCKS : -D port — proxy SOCKS5 pour tout le trafic
  • ProxyJump : -J user@bastion — traverser un bastion/jump host
  • Multiplexing : ControlMaster auto, ControlPath, ControlPersist — réutiliser connexions

1.4 Sécurisation SSH

# /etc/ssh/sshd_config hardening
PermitRootLogin prohibit-password
PasswordAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
AllowUsers deploy admin
Protocol 2
X11Forwarding no
AllowTcpForwarding yes
ClientAliveInterval 300
ClientAliveCountMax 2
  • fail2ban : protection brute-force (ban après N tentatives)
  • Port knocking : séquence de ports avant ouverture SSH
  • 2FA : Google Authenticator PAM module
  • Audit : auditd pour tracer les connexions SSH

2. TERMINAUX & MULTIPLEXEURS

2.1 tmux (Terminal Multiplexer)

# Sessions persistantes (survive déconnexion SSH)
tmux new -s wevads          # nouvelle session
tmux attach -t wevads       # réattacher
tmux ls                     # lister sessions
Ctrl+b d                    # détacher
Ctrl+b c                    # nouveau window
Ctrl+b %                    # split vertical
Ctrl+b "                    # split horizontal
Ctrl+b [                    # mode scroll/copy

2.2 Alternatives modernes

  • Zellij (Rust) : layout system, plugins WASM, floating panes
  • screen : legacy mais encore présent partout
  • mosh : Mobile Shell — resilient aux changements IP/réseau, UDP-based, prediction locale

2.3 Shells modernes

  • fish : autosuggestions, syntax highlighting natif, web-based config
  • zsh + Oh My Zsh : plugins (git, docker, kubectl), thèmes (powerlevel10k)
  • nushell : structured data pipelines, tables au lieu de texte
  • starship : prompt cross-shell, git status, runtime versions

3. REMOTE DEVELOPMENT

3.1 VS Code Remote

  • Remote-SSH : édition distante avec IntelliSense local, terminal intégré
  • Remote-Containers : développement dans Docker containers
  • Remote-WSL : Windows ↔ Linux seamless
  • Tunnels : code tunnel — accès via navigateur sans SSH direct

3.2 Claude Code (Anthropic CLI)

  • Installation : npm install -g @anthropic-ai/claude-code
  • Capabilities : agentic coding, lecture/écriture fichiers, exécution commandes
  • MCP Servers : intégration avec outils externes (GitHub, Jira, bases de données)
  • Modes : interactive, headless (--print), CI/CD integration
  • Modèles : Claude Opus 4.6 (défaut), Sonnet 4.5, Haiku 4.5
  • Best practices : CLAUDE.md à la racine du projet, commandes slash (/init, /compact)

3.3 Cursor IDE

  • AI-first IDE basé sur VS Code fork
  • Tab completion avec contexte codebase
  • Composer pour modifications multi-fichiers
  • Chat inline avec sélection de code
  • Support Claude, GPT-4, modèles custom

3.4 Autres outils remote

  • JetBrains Gateway : IDE remote pour IntelliJ/PyCharm/WebStorm
  • Coder : self-hosted cloud dev environments
  • Gitpod : cloud workspaces, prebuilds, .gitpod.yml
  • GitHub Codespaces : dev containers dans le cloud GitHub

4. INFRASTRUCTURE AS CODE (IaC)

4.1 Ansible

# playbook.yml — Configuration serveur WEVADS
- hosts: wevads_servers
  become: yes
  tasks:
    - name: Install packages
      apt:
        name: [postgresql-13, apache2, python3-pip]
        state: present
    - name: Deploy config
      template:
        src: templates/apache.conf.j2
        dest: /etc/apache2/sites-available/wevads.conf
      notify: restart apache
  handlers:
    - name: restart apache
      service: name=apache2 state=restarted
  • Inventaires : statiques (INI/YAML), dynamiques (AWS, Azure, GCP plugins)
  • Rôles : Galaxy roles, collections
  • Vault : chiffrement des secrets (ansible-vault encrypt)
  • AWX/Tower : interface web, RBAC, scheduling

4.2 Terraform

# main.tf — Infrastructure Hetzner
provider "hcloud" {
  token = var.hcloud_token
}
resource "hcloud_server" "gpu" {
  name        = "wevads-gpu"
  server_type = "gex44"
  image       = "ubuntu-24.04"
  location    = "fsn1"
}
  • State : remote (S3, Terraform Cloud, Consul)
  • Modules : réutilisables, registry public
  • Workspaces : multi-environnement (dev/staging/prod)
  • Import : terraform import pour infrastructure existante
  • OpenTofu : fork open-source de Terraform (post licence BSL)

4.3 Pulumi

  • IaC avec vrais langages (Python, TypeScript, Go, C#)
  • State management cloud ou self-hosted
  • CrossGuard : policy as code
  • Automation API pour intégration programmatique

5. CI/CD PIPELINES

5.1 GitHub Actions

# .github/workflows/deploy.yml
name: Deploy WEVADS
on:
  push:
    branches: [main]
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Deploy via SSH
        uses: appleboy/ssh-action@v1
        with:
          host: 89.167.40.150
          username: root
          key: ${{ secrets.SSH_KEY }}
          script: |
            cd /opt/wevads && git pull && systemctl reload apache2

5.2 GitLab CI

# .gitlab-ci.yml
stages: [test, build, deploy]
deploy:
  stage: deploy
  script:
    - ssh root@server "cd /opt/wevads && git pull"
  only: [main]

5.3 ArgoCD (GitOps)

  • Déclaratif, Git comme source de vérité
  • Sync automatique Kubernetes manifests
  • Rollback instantané
  • Multi-cluster support

6. CONTAINERS & ORCHESTRATION

6.1 Docker

# Dockerfile multi-stage optimisé
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci --production
COPY . .
RUN npm run build

FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
EXPOSE 3000
USER node
CMD ["node", "dist/server.js"]
# Docker Compose pour stack WEVADS
docker compose up -d
docker compose logs -f wevads
docker compose exec wevads bash

6.2 Kubernetes (K8s)

  • Architecture : Control Plane (API Server, etcd, Scheduler, Controller Manager) + Worker Nodes (kubelet, kube-proxy)
  • Objects : Pod, Deployment, Service, Ingress, ConfigMap, Secret, PV/PVC
  • Helm : package manager, charts, values.yaml
  • Kustomize : overlays sans templates
  • k3s : Kubernetes léger pour edge/small clusters
  • kubectl : CLI principal, contexts multi-cluster

6.3 Podman

  • Rootless containers, daemonless
  • Compatible Docker CLI
  • Pod concept (multi-container groups)
  • Systemd integration native

7. MONITORING & OBSERVABILITÉ

7.1 Stack Prometheus + Grafana

# prometheus.yml
scrape_configs:
  - job_name: 'wevads'
    static_configs:
      - targets: ['89.167.40.150:9090']
    scrape_interval: 15s
  • Prometheus : TSDB, PromQL, alerting rules
  • Grafana : dashboards, alerting, data sources multiples
  • Alertmanager : routing, silencing, grouping

7.2 Alternatives

  • Datadog : SaaS complet (APM, logs, infra, RUM), ~$15-23/host/mois
  • New Relic : observabilité full-stack, free tier 100GB/mois
  • Zabbix : open-source, agent-based, templates
  • Netdata : real-time monitoring, zero config

7.3 Logging

  • ELK Stack : Elasticsearch + Logstash + Kibana
  • Loki + Grafana : logging léger, labels comme Prometheus
  • Fluentd/Fluent Bit : log collection & forwarding
  • Vector : pipeline logs/metrics haute performance (Rust)

8. OUTILS CLI ESSENTIELS

8.1 Gestion fichiers & texte

# Recherche puissante
fd "*.php" /opt/wevads/          # find moderne (Rust)
rg "function.*send" /opt/wevads/  # ripgrep (Rust, 10x faster que grep)
fzf                               # fuzzy finder interactif

# Manipulation texte
jq '.data.offers[] | .name'       # JSON processor
yq '.services.web.image'          # YAML processor
bat file.php                      # cat avec syntax highlighting
delta                             # diff amélioré

8.2 Réseau & debug

# HTTP testing
curl -X POST https://api.example.com/v1 -H "Content-Type: application/json" -d '{"key":"value"}'
httpie POST api.example.com/v1 key=value   # curl humain-friendly
wget --mirror --convert-links site.com      # téléchargement récursif

# DNS & réseau
dig +short example.com A
nslookup example.com
mtr 89.167.40.150                # traceroute interactif
ss -tlnp                         # ports ouverts (remplace netstat)
nmap -sV 89.167.40.150           # scan ports & services

# Performance
htop                             # process monitor interactif
btop                             # htop moderne
iotop                            # I/O monitoring
duf                              # disk usage (df moderne)
ncdu /opt/wevads/                # disk usage interactif

8.3 Base de données CLI

# PostgreSQL
psql -h localhost -U postgres -d adx_system
\dt                              # lister tables
\d+ table_name                   # structure détaillée
COPY (SELECT * FROM offers) TO '/tmp/offers.csv' CSV HEADER;
pg_dump -Fc adx_system > backup.dump
pg_restore -d adx_system backup.dump

# Redis
redis-cli
KEYS pattern*
GET key
INFO memory

9. SÉCURITÉ CLI

9.1 Gestion des secrets

  • HashiCorp Vault : secrets management, dynamic credentials, encryption as a service
  • SOPS (Mozilla) : chiffrement fichiers YAML/JSON avec KMS/PGP
  • age : chiffrement fichier simple (remplacement GPG)
  • 1Password CLI : op read op://vault/item/field
  • direnv : variables d'environnement par dossier (.envrc)

9.2 Audit & compliance

# Lynis — audit sécurité système
lynis audit system

# ClamAV — antivirus
clamscan -r /opt/wevads/

# rkhunter — rootkit hunter
rkhunter --check

# Trivy — scan vulnérabilités containers
trivy image wevads:latest
trivy fs /opt/wevads/

10. SCRIPTS AUTOMATION WEVAL

10.1 Health check pattern

#!/bin/bash
# health-check.sh — Monitoring services WEVADS
SERVICES=("apache2" "postgresql" "pmta" "n8n")
for svc in "${SERVICES[@]}"; do
    if systemctl is-active --quiet "$svc"; then
        echo "✅ $svc: running"
    else
        echo "❌ $svc: DOWN" | mail -s "ALERT: $svc down" yacine@weval-consulting.com
    fi
done
# Check HTTP endpoints
curl -sf http://localhost:5821/api/health > /dev/null || echo "❌ WEVADS API down"
curl -sf http://151.80.235.110/track.php > /dev/null || echo "❌ OVH tracking down"

10.2 Déploiement pattern

#!/bin/bash
# deploy.sh — Déploiement chirurgical
set -euo pipefail
BACKUP_DIR="/opt/wevads/backups/$(date +%Y%m%d-%H%M%S)"
mkdir -p "$BACKUP_DIR"
cp /opt/wevads/target_file "$BACKUP_DIR/"
# str_replace equivalent en sed
sed -i 's/old_pattern/new_pattern/g' /opt/wevads/target_file
php -l /opt/wevads/target_file && echo "✅ Syntax OK" || { echo "❌ Rollback"; cp "$BACKUP_DIR/target_file" /opt/wevads/; exit 1; }
systemctl reload apache2
echo "✅ Deployed successfully"