XenServer Commands Cheat Sheet

Here you are a XenServer Commands Cheat Sheet!

  • Configure SR-IOV
    • /opt/xensource/libexec/xen-cmdline –set-xen iommu=1
    • lspci
    • xe vm-param-set other-config:pci=0/0000:07:10.0 uuid=uuid_of_the_VM
  • Enable and Disable Open VSwitch
    • xe-switch-network-backend bridge
    • xe-switch-network-backend openvswitch
  • Setup Diagnostic Website
    • cd /opt/xensource/www
    • ln –s /opt/xensource/debug/www debug
    • http://masterserverip/debug/index.html
  • Configure Auto Start VMs
    • Pool Config : xe pool-param-set uuid=… other-config:auto_poweron=true
    • VM Config: xe vm-param-set uuid=… other-config:auto_poweron=true
  • iSCSI Commands
    • discover: iscsiadm –mode discovery –type sendtargets –portal <IP-Address of the iSCSI target>
    • login: iscsiadm –mode node –targetname <target IQN you have discovered before> –portal <IP-Address of your Target>:3260 –login
    • logout: iscsiadm –mode node –targetname <target IQN you have discovered before> –portal <IP-Address of your Target>:3260 –logout
  • View TapDisks
    • tap-ctl list
    • ls -l /var/run/sr-mount/…..
  • Compare Template Differences
    • xe template-list name-label=Citrix\ XenApp\ on\ Windows\ Server\ 2003\ \(32-bit)\) params=all >> /root/2k3-32
    • xe template-list name-label=Citrix\ XenApp\ on\ Windows\ Server\ 2008\ \(32-bit)\) params=all >> /root/2k8-32
    • diff –side-by-side –suppress-common-lines /root/2k3-32 /root/2k8-32 (to see which parameters differ)
    • or
    • diff –suppress-common-lines /root/2k3-32 /root/2k8-32 (to see the full difference)
  • Reclaim Disk Space from Deleted XenServer Snapshots (http://support.citrix.com/article/CTX123400)
    • xe host-call-plugin host-uuid=<host-UUID> plugin=coalesce-leaf fn=leaf-coalesce args:vm_uuid=<VM-UUID>
  • Emergency Master Server Failure Recovery
    • xe host-emergency-ha-disable force=true
    • xe pool-emergency-transition-to-master
    • pool-designate-new-master host-uuid=<UUID of member XenServer host to become new master>
    • cat /etc/xensource/pool.conf to reflect to the new master.
    • Restarted XAPI service and it back to the pool.
  • Remove a Lost server from a Resource Pool

xe host-list
xe -s [ip address] -u root -pw PASSWORD pool-sync-database
xe -s [ip address] -u root -pw PASSWORD host-forget uuid=[the above command will provide the UUID]
xe pool-eject host-uuid

  • Copy a VM to another XenServer

xe vm-list (note the name of the VM you wish to copy)
xe sr-list (note the name of the storage you will to copy the VM to)
xe vm-copy (needs the following parameters to complete)
xe vm-copy vm=<name of VM to copy> sr-uuid=<UUID of SR to copy VM to> new-name-label=<NewNameofVM> new-name-description=”Description of VM”

  • Force Pool master Selection

xe pool-emergency-transition-to-master
xe pool-recover-slaves
xe host-list
xe pool-sync-database
xe host-forget

  • Check if XenServer is a Pool Master

cat /etc/xensource/pool.conf
Output says “master” , slaves output “slave:<master host IP>”

  • Enable Open vSwitch

xe-switch-network-backend openvswitch
xe host-list params=software-version

  • Enter XenServer Config Menu via SSH

xsconsole

  • Configure HA Timeout
      • xe pool-ha-enable heartbeat-sr-uuids=021e7e21-1e64-a0b3-2e22-5bbfcfe559e9 ha-config:timeout=10
      • Minimum timeout is 10 seconds
      • Default is 30 Seconds
      • xe pool-ha-compute-max-host-failures-to-tolerate
  • Destroying or forgetting a SR (Storage Repository)


xe -s [host ip] -u root -pw [password] sr-list
xe -s [host ip] -u root -pw [password] pbd-list sr-uuid=
xe -s [host ip] -u root -pw [password] pbd-unplug uuid=
xe -s [host ip] -u root -pw [password] pbd-destroy uuid=
xe -s [host ip] -u root -pw [password] sr-forget uuid=

  • xentop

displays real-time information about Xen system.

  • xen-bugtool –yestoall
  • Set HA Timeouot

xe pool-ha-enable heartbeat-sr-uuids=##### ha-config:timeout=however many seconds you want.

  • VM Operations

xe task-list
xe task-cancle uuid=xe
vm-shutdown –force vm=

  • Overload CPU for testing Workload Balancing

while true ; do true ; donewhile true ; do true ; done &while true ; do `ls –lR /` ; done

  • How to Create a Local Storage Repository (CTX121313)

# cat /proc/partitions
# ll /dev/disk/by-id
Find the disk ID of the “sdb” or “cciss/c0d1”disk. The “scsi-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx” or “cciss-xxxxxxxxxxxxxxxxxxxxxxxxxx”format is what you need.
Create a Storage Repository (SR):
# xe sr-create content-type=user device-config:device=/dev/disk/by-id/<scsi-xxxxxxxxxxxxxxxxxxxxxxxxx> host-uuid=<host-uuid> name-label=”Local Storage 2” shared=false type=lvm-
Or –
# xe sr-create content-type=user device-config:device=/dev/disk/by-id/<cciss-xxxxxxxxxxxxxxxxxxxxxxxxx> host-uuid=<host-uuid> name-label=”Local Storage 2” shared=false type=lvm

  • Cancel XenServer Tasks

xe task-list
xe task-cancel uuid=<task uuid>

  • Install XenTools on Linux

mount /dev/xvdd /mnt
cd /mnt/Linux
./install.sh

QLogic, run scli
Emulex, run hbanywhere
Emulex: /bin/sbin/ocmanager
QLogic FC: /opt/QLogic_Corporation/SANsurferCLI
QLogic iSCSI: /opt/QLogic_Corporation/SANsurferiCLI
Enable HA

  • xe vm-param-set uuid=<vm_uuid> ha-restart-priority=<1> ha-always-run=true
  • xe pool-ha-enable heartbeat-sr-uuids=<sr_uuid>

Reboot Host in HA

  • host-disable host=<hostname>
  • host-evacuate uuid=<host uuid>
  • host-shutdown host=<hostname>

Designate new master

  • Xe pool-designate-new-master host-uuid=<UUID of member XenServer host to become new master>

Pool Emergency Actions

  • host-emergency-ha-disable –force
  • pool-recovery-slaves
  • pool-eject host-uuid=<host UUID>
  • pool-emergency-reset-master master-address=<ip address of pool master>
  • pool-emergency-transition-to-master uuid=<host uuid>
  • xe pool-join master-address=<host1> master-username=<administrators_username> master-password=<password>

Snapshot Copy (Fast Clone)

  • xe snapshot-list snapshot-of=<vm uuid>
  • xe snapshot-copy new-name-label=<vm-template-name> snapshot-uuid=<uuid of the snapshot>
  • xe template-list
  • xe snapshot-export-to-template snapshot-uuid=<uuid of snapshot> filename=<template filename> (.XVA)
  • other-config snapmanager=true
  • xe vm-snapshot-with-quiesce vm=<vm uuid> ne-name-lablel=<name of new vm> (install-XenProvider.cmd)

Memory Consistent Snapshots

  • xe vm-checkpoint vm=<vm uuid> new-name-lable=<name of the snapshot>

Role Based Administration

  • xe subject-add subject-name=[active directory account name]
  • xe subject-role-add uuid=<subject uuid> role-name=<role_name>

Configure Management Interface

  • xe pif-scan, xe pif-list, xe pif-reconfigure-ip, xe host-management-reconfigure

Create NFS ISO Repository

  • xe sr-create host-uuid=<mast uuid> content-type=iso name-lable=<”name”> location=\\10.1.1.1:cds

Create a shared NFS SR on 192.168.1.10:/export1

  • xe sr-create host-uuid=<host_uuid> content-type=user name-label=<”Example shared NFS SR”> shared=true device-config:server=<192.168.1.10> device-config:serverpath=</export1> type=nfs

Physic NIC configuration

  • xe pif-scan
  • xe pif-plug
  • xe pif-introduce

VM in libo

  • xe vm-list
  • xe vm-reset-powerstate uuid=<uuid of VM> force=true

XAPI stack

  • service xapi status
  • service xapi restart
  • xe-toolstack-restart

XenServer Log Files

  • /var/log – XenServer Log Files
  • /etc/logrotate.conf – XenServer Log Rotation Configuration File

Search SR to locate metadata

  • xe sr-probe type=lvmoiscsi device-config:target=IP device-config:targetIQN=IQN device-config:SCSIid=SCSIID sm-config:metadata=true

Check VDI database

  • xe vm-list database:vdi-uuid=$my_vdi

Check inventory

  • . /etc/xensource-inventory
  • xe host-list uuid=$INSTALLATION_UUID

Exporting and Importing VMs via API – http://docs.vmd.citrix.com/XenServer/5.6.0fp1/1.0/en_gb/sdk.html#vm_import_and_export

  • curl http://root:foo@myxenserver1/export?uuid=<vm_uuid> -o <exportfile>
  • curl -T <exportfile> http://root:foo@myxenserver2/import?sr_uuid=<uuid_of_sr>
  • curl -T <exportfile> http://root:foo@myxenserver2/import
  • http://server/import_metadata
  • http://server/export_metadata.

15 usos prácticos del comando mysqladmin de MySQL

Aqui os dejo 15 usos prácticos del comando de MySQL tan usado por los syadmins, mysqladmin

mysql
MySQL

1. ¿Cómo cambiar la contraseña del usuario root en MySQL

# mysqladmin -u root -pxxx password ‘yyy’
# mysql -u root -pyyy
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 2
Server version: 5.0.67 MySQL Community Server (GPL)
Type ‘help;’ or ‘h’ for help. Type ‘c’ to clear the buffer.

2. ¿Cómo chequear si el servidor MySQL está corriendo?

# mysqladmin -u root -p ping
Enter password:
mysqld is alive

3. ¿Cómo saber que versión de MySQL tengo?

# mysqladmin -u root -pxxx version
mysqladmin  Ver 8.42 Distrib 5.0.67 on i686
Copyright (C) 2000-2006 MySQL AB
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL license
Server version          5.0.67
Protocol version        10
Connection              Localhost via UNIX socket
UNIX socket             /var/lib/mysql/mysql.sock
Uptime:                 100 days 0 hours 0 min 0 sec
Threads: 1 Questions: 241986 Slow queries: 0 Opens: 11097
Flush tables: 2 Open tables: 32 Queries per second avg: 1.23

4. ¿Cuál es el estado actual del servidor MySQL?

# mysqladmin -u root -pxxx status
Uptime: 8640000
Threads: 1 Questions: 241986 Slow queries: 0 Opens: 11097
Flush tables: 2 Open tables: 32 Queries per second avg: 1.23

El comando status muestra la siguiente información:

  • Uptime: segundos desde los que se inició el servidor
  • Threads: numero total de clientes conectados
  • Questions: número total de consultas que el servidor ha ejecutado desde desde su inicio.
  • Slow queries: número total de consulta que el servidor ha ejecutado y que tienen un tiempo mayor de ejecución a la variable long_query_time.
  • Opens: número total de tablas abiertas por el servidor.
  • Flush tables: cuantas tablas han sido «volcadas».
  • Open tables: número total de tablas abiertas en la base de datos.

5. ¿Cómo ver las variables de estado de MySQL y sus valores actuales?

# mysqladmin -u root -pxxx extended-status
+———————————–+———–+
| Variable_name                     | Value     |
+———————————–+———–+
| Aborted_clients                   | 579 |

6. ¿Cómo ver las variables del sistema de MySQL y sus valores?

# mysqladmin  -u root -pxxx variables
+———————————+———————————+
| Variable_name                   | Value                           |
+———————————+———————————+
| auto_increment_increment        | 1 |

7. ¿Cómo ver todos los procesos/consultas ejecutándose en la base de datos?

# mysqladmin -u root -pxxx processlist
+—-+——+———–+—-+———+——+——-+——————+
| Id | User | Host      | db | Command | Time | State | Info             |
+—-+——+———–+—-+———+——+——-+——————+
| 20 | root | localhost |    | Sleep   | 36 |       |                  |
| 23 | root | localhost |    | Query   | 0 |       | show processlist |
+—-+——+———–+—-+———+——+——-+——————+

También puedes correr este comando automáticamente cada un segundo de la siguiente forma:

# mysqladmin -u root -pxxx -i 1 processlist
+—-+——+———–+—-+———+——+——-+——————+
| Id | User | Host      | db | Command | Time | State | Info             |
+—-+——+———–+—-+———+——+——-+——————+
| 20 | root | localhost |    | Sleep   | 36 |       |                  |
| 23 | root | localhost |    | Query   | 0 |       | show processlist |
+—-+——+———–+—-+———+——+——-+——————++—-+——+———–+—-+———+——+——-+——————+
| Id | User | Host      | db | Command | Time | State | Info             |
+—-+——+———–+—-+———+——+——-+——————+
| 24 | root | localhost |    | Query   | 0 |       | show processlist |
+—-+——+———–+—-+———+——+——-+——————+

8. ¿Cómo crear una base de datos MySQL?

# mysqladmin -u root -pxxx create basedeprueba

9. ¿Cómo eliminar una base de datos MySQL?

# mysqladmin -u root -pxxx drop basedeprueba
Dropping the database is potentially a very bad thing to do.
Any data stored in the database will be destroyed.Do you really want to drop the ‘basedeprueba’ database [y/N] y
Database “basedeprueba” dropped

10. ¿Cómo recargar/refrescar los privilegios de la tabla de permisos?

# mysqladmin -u root -pxxx reload;

El comando refresh hará un flush de todas las tablas y cerrará/abrirá los archivos de log.

# mysqladmin -u root -pxxx refresh;

11. ¿Cuál es el método seguro de detener el servidor MySQL?

# mysqladmin -u root -pxxx shutdown

12. Listado de todos los comandos flush

# mysqladmin -u root -pxxx flush-hosts
# mysqladmin -u root -pxxx flush-logs
# mysqladmin -u root -pxxx flush-privileges
# mysqladmin -u root -pxxx flush-status
# mysqladmin -u root -pxxx flush-tables
# mysqladmin -u root -pxxx flush-threads

13. ¿Cómo matar un proceso pendiente de un cliente MySQL?
Previo a este comando es necesario identificar el thread a eliminar ejecutando el comando processlist de mysqladmin.

# mysqladmin -u root -pxxx kill 20

14. ¿Cómo iniciar y parar la replicación en un servidor esclavo en MySQL ?

# mysqladmin  -u root -pxxx stop-slave
Slave stopped# mysqladmin  -u root -pxxx start-slave

15. ¿Cómo combinar múltiples comandos de mysqladmin juntos?

# mysqladmin  -u root -pxxx process status version
+—-+——+———–+—-+———+——+——-+——————+
| Id | User | Host      | db | Command | Time | State | Info             |
+—-+——+———–+—-+———+——+——-+——————+
| 43 | root | localhost |    | Query   | 0 |       | show processlist |
+—-+——+———–+—-+———+——+——-+——————+Uptime: 3135
Threads: 1 Questions: 50 Slow queries: 1 Opens: 10 Flush tables: 2
Open tables: 0 Queries per second avg: 0.5
mysqladmin  Ver 8.42 Distrib 5.0.67 on i686
Copyright (C) 2000-2006 MySQL AB
This software comes with ABSOLUTELY NO WARRANTY. This is free software,
and you are welcome to modify and redistribute it under the GPL license

Server version          5.0.67
Protocol version        10
Connection              Localhost via UNIX socket
UNIX socket             /var/lib/mysql/mysql.sock
Uptime:                 52 min 15 sec

Vía: The Geek Stuff

<a title=»MySQL» href=»https://blogofsysadmins.com/category/mysql»><strong>MySQL</strong></a>

GoogleCL – Accede a los servicios de datos de Google por consola/terminal

De Google podemos decir cualquier cosa, excepto que sea predecible con sus nuevos servicios y aplicaciones. Y este es el caso de GoogleCL, una aplicación para acceder a los servicios de datos de la empresa desde la línea de comandos. Fue presentado con bombo y platillo hace no más de una semana y no es sino un gran script Python que usa las bibliotecas gdata (Google Data Protocol). Les presentaré unos ejemplos para comenzar a aprovecharlo.

Por ahora, GoogleCL soporta estos servicios:

Docs

  google docs edit --title "Comandos Linux"

Blogger

  google blogger post --title "Frase" "Si no te equivocas de vez en cuando, es que no lo intentas"

Calendar

  google calendar add "Desayuno en Tiffany"

Contacts

  google contacts list name,email > contactos-respaldo.csv

Picasa

  google picasa create --title "Fotos vergonzosas" ~/fotos/familia/*.png

Youtube

  google youtube post --category Education aprendiendo_navi.mp4

Instalación enUbuntu/Debian

Descarga el código fuente o bien el DEB para sistemas de la familia Debian. Elige tu favorita del sitio de descargas. La versión más reciente a la fecha es la 0.9.7. Desde Debian/Ubuntu ejecuta:

  sudo dpkg -i googlecl_0.9.7-1_all.deb

Uso

Hay muchos ejemplos en el sitio de GoogleCL. Aquí me concentraré en mostrar cómo configurar el acceso a Google Docs desde la línea de comandos. Antes de eso debes saber que ejecutado sin argumentos, GoogleCL inicia una sesión interactiva a través del comando google, con el carácter “>” como prompt.

  google
  > help
  Welcome to the Google CL tool!
    Commands are broken into several parts: service, task, options, and arguments.
    For example, in the command

    [...más salida...]

    Enter "> help <service>" for more information on a service.
    Or, just "quit" to quit.

   > help docs
   Available tasks for service docs: 'edit', 'delete', 'list', 'upload', 'get'
    edit: Edit a document
     Requires: title Optional: format, editor

    delete: Delete documents
     Requires: none Optional: title

    list: List documents
     Requires: delimiter Optional: title, folder

    upload: Upload a document
     Requires: none Optional: title, folder, no-convert Arguments: PATH_TO_FILE

    get: Download a document
     Requires: (title OR folder) Arguments: LOCATION

  > quit

Usaré la sesión interactiva en todos los ejemplos.

Es importante configurar el navegador que utilizaremos con GoogleCL para realizar ciertas tareas. Hay dos opciones: exportar una variable de ambiente BROWSER o editar el archivo de configuración de la aplicación. Te recomiendo esta última.

  echo auth_browser=firefox >> ~./google/config

Desde el shell de GoogleCL y con ayuda de la documentación haremos unas sencillas tareas. Comencemos por obtener una lista de nuestros documentos. La primera vez te solicitará un usuario y luego que aceptes desde el navegador que GoogleCL pueda acceder a tu cuenta en el futuro.

  google
  > docs list
  Please specify user: *****
  Please log in and/or grant access via your browser at https://www.google.com
  ***** then hit enter.

El navegador que elegiste se abre y debes dar clic en “Grant access”. Un archivo access_tok_tu_usuario se crea bajo el directorio ~./google.

De ahora en adelante ya no será necesario autorizar nada para ese usuario. Después de aceptar, en el shell de google aparece un listado de tus archivos. Aquí muestro una vista parcial de la salida porque es extensa.

  Lista de ejemplos,http://docs.google.com/Doc?docid=*****
  Reporte 10-P,http://spreadsheets.google.com/ccc?key=*****
  [... más salida ...]

Ahora edito un documento de texto con Vim.

 docs edit --title "In the beginning was the command line" --editor vim

Y aquí lo descargo

 docs get --title "In the beginning was the command line"
 Downloading In the beginning was the command line to /home/eli/In the [...] .txt

Conclusiones

Como sucede con cualquier herramienta, GoogleCL puede ser tan poderoso como lo quieras. Sobre todo si lo incluyes en tus scripts personales. Además notarás que algunas opciones tienen bugs, pero ten paciencia y espera la versión 1.0 estable. Si eres frecuente usuario del shell y de los servicios de Google, encontrarás en GoogleCL un importante aliado para tu productividad.

Buscar un archivo creado entre dos fechas en al shell de Linux

Te acuerdas que creaste un archivo entre el 15 de Septiembre de 2010 y el 30 de Septiembre de ese mismo año. ¿Cómo lo puedes buscar en Linux? Fácil, usando el comando find y estos truquitos:

Primera forma para versiones antiguas del comando find (< =2.4)

$ touch -d "15 sep 2010" /tmp/begin
$ touch -d "30 sep 2010" /tmp/end
$ find . -newer /tmp/begin -a \! -newer /tmp/end

Segunda forma (Para versiones nuevas de find (>=2.4), te lo puedes hacer con un solo comando mediante la opción ‘-newerXY’)

$ find . -newermt “15 sep 2010″ \! -newermt “30 sep 2010″)

Lo he necesitado varias veces y nunca me acordaba de la receta, así que la dejo aquí compartida para todos. ¡Que os aproveche!

The Linux Command Line – Ebook

The Linux ® Command Line es un libro publicado bajo licencia Creative Commons creado por William E. Shotts, Jr especialmente para aquellos que se están iniciando en el mundo de la línea de comandos Linux.

En sus 522 páginas se cubre el mismo material disponible en LinuxCommand.org pero con mucho más detalle. Además de lo básico de la línea de comandos se enseña el shell scripting y el uso de los programas más comunes de la línea de comandos Linux.

Podéis descargar el libro a través de este Link.

http://sourceforge.net/projects/linuxcommand/files/TLCL/09.12/TLCL-09.12.pdf/download

Web oficial de el libro. http://linuxcommand.org/