Настройка ip-адреса vmware esxi

Vmware

Important Log Files

  • Host abruptly rebooted

    /var/log/vmksummary.log

  • Slow boot issues

    /var/log/boot.gz  (You can also enable serial logging (Shift + o))

  • ESXi not responding

    • /var/log/hostd.log
    • /var/log/hostd-probe.log
  • VM issues

    vmware.log (This file is located in virtual machine folder along with the vmx file)

  • Storage issues

    /var/log/vmkernel.log

  • Network and storage issues

    /var/log/vobd.log

  • HA issues

    • /var/log/fdm.log
    • /opt/vmware/fdm/prettyprint.sh hostlist | less
  • Unable to login because, root account lockout

    • /var/log/vobd.log
    • /var/log/auth.log
    • By default 10 maximum attempts. Only active in SSH and WebService.

Conclusion

Today’s blog post has covered a series of ESXi shell commands including ESXCLI commands. Using the command line interface in ESXi gives you more power in addition to nice graphical user interfaces of VMware vSphere Client and VMware Host Client for managing ESXi hosts. You can use ESXi shell commands for viewing and configuring settings that are hidden or not available in the GUI. Use the ESXi shell commands list provided in this blog post for fine ESXi tuning and experience the extra power of using the command line interface in VMware vSphere. You can learn more by reading about PowerCLI, another type of the command line interface for managing VMware vSphere from Windows PowerShell.

Отказоустойчивость

Что будет, если упадёт кластер KMS

Очевидно, что ничего хорошего. В окне конфигурации Key Management Servers в vCenter будет такая картина.

Падение KMS не повлияет на уже запущенные VM, которые продолжать работать (и их можно будет выключать, включать, мигрировать на другие хосты) до тех пор, пока в ОЗУ ESXi хранятся KEK, ранее полученные у KMS. KEK будут храниться в памяти до перезагрузки ESXi хоста.

При попытке включить VM Encryption при неработающем KMS пойдут ошибки генерации ключа.

Что произойдёт при перезагрузке ESXi хоста

Хост будет требовать включить шифрование вручную

VM, будучи зарегистрированной на хосте, который не хранит в ОЗУ KEK для этой VM (например, если ESXi хост был перезагружен или был добавлен в кластер после первичной инициализации шифрования), будет требовать разблокировать её, передав KEK на ESXi хост.

Adding a Cron Job

You’ll first need to SSH into your ESXi host. Once there, you can see the current crontab file at /var/spool/cron/crontabs/root. In ESXi 7.0, the file contains:

As you can see, ESXi already uses cron to schedule several internal housekeeping routines. Before changing the file, be sure to back it up just in case:

You can modify the file using ‘vi’. For those not familiar with Linux, there is a bit of a learning curve to vi so I’d recommend reading up on how to navigate around in it. There are quite a few good turorials available online.

Note: When using :wq to save your changes, you’ll likely get a warning that the file is read only. You don’t need to fiddle with the permissions. Simply use :wq! and the file will be written successfully.  

I have added a single line at the bottom of the file. Here is the updated root crontab file:

Note: As mentioned previously, if you are not familiar with the min/hour/day/mon/dow formatting that cron uses, there are a number of good resources online that can help.

Despite updating the file, your changes will not take effect until the crond service is restarted on the host. First, get the crond PID (process identifier) by running the following command:

Next, kill the crond PID. Be sure to change the PID number to what you obtained in the previous step.

Once the process is stopped, you can use BusyBox to launch it again:

You’ll know it was restarted successfully if you have a new PID now:

After leaving the host idle for a few minutes, you can see the command has been running every two minutes as desired:

As you can imagine, the possibilities are endless here. I will share some of the scripts I have used to collect some performance metrics via cron in a future post.

Полный перечень команд

Описание Запрос
Общая информация
Показать детальную информацию ctrl all show config detail
Статус контроллера ctrl all show status
Пересканировать устройства rescan
Пересканировать новые добавленные устройства rescandetects newly added devices since the last rescan
Добавить лицензионный ключ для RAID контроллера ctrl slot=1 add licensekey=XXXXX-XXXXX-XXXXX-XXXXX-XXXXX
Работа с физическими дисками в RAID-массиве  
Получить информацию о всех дисках в указанном контроллере ctrl slot=1 pd all show status
 Получить информацию о конкретном диске ctrl slot=1 pd 1I:1:8 show detail
Очистка диска ctrl slot=1 pd 1I:1:8 modify erase
Управление светодиодами дисков ctrl slot=1 pd 1I:1:8 modify led=on/off
Работа с логическими томами  
Показать информацию о логических томах на контроллере ctrl slot=1 ld all show detail
Показать информацию о конкретном логическом томе на контроллере ctrl slot=1 ld 1 show detail
Показать статус всех логических томов на контроллере ctrl slot=1 ld all show status
Показать статус конкретного логического тома на контроллере ctrl slot=1 ld 1 show status
Создание логического тома на примере RAID-5 ctrl slot=1 create type=ld drives=1I:1:1,1I:1:2,1I:1:3,1I:1:4, 1I:1:5 raid=5
Добавить физический диск в логический том ctrl slot=1 ld 1 add drives=1I:1:6,1I:1:7
Добавить запасной диск ctrl slot=1 array all add spares=1I:1:8
Удаление логического тома ctrl slot=1 ld 1 delete
Расширение логического тома на максимальный размер ctrl slot=1 ld 1 modify size=max forced
Перезапуск отказавших дисков ctrl slot=1 ld 1 modify reenable forced
Трансформирование уровня RAID (в пример в RAID 1) ctrl slot=1 ld 1 modify raid=1
Установить повышенный приоритет трансформации ctrl slot=1 modify rebuildpriority=high
Работа с Кэшем 
Изменить соотношения чтения\записи кэша ctrl slot=1 modify cacheratio=100/0 (cacheratio=чтение/запись)
Отключить\Включить кэш для определенного логического тома ctrl slot=0 logicaldrive 1 modify arrayaccelerator=disable/enable
Работа с HP SSD Smart Path 
Включение/выключение HP SSD Smart Path ctrl slot=1 array a modify ssdsmartpath=enable/disable

Conclusion

Today’s blog post has covered a series of ESXi shell commands including ESXCLI commands. Using the command line interface in ESXi gives you more power in addition to nice graphical user interfaces of VMware vSphere Client and VMware Host Client for managing ESXi hosts. You can use ESXi shell commands for viewing and configuring settings that are hidden or not available in the GUI. Use the ESXi shell commands list provided in this blog post for fine ESXi tuning and experience the extra power of using the command line interface in VMware vSphere. You can learn more by reading about PowerCLI, another type of the command line interface for managing VMware vSphere from Windows PowerShell.

About ESXCLI Commands

ESXCLI is a part of the ESXi shell, this is a CLI framework intended to manage a virtual infrastructure (ESXi components such as hardware, network, storage, etc.) and control ESXi itself on the low level. All ESXCLI commands must be run in the ESXi shell (console). Generally, ESXCLI is the command that has a wide list of subcommands called namespaces and their options. The ESXCLI command is present right after ESXi installation along with other ESXi shell commands. You can locate ESXCLI and explore the nature of ESXCLI after executing the following commands:

which esxcli

ls -l /sbin/esxcli

ESXICLI is a complex script written in Python

As you see in the console output, ESXCLI is a script written in Python that is located in the /sbin/ directory. If you want to see the contents of the script, you can use the built-in text editor vi.

Thus, ESXCLI consists of branches that are the main categories (namespaces) of ESXCLI commands. Notice that ESXCLI commands are case-sensitive, similarly to other console commands used in ESXi. The entire list of all available ESXCLI namespaces and commands is displayed after running the command:

esxcli esxcli command list

The list of available ESXCLI commands depends on the ESXi version.

Hence, the list of top ESXCLI namespaces for ESXi 6.7 is as follows:

  • device – device manager commands
  • esxcli – commands related to ESXCLI itself
  • fcoe – Fibre Channel over Ethernet commands
  • graphics – VMware graphics commands
  • hardware – commands for checking hardware properties and configuring hardware
  • iscsi – VMware iSCSI commands
  • network – this namespace includes a wide range of commands for managing general host network settings (such as the IP address, DNS settings of an ESXi host, firewall) and virtual networking components such as vSwitch, portgroups etc.
  • nvme – managing extensions for VMware NVMe driver
  • rdma – commands for managing the remote direct memory access protocol stack
  • sched – commands used for configuring scheduling and VMkernel system properties
  • software – managing ESXi software images and packages for ESXi
  • storage – commands used to manage storage
  • system – commands for configuring VMkernel system properties, the kernel core system and system services
  • vm – some commands that can be used to control virtual machine operations
  • vsan – VMware vSAN commands

The main commands appear as verbs indicating the same action:

  • list – show the list of objects available for the defined namespace (for example, esxcli hardware bootdevice list – list available boot devices)
  • get – get the value of the defined setting or property (for instance, esxcli hardware clock get – check the time set)
  • set – set the necessary parameter manually (for example, esxcli hardware clock set -y 2019 -s 00 – set the year to 2019 and set the seconds to 00)
  • load/unload – load/unload system configuration (esxcli network firewall load – load the firewall module and firewall settings stored in the configuration file)

If you are unable to remember a particular ESXCLI command related to the appropriate namespace, you can enter the command and see a tip in the output of the console—for example, type:

esxcli network to see all available commands for the network namespace, then type:

esxcli network vm to check the commands for the vm namespace.

Viewing the ESXi shell commands for the ESXCLi network namespace

The ESXCLI log file is located in /var/log/esxcli.log

The data is written to this file if an ESXCLI command has not been executed successfully. If an ESXCLI command is run successfully, nothing is written to this log file.

Симптом

Тормозили нагруженные виртуальные машины, при этом по мониторингу vSphere наблюдалась весьма интересная картина.

На виртуальной машине Disk latency time составлял до нескольких секунд. Конечно, в таком случае чего удивляться, что система тормозит.

5d461036-284c-c2e1-9649-7e62db163a2b?t=1582616273174

НО, с точки зрения системы хранения и ГИПЕРВИЗОРА ESXi на котором виртуальная машина жила картина была очень и очень хорошей — Disk latency time на хосте с множеством виртуальных машин по всем дискам не превышал 200 мс. Три секунды показанные виртуальной машиной и близко не стоят к показанной цифре.

b28bc78f-9857-f04f-4062-a050a39a4a3f?t=1582616703184

Несоответствие потребовало детального разбора в происходящем.

Действия на стороне СХД

Необходимые настройки на СХД можно разделить на два этапа:

  • Настройка интерфейсов
  • Настройка пространства хранения

Настраивать интерфейсы требуется в основном в случае использования протокола iSCSI: необходимо задать IP адреса портов на вкладке iSCSI Ports. IP адреса портов должны быть из разных подсетей, чтобы однозначно маршрутизировался трафик на стороне хоста.

В случае использования интерфейса Fibre Channel ничего настраивать, как правило, не нужно.

Далее необходимо создать пространство хранения. Сначала создается пул – группа физических накопителей, работающих совместно. Пулов в пределах СХД может быть несколько. Накопители внутри пула объединяются в соответствии с выбранным при его создании уровнем RAID, обеспечивая заданную надежность. Пулы создаются на вкладке Pools → Create Pool, где запускается пошаговый мастер.

Как её исправить?

Проблемы с оперативной памятью

Оперативная память может являться прямым источником данной ошибки. Например, пользователи старых компьютеров зачастую хотят ускорить работу системы, и самым очевидным способом является увеличение объема оперативной памяти. Но, не ознакомившись с руководством к материнской плате, в котором четко указана характеристика оперативной памяти и ее максимальный объем, наш обыватель покупает модуль памяти побольше и «чтоб подходила по разъёму», это неправильно.

Перед тем как покупать новый модуль памяти для начала нужно убедиться, что он будет совместим с Вашей материнской платой

Важно! Если объём оперативной памяти увеличится в размере от 4 гБ и выше, для того чтобы система использовала весь объём, необходимо будет переустановить операционную систему на 64-разрядную.

Связано это с тем, что изначально при производстве не был выявлен дефект или во время интенсивной работы системы, когда оперативная память неоднократно перегревалась. Последствие этого перегрева внутри модуля появились «BAD SECTOR» (плохие секторы). Плохие сектора оперативной памяти не дают системе и программам правильно работать и не редко могут вызвать и другие ошибки (синие экраны).Решение этой проблемы – это частичная, либо полная замена оперативной памяти на новую. Но перед заменой необходимо произвести полную диагностику оперативной памяти.

Внимание! Диагностику должен производить квалифицированный специалист, обладающий необходимыми навыками и оборудованием для проведения диагностики.

Повреждение системного драйвера «win32k.sys»

Как уже было сказано выше, файл «win32k.sys» может быть заражен вирусом и антивирус попытается его вылечить или удалить. Повреждение «win32k.sys» также приведет его в нерабочее состояние.

  1. Первое что необходимо сделать — это проверить карантин антивируса и его журнал. Если файл находится в карантине, то можно попытаться его восстановить и добавить в исключения антивируса. Естественно, если он туда попал, то не просто так, и после удачного восстановления желательно сохранить все важные файлы скачав их на флэшку или жёсткий диск. Далее переустановить систему. Это чистовой вариант решения проблемы, но перед тем как обратно закачивать файлы на компьютер установите антивирус.
  2. Если в карантине не нашелся «win32k.sys», то вероятнее всего он повреждён. Здесь нам понадобится системная утилита проверки файлов, она же и попытается восстановить повреждённый файл.
  3. Нам понадобится запустить командную строку от имени администратора. Переходим в меню «Пуск» -> «Все программы» -> «Стандартные» и находим в списке «Командная строка» нажимаем на нее правой кнопкой мыши и нажимаем на пункт «Запуск от имени администратора» далее в появившемся окне жмем «Да», тем самым мы подтверждаем свои действия.
  4. В открывшемся окне вводим команду «sfc /scannow» (без кавычек) далее на клавиатуре жмем «Enter» и дожидаемся окончание процесса.
  5. После сканирования в окне появятся результаты проверки. Если будет обнаружена ошибка в файлах системы, Windows их устранит и после этого потребуется перезагрузка системы.

Несовместимость «железа» и ОС

Иногда пользователи приобретают новый компьютер или ноутбук с очень скромными характеристиками, и ошибочно полагают, что на новый компьютер лучше всего установить операционную систему «попроще», и как правило устанавливают Win. XP.

Проблема кроется в том, что старая система не была рассчитана на новые стандарты памяти, контроллеры, шины и прочее внутренне наполнение компьютера. Вследствие чего возникают конфликты и проблемы несовместимости «железа» с операционной системой в виде «синих экранов», разных ошибок, не говоря уже о драйверах которые просто не выпускаются на старые операционные системы.

Примечание. Новые операционные системы не всегда высоко-требовательны, их сильная сторона в оптимизации ресурсов компьютера.

Important: Protect VMware VM from security threats

Before making big changes, a backup of the virtual machine is needed, especially when using unfamiliar VMware commands, since it is likely to cause damage to your virtual machines. Here, I’d like to apply AOMEI Cyber Backup, a free VMware backup software, to provide continuous protections for virtual machines. With this professional tool, you can get the following benefits.

Support Free ESXi: AOMEI Cyber Backup supports both paid and free versions of VMware ESXi.Secure VM backup: schedule VMware or Hyper-V virtual machine backups and perform hot backup to protect crucial data continuously without human errors.Instant disaster recovery: instantly restore the whole virtual machine to the previous state or restore it to another host based on a few clicks.Full compatibility: centrally manage VMs on VMware ESXi 6.0 and later versions, as well as Hyper-V in Windows 8/8.1/10/11, Windows Server/Microsoft Hyper-V Server 2012 R2 and later versions.

Create a secure backup task that covers multiple ESXi VMs. You can click the following button to download the perpetual Free Edition:

Download FreewareVMware ESXi & Hyper-V
Secure Download

*You can choose to install this VM backup software on either Windows or Linux system.

One quick virtual machine backup software

1. Bind Devices: Access to AOMEI Cyber Backup web client, navigate to Source Device >> VMware / Hyper-V to add a host. Take VMware as an example, you can Add vCenter or Standalone ESXi for VMs backup.

Add VMware ESXi host

2. Click Backup Task > Create New Task to set up the backup task as you need.

  • Device Type: You can either create a VMware ESXi Backup or Hyper-V Backup.
  • Device: Select the VMs you want to backup on the host in one task.
  • Target: You can select to back up to a local path, or to a network path. Used paths will be saved in Favorite Storage for handy selection.
  • Schedule: You can schedule VM backup. Choose to perform full, differential or incremental backup, and automate execution daily, weekly or monthly according to the frequency you specified.

schedule VMware backup

3. Start Backup: Click Start Backup and select Add the schedule and start backup now, or Add the schedule only.

✎ In addition to the basic features, you can also upgrade to enjoy advanced functions:✦ Batch VM backup: batch backup large numbers of VMs managed by vCenter Server or on standalone ESXi hosts.✦ Backup Cleanup: You can specify a retention policy, and the old backup files that exceed the period will be automatically deleted.✦ Restore to new location: If your original VM corrupts, you can easily restore VM to its previous place or to another datastore/host without any complicated configuration and reinstallation.

Фильтрация результатов

Используя командлет Get-* совместно с PowerShell-командой ‘where’, вы можете
получить результаты по интересующим вас свойствам. Если вы хотите вывести список всех виртуальных
машин, находящихся в режиме PoweredOn, и отобразить результаты вывода с характеристиками:
имя машины, количество процессоров, используемая память, статус ВМ и имя VM-хоста,
примените следующий командлет:

    Get-VM | Where {$_.Powerstate -eq “PoweredOn”} | Select Name, NumCPU, MemoryMB, PowerState, VMHost

Обратите внимание на переменную $_, которая хранит текущий объект конвейера,
а результат выводится следующим образом:

Рисунок 3. Список виртуальных машин согласно заданным критериям

Hardware change

Change MAC address

In the event of a hardware (ex)change, especially the motherboard, it should be noted that the ESXi host retains its original MAC address. This leads to issues. The switch will not automatically forward the correct new main IP to the server, as the MAC address that is being broadcast is incorrect. You need to reset the MAC address via the ESXi shell. There are several approches for doing this, listed in the following VMWare Knowledge Base Article. The most elegant solution is when the ESXi host automatically recognizes the new MAC address when changing platforms and uses that. You can use the following command for that:

Either perform this command before the platform change or, if the change has already happened, there are two options:

  • Order a KVM Console console and enable the ESXi shell, and then press to switch to the console and enter the command. Afterwards, pressing will bring you back to the GUI.
  • Temporarily teach the switch the new MAC address by booting into the Rescue System and then back into the ESXi host. As a result, the ESXi host will now be reachable again via the main IP, but only for a limited amount of time. The length of this time depends on how long the switch takes to delete the ARP cache entry for this MAC address. Normally there is enough time to log in via SSH and execute the command, assuming that you have enabled SSH access. However, even this is configurable, as connecting via the ESXi client would be possible again.

With either option, you need to do a restart afterwards. You can initiate this via the console:

After a restart, the MAC address should be set correctly and you can verify this in the ESXi shell with the following command:

The new MAC address should show up next to the main IP.

Code & Tools

Python

  • pyvmomi — Python SDK for the VMware vSphere API that allows you to manage ESX, ESXi, and vCenter.
  • pyvmomi-community-samples — Community contributed samples for the pyVmomi library.
  • pyvmomi-tools — Incubator project for additional pyVmomi based tools and libraries as needed by the development community.

Third-Party

  • esxi-tools — A collection of Python tools and scripts to automate the management of a remote ESXi host.
  • esxi-util — python scripts to operate ESXi server.
  • py-vconnector — VMware vSphere Connector Module for Python.
  • django-vsphere — django-vsphere is an app for Django to have a centralized dashboard for all your VMWare vSphere ESXi.
  • esxi-simple-web — Basic controls for esxi host in the browser.
  • ESXi-PoC-Client — C++ client to communicate with ESXi Web-service and dump virtual machines information.
  • pi-control — Control & monitor ESXi hypervisor from raspberry-pi.
  • suseviclient — Lightweight tool for ESXi management from Linux box.
  • vmmng — Simple, yet effective, VMWare ESXi comand line wrapper written in Ruby.
  • RVC — Ruby vSphere Console — Linux console UI for vSphere, built on the RbVmomi bindings to the vSphere API.

esxi два метода проверки работоспособности жесткого диска

Список жестких дисков

Просмотр интеллектуальной информации о жестком диске

Предварительное понимание регулярных выражений Python (4)

Сегодня я продолжу делиться базовыми знаниями о регулярных выражениях Python. В основном я представляю использование специального символа «». Ниже приведено конкретное руководство. .

Использование внутреннего соединения, левого соединения, правого соединения в оракуле

Левое-правое соединение фактически говорит, какая таблица является результатом нашего совместного запроса ~ 1. Взаимосвязь проста select A.*, B.* from A,B where A.id = B.id select A.*, B.* from.

Готов к работе

  • win7
  • u диск
  • ESXi зеркало
  • Драйвер сетевой карты
  • Программное обеспечение для переупаковки изображений
  • u программа для записи дисков

Win7 используется для запуска программы для переупаковки образов ESXi-Customizer и программы записи на дискету.
Флэш-накопитель USB используется для записи образа ESXi.
Для загрузки зеркала требуется учетная запись vmware,Зеркальный адрес загрузки
При установке ESXi обычно отсутствуют драйверы сетевой карты, поэтому их можно упаковать только вручную.Адрес загрузки драйвера сетевой картыЯ под net55-r8168.
Программное обеспечение для переупаковки образов ESXi-Customizer используется для упаковки драйвера в образ. Используется ESXi-Customizer-v2.7.2. Он немного устарел, но все еще прост в использовании

Обратите внимание, что его можно запустить только под win7, но не под win10.
U дискеты с программным обеспечением для записи дисков не упоминаются, другие программы для записи также в порядке.

Заключение

В первой части статьи мы познакомились с особенностью администрирования виртуальной инфраструктуры средствами PowerShell
и PowerCLI. Научились автоматизировать создание отчетов, извлекать свойства относительно заданных объектов виртуализации,
создавать и конфигурировать кластер, настраивать функциональность HA и DRS.

Следите за новыми материалами первого блога о корпоративном IaaS.
В следующей статье мы расскажем, как с помощью командной строки перемещать узлы в кластер, настраивать виртуальный свитч, мигрировать сетевые настройки, автоматизировать
процесс создания виртуальных машин, наводить порядок в виртуальном и облачном окружении, используя теги.

Понравилась статья? Поделиться с друзьями:
Быть в курсе нового
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: