How to use `virsh` via SSH without running `virsh` on the remote host?
Aug 10, 7:45pm

To use virsh via SSH without executing it on the remote host, you need to tunnel the libvirt socket over SSH. This allows your local virsh to communicate with the remote libvirt daemon (libvirtd) as if it were running locally.

Here’s how to do it:


Method: SSH Port Forwarding for Libvirt Socket

Libvirt uses a Unix domain socket (typically /var/run/libvirt/libvirt-sock) for communication. Since Unix sockets cannot be directly forwarded over SSH, you can use socat to expose the socket as a TCP port on the remote host, then forward that port over SSH.

Step 1: On the Remote Host

  1. Install socat (if not already installed):

    bash
    sudo apt install socat  # Debian/Ubuntu
    sudo yum install socat  # RHEL/CentOS
  2. Expose the libvirt socket as a TCP port (e.g., port 16509):

    bash
    sudo socat TCP-LISTEN:16509,reuseaddr,fork UNIX-CONNECT:/var/run/libvirt/libvirt-sock
    • This command listens on TCP port 16509 and forwards all traffic to the libvirt Unix socket.
    • Run this in a screen or tmux session to keep it persistent.
  3. (Optional) Secure the port:

    • Use a firewall (e.g., ufw or iptables) to restrict access to the port to your IP only.

Step 2: On Your Local Machine

  1. Forward the remote TCP port over SSH:

    bash
    ssh -L 16509:localhost:16509 user@remote-host
    • This forwards the remote port 16509 to your local port 16509.
  2. Connect virsh to the local TCP port:

    bash
    export LIBVIRT_DEFAULT_URI="qemu+tcp://localhost:16509/system"
    virsh list
    • The LIBVIRT_DEFAULT_URI environment variable tells virsh to connect to the remote libvirt daemon via the tunneled port.

Alternative: Direct SSH Command (Not Recommended)

If you must run virsh commands directly over SSH (without tunneling), you can do:

bash
ssh user@remote-host "virsh list"

But this executes virsh on the remote host, which is not what you asked for.


Why This Works

  • socat converts the Unix socket to a TCP port, which SSH can forward.
  • The local virsh connects to the tunneled port, which is routed to the remote libvirt socket.
  • No virsh is executed on the remote host—only the socket is accessed.

Notes

  • Security: Ensure the socat port is not exposed to untrusted networks. Use SSH tunneling for encryption.
  • Persistence: Use systemd or supervisord to keep socat running after logout.
  • Libvirt URI: The URI format is qemu+tcp://[host]:[port]/system for QEMU/KVM. Adjust for other hypervisors (e.g., lxc:// for LXC).
Aug 10, 7:45pm

This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.

Vibe can make mistakes. Check answers. Learn more