Feature suggestion : allow pct enter to work with the hostname rather than ID number

shodan

Active Member
Sep 1, 2022
235
66
33
Example

Code:
root@proxmox:~# pct list
VMID       Status     Lock         Name
100        stopped                 test1
107        stopped                 ooga
115        running                 sdweb
116        stopped                 textgen
125        stopped                 comfyui
130        stopped                 nginx
131        stopped                 http-server
999        stopped                 myopenwrt
1001       stopped                 myopenwrt2
root@proxmox:~# pct enter sdweb
400 Parameter verification failed.
vmid: type check ('integer') failed - got 'sdweb'
pct enter <vmid> [OPTIONS]
 
bash workaround:


Code:
vmid=$(pct list |grep -m 1 sdweb |awk '{print $1}')
[ "$vmid" = "" ] && echo "Error" || pct enter $vmid

# substitute sdweb with $1 for OTF argument
 
bash workaround:


Code:
vmid=$(pct list |grep -m 1 sdweb |awk '{print $1}')
[ "$vmid" = "" ] && echo "Error" || pct enter $vmid

# substitute sdweb with $1 for OTF argument
That will always yield the container with the smallest VMID in case of multiple containers with the same name. If that is what you want, you can use it.
 
pct list can be slow, even hang. I use this:

Code:
lxc() {
   vmid() {
      local arg="$1"
      if [[ ! "$arg" =~ ^[0-9]+$ ]]; then
         for f in /etc/pve/lxc/*.conf; do
            h=$(awk -F': ' '/^hostname:/ {print $2}' "$f")
            if [[ "$h" == "$arg" ]]; then
               basename "$f" .conf
               return
            fi
         done
      fi
      echo "$arg"
   }

   # Single arg -> pct enter <vmid/hostname> with root login shell
   if [ $# -eq 1 ]; then
      pct exec "$(vmid "$1")" -- su -l root
      return
   fi

   if [[ "$1" == "enter" ]]; then
      # enter <vmid/hostname> -> pct enter <vmid/hostname> with root login shell
      pct exec "$(vmid "$2")" "${@:3}" -- su -l root
   else
      # Multiple args -> pct <command> <vmid/hostname> $@
      pct "$1" "$(vmid "$2")" "${@:3}"
   fi
}

Examples:
Code:
lxc 107 <- shortcut to enter
lxc enter 107
lxc reboot 107
lxc media <- shortcut to enter by name
lxc enter media <- enter by name
lxc reboot media <- any command by name!

And when you enter it gives you a proper root login shell (runs .bashrc, etc).