Python для системного администратора windows

Автор перевода messerr, просто с кармой ему не повезло.

Введение

 

Как системный администратор, вы сталкиваетесь с многочисленными проблемами. Управление пользователями, дисковым пространством, процессами, устройствами и бэкапами могут стать причиной потери волос, юмора или вменяемости у многих администраторов. Shell скрипты могут выручить, но они зачастую имеют множество ограничений. В этом случае полнофункциональный скриптовый язык, такой как Python, способен превратить утомительную задачу в легкую и, смею сказать, веселую.
Примеры в этой статье демонстрируют различные возможности Python, которые вы можете использовать на практике. Если Вы работаете с помощью них — вы на правильном пути к пониманию силы Python.
 

О модулях

 

Модуль – важное понятие в языке Python. По существу, модуль – это ресурс, который вы подключаете к программе, чтобы затем использовать его. Этот процесс можно сравнить  с тем, что вы достанете из ящика лист бумаги и положите его на свой стол, подготовив тем самым к дальнейшему использованию. Модули подключаются при помощи команды import, которая присутствует в начале каждого примера. Модули доступны для связи с базами данных, сетевого программирования, сервисов операционных систем и сотен других полезных областей.

Заставим Python работать

Python — полнофункциональный, надежный язык программирования и, по существу, имеет массу свойств. Изучение его может стать задачей эпических масштабов. Однако, помните, что многие способности, такие как GUI инструментарий, имеют для системного администратора низкую ценность. Вот почему в этой статье используются специфичные примеры: они демонстрируют навыки, необходимые для эффективного написания скриптов управления системой.

Немного о примерах:

  • Каждый пример использует try: и except: с блоком кода внутри. Это осуществляет элементарную обработку ошибок. Python имеет обширную поддержку для обработки всех видов исключений, но, в рамках примеров этой статьи, я обошелся простой проверкой.
  • Эти примеры тестировались с помощью Python 2.5, запущенном на Linux® box, но они должны работать на любой Unix/Linux машине.

Вы несомненно задумаетесь об улучшении этих скриптов. Это хорошо! Натура Python-скриптов заключается в том, что они могут быть легко модифицированы и настроены без необходимости перекомпиляции.

 
Пример 1: Поиск файлов и отображение прав в дружественном формате

Первый пример (Листинг 1) осуществляет поиск файлов, в соответствии с шаблоном (который вводит пользователь) и выводит результат на экран вместе с правами доступа для каждого файла. Во-первых, вы можете подумать, что эта программа не делает ничего большего, чем вызов команды find; однако она отображает результаты особым образом и ваши варианты отображения этого расширенного поиска безграничны.
Скрипт по существу решает три задачи:

  1. Получает шаблон поиска от пользователя
  2. Выполняет поиск
  3. Показывает результаты пользователю

При написании скрипта постоянно задавайте себе вопрос, «Выполнение какой задачи данный код обеспечивает?» Задавая себе этот вопрос, вы повышаете внимание в вашей работе и ее эффективность.

Листинг 1. Поиск файлов и отображение результатов с правами доступа.

# -*- coding: utf-8 -*-
import stat, sys, os, string, commands
#Записываем в переменную шаблон поиска, введенный пользователем
try:
    pattern = raw_input("Введите шаблон поиска:\n")
    #запускаем команду 'find' и присваиваем результат переменной
    commandString = "find " + pattern
    commandOutput = commands.getoutput(commandString)
    findResults = string.split(commandOutput, "\n")
    #выводим найденные файлы вместе с правами доступа
    print "Файлы:"
    print commandOutput
    print "================================"
    for file in findResults:
        mode=stat.S_IMODE(os.lstat(file)[stat.ST_MODE])
        print "\nPermissions for file ", file, ":"
        for level in "USR", "GRP", "OTH":
            for perm in "R", "W", "X":
               if mode & getattr(stat,"S_I"+perm+level):
                   print level, " имеет ", perm, " права доступа"
               else:
                   print level, " не имеет ", perm, " прав доступа"
except:
    print "Возникла проблема! Проверьте сообщение выше."

Программа следует по следующим этапам:

  1. Запрашивает у пользователя шаблон поиска (строки 7-9).
  2. Печатает список найденных файлов (строки 12-14).
  3. Используя модуль stat, получает права доступа для каждого найденного файла и отображает их на экране (строки 15-23).

Результат работы программы показан в Листинге 2.

$ python example1.py
Enter the file pattern to search for:
j*.py

Листинг 2. Вывод первого примера

$ python example1.py
Введите шаблон поиска:
j*.py
Файлы:
jim.py
jim2.py~
================================
Permissions for file  jim.py :
USR  имеет  R  права доступа
USR  имеет  W  права доступа
USR  не имеет  X  прав доступа
GRP  имеет  R  права доступа
GRP  не имеет  W  прав доступа
GRP  не имеет  X  прав доступа
OTH  имеет  R  права доступа
OTH  не имеет  W  прав доступа
OTH  не имеет  X  прав доступа
Permissions for file  jim2.py :
USR  имеет  R  права доступа
USR  имеет  W  права доступа
USR  не имеет  X  прав доступа
GRP  имеет  R  права доступа
GRP  не имеет  W  прав доступа
GRP  не имеет  X  прав доступа
OTH  имеет  R  права доступа
OTH  не имеет  W  прав доступа
OTH  не имеет  X  прав доступа

Пример 2: Выполнение операций с архивом tar при помощи меню

Предыдущий пример для своей работы запрашивал у пользователя поисковый шаблон. Другой способ получить от пользователя информацию — аргумент в командной строке. Программа в Листинге 3 показывает как сделать это в Python: код берет имя файла tar, как аргумент командной строки и затем предложит пользователю несколько опций.
Этот пример так же показывает новый способ решения проблемы. Первый пример использовал модуль команд для запуска find и захвата вывода. Этот подход можно назвать неуклюжим и не очень «питоновским». Этот пример использует для открытия tar файла модуль tarfile, преимущество которого в том, что он позволяет Вам использовать атрибуты и методы Python при манипуляции с файлами. При помощи многих модулей Python, вы можете делать вещи, недоступные через командную строку.
Этой хороший пример использования меню в Python. Программа выполняет различные действия в зависимости от вашего выбора:

  • Если вы нажмете 1, программа предложит выбрать файл в архиве для извлечения в текущую директорию и затем извлечет файл.
  • Если вы нажмете 2, программа предложит выбрать файл и затем покажет информацию о нем.
  • Если вы нажмете 3, программа выведет список всех файлов в архиве.

Листинг 3. Выполнение операций с архивом tar при помощи меню

# -*- coding: utf-8 -*-
import tarfile, sys
try:
    #открываем tar-файл
    tar = tarfile.open(sys.argv[1], "r:tar")
    #выводим меню и сохраняем выбор
    selection = raw_input("Введите\n\
    1 чтобы извлечь файл\n\
    2 чтобы вывести информацию о файле в архиве\n\
    3 чтобы показать все файлы в архиве\n\n")
    #выполняем действия, основанные на выборе
    if selection == "1":
        filename = raw_input("введите имя файла для извлечения:  ")
        tar.extract(filename)
    elif selection == "2":
        filename = raw_input("введите имя файла для просмотра:  ")
        for tarinfo in tar:
            if tarinfo.name == filename:
                print "\n\
                Имя файла:\t\t", tarinfo.name, "\n\
                Размер:\t\t", tarinfo.size, "байт\n"
    elif selection == "3":
        print tar.list(verbose=True)
except:
    print "При выполнении программы возникла проблема!"

Программа следует по следующим этапам:

  1. Открывает tar файл (строка 5).
  2. Выводит на экран меню и получает выбор пользователя (строки 8-11).
  3. Если вы нажали 1 (строки 14-16), извлекает файл из архива.
  4. Если вы нажали 2 (строки 17-23), предоставляет информацию о выбранном файле.
  5. Если вы нажали 3 (строки 24-25), предоставляет информацию о всех файлах в архиве.

Результат работы программы показан в Листинге 4.

Листинг 4. Меню пользователя для второго примера

$ python example2.py jimstar.tar
Введите
    1 чтобы извлечь файл
    2 чтобы вывести информацию о файле в архиве
    3 чтобы показать все файлы в архиве

Пример 3. Проверка запущенного процесса и отображение информации в дружественном представлении.

Одной из важнейших обязанностей системного администратора является проверка запущенных процессов. Скрипт в Листинге 5 даст вам несколько идей. Программа использует преимущества возможностей Unix: команда grep использует вывод, генерированный другой командой. Это позволит вам уменьшить объем данных, которые в дальнейшем будет анализировать Python.
Программа так же использует модуль string. Изучите этот модуль — вы будете часто его использовать.

Листинг 5. Отображение информации о запущенном процессе в
дружественном представлении

# -*- coding: utf-8 -*-
import commands, os, string
program = raw_input("Введите имя программы для проверки: ")
try:
    #выполняем команду 'ps' и присваиваем результат списку
    output = commands.getoutput("ps -f|grep " + program)
    proginfo = string.split(output)
    #выводим результат
    print "\n\
    Путь:\t\t", proginfo[5], "\n\
    Владелец:\t\t\t", proginfo[0], "\n\
    ID процесса:\t\t", proginfo[1], "\n\
    ID родительского процесса:\t", proginfo[2], "\n\
    Время запуска:\t\t", proginfo[4]
except:
    print "При выполнении программы возникла проблема!"

Программа следует по следующим этапам:

  1. Получает имя процесса для проверки и присваивает его переменной (строка 3).
  2. Запускает команду ps и добавляет результат в список (строки 7-8).
  3. Выводит детальную информацию о процессе (строки 11-16).
  4. Результат работы программы показан в Листинге 6.

Листинг 6. Вывод третьего примера

$ python example3.py
Введите имя программы для проверки: xterm
    Путь:        pts/0
    Владелец:            goga
    ID процесса:        26509
    ID родительского процесса:    26493
    Время запуска:        17:28

Пример 4. Проверка имен пользователей и паролей на соблюдение политики безопасности.
Управление безопасностью важная часть работы для каждого системного администратора. Python делает эту работу проще, как показывает последний пример.
Программа в Листинге 7 использует модуль pwd для доступа к базе данных паролей. Она проверяет имена пользователей и пароли на соблюдение политики безопасности (в данном случае, имена должны быть как минимум 6 символов в длину, пароли — 8 символов).
Есть два предостережения:
Эта программа работает только если у вас есть полные права для доступа к /etc/passwd.
Если вы используете теневые пароли, скрипт работать не будет (однако, в Питон 2.5 есть модуль spwd, который решит эту проблему).


Листинг 7. Проверка имен пользователей и паролей на соблюдение политики безопасности

# -*- coding: utf-8 -*-
import pwd
#заводим счетчики
erroruser = []
errorpass = []
#получаем базу данных паролей
passwd_db = pwd.getpwall()
try:
    #проверяем каждое имя пользователя и пароль на валидность
    for entry in passwd_db:
        username = entry[0]
        password = entry [1]
        if len(username) < 6:
            erroruser.append(username)
        if len(password) < 8:
            errorpass.append(username)
    #выводим результаты на экран
    print "Следующие пользователи имеют имена менее чем из 6 символов:"
    for item in erroruser:
        print item
    print "\nСледующие пользователи имеют пароли менее чем из 8 символов:"
    for item in errorpass:
        print item
except:
    print "Возникла проблема при выполнении программы!"

Программа следует по следующим этапам:

  1. Инициализирует списки счетчиков (строки 4-5).
  2. Открывает базу данных паролей и записывает данные в список (строка 8).
  3. Проверяет имена пользователей и пароли на валидность (строки 12-18).
  4. Выводит имена и пароли, не соответствующие политике безопасности (строки 21-26).

Результат работы программы показан в Листинге 8.

Листинг 8. Вывод четвертого примера

$ python example4.py
Следующие пользователи имеют имена менее чем из 6 символов::
Guest
Следующие пользователи имеют пароли менее чем из 8 символов:
Guest
johnsmith
joewilson
suejones

Другое применение скриптов.
Вы можете использовать Python по ряду направлений для управления системой. Одна из лучших вещей, которую вы можете сделать — проанализировать свою работу, определить какие задачи вы выполняете неоднократно и изучить модули Python, которые помогут вам решить эти задачи — почти наверняка, таковые найдутся.
Некоторые области, где Python может быть отличным помощником:

  • Управление серверами: проверка патчей для конкретного приложения и их автоматическое обновление.
  • Журналирование: автоматическая отправка e-mail при появлении в логах особого вида ошибки.
  • Сеть: создание Telnet соединения к серверу и слежение за статусом соединения.

Тестирование web-приложений: использование свободно доступных инструментов для эмуляции веб-браузера и проверки веб-приложения на функциональность и производительность.
Это всего лишь несколько примеров — я уверен вы сможете добавить к ним свои собственные полезные идеи.

Резюме

С его легкостью в изучении, его умением управлять файлами, процессами, строками и числами, и его почти бесконечным массивом вспомогательных модулей, Python — это скриптовый язык, который выглядит так, будто был создан специально для системных администраторов. Python — это ценный инструмент в инструментарии любого системного администратора.

Python — этот универсальный швейцарский нож в мире IT! Казалось бы, еще вчера мы писали bash-скрипты, напоминающие древние заклинания, а сегодня — вуаля! — у нас есть язык, который даже начинающий админ может освоить быстрее, чем научиться правильно произносить «kubectl«.

сисадмин

Python ворвался в мир системного администрирования, словно супергерой в трико, готовый спасти нас от рутины и бесконечных повторяющихся задач. Его сила — в простоте (да-да, даже ваша бабушка сможет прочитать этот код) и гибкости (как йог, который может завязаться в крендель).

Хотите автоматизировать управление серверами? Пожалуйста! Нужно написать скрипт для массовой рассылки сообщений «Почему вы еще не обновили Windows?»? Легко! Python справится с этим быстрее, чем вы успеете сказать «асинхронность».

Но давайте без иллюзий — Python не сделает вашу работу за вас (мечты, мечты). Зато он превратит вас из замученного админа, погрязшего в рутине, в элегантного дирижера оркестра серверов и сетей. И, кто знает, может быть, у вас даже появится время на обед. Или сон. Выбирайте сами.

Ключевые инструменты Python для системных администраторов

Инструменты! Как говорил мой дедушка-столяр: «Хороший инструмент — половина работы». Правда, он никогда не имел дела с Python, но, поверьте, принцип тот же. Итак, дамы и господа, встречайте звездное трио, которое превратит вашу админскую жизнь из драмы в комедию (ну, или хотя бы в трагикомедию).

Fabric

Представьте, что вы — кукловод, а ваши серверы — марионетки. Fabric — это те самые ниточки, которые позволят вам управлять этим цифровым театром. С его помощью вы можете отдавать команды удаленным серверам, словно император своим легионам. «Установить! Обновить! Перезагрузить!» — и армия ваших серверов послушно выполняет приказы.

Fabric настолько упрощает жизнь, что вы можете управлять сотней серверов, сидя в пижаме и попивая какао. Правда, есть риск, что ваши коллеги забудут, как вы выглядите. Но кого это волнует, когда у вас есть такая сила?

Ansible

Если Fabric — это ниточки кукловода, то Ansible — это целый кукольный театр с автоматизированными декорациями. Этот инструмент позволяет не просто отдавать команды, а создавать целые сценарии управления инфраструктурой.

Хотите развернуть новый веб-сервер? Ansible сделает это быстрее, чем вы успеете сказать «деплой». Нужно обновить конфигурацию на всех машинах разом? Считайте, что это уже сделано. Ansible — это как если бы у вас был армия клонов, готовых выполнить любую задачу. Только без побочных эффектов из «Звездных войн».

psutil

А теперь встречайте — psutil, ваш личный шпион в мире системных ресурсов! Этот инструмент позволяет мониторить использование CPU, памяти, дисков и сети с точностью швейцарских часов.

С psutil вы будете знать о состоянии вашей системы больше, чем она сама о себе. Хотите узнать, какой процесс съедает всю память? psutil расскажет вам об этом во всех красочных подробностях. Это как иметь рентгеновское зрение, только для компьютеров.

А теперь, чтобы окончательно закрепить наши знания, давайте взглянем на эту таблицу использования наших цифровых супергероев:

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

Примеры использования Python в IT

Итак, дорогие мои кибер-ковбои и цифровые амазонки, давайте посмотрим, как Python может превратить вашу IT-жизнь из унылой пустыни в цветущий оазис эффективности. Или, по крайней мере, в место, где вы будете меньше биться головой о клавиатуру.

Управление серверами

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

Например, вы можете написать скрипт, который одним взмахом руки (ну, или нажатием клавиши) обновит конфигурацию на всех серверах. Или создать систему резервного копирования, которая будет работать с точностью швейцарских часов. «Но постойте!» — воскликнете вы. «Разве это не похоже на то, что делает Ansible?» Да, похоже. Но с Python у вас больше свободы для творчества. Это как сравнивать готовый торт из магазина и возможность испечь свой собственный. Иногда нужно именно ваше фирменное блюдо.

Мониторинг сети

А теперь представьте, что вы — Шерлок Холмс цифрового мира. Ваша задача — раскрыть тайны сетевого трафика. Python-библиотеки, такие как Scapy или PyShark, станут вашим верным Ватсоном.

С их помощью вы можете создать систему мониторинга, которая будет отслеживать сетевой трафик в режиме реального времени. Обнаружить подозрительную активность? Легко! Найти причину замедления сети? Элементарно! Вы сможете видеть каждый пакет данных, словно это письмо, летящее по почте. Только, в отличие от обычной почты, эти письма доходят до адресата за миллисекунды. И да, читать чужие письма в этом случае не только можно, но и нужно. Просто не увлекайтесь слишком сильно, окей?

Объем сетевого трафика за временные интервалы

Автоматизация развертывания ПО

Теперь давайте поговорим о том, как Python может превратить процесс развертывания ПО из кошмара в приятную прогулку. Ну, или хотя бы в менее страшный кошмар.

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

Вы можете написать Python-скрипты, которые будут автоматически проверять наличие обновлений, устанавливать их, а затем проводить тесты, чтобы убедиться, что все работает как надо. Это как иметь армию клонов, которые делают всю грязную работу за вас. Только эти клоны не взбунтуются и не попытаются захватить галактику. По крайней мере, я на это надеюсь.

Итак, дорогие мои, Python в IT — это как швейцарский нож для системного администратора. Только вместо открывалки для бутылок у вас есть инструменты для управления серверами, а вместо штопора — средства для мониторинга сети. И поверьте, в мире IT это гораздо полезнее. Хотя, конечно, иногда и штопор бы не помешал…

Преимущества Python перед традиционными инструментами

Традиционные инструменты. Они как старый добрый молоток: надежны, проверены временем, но, честно говоря, немного скучноваты. Python же — это как если бы ваш молоток внезапно научился говорить, летать и готовить кофе.

Давайте рассмотрим, почему Python заставляет других участников вечеринки автоматизации IT чувствовать себя неловко:

  • Простота: Python читается как книга. Правда, местами как «Улисс» Джойса, но всё же легче, чем Perl.
  • Универсальность: Python — как тот парень из старшей школы, который одновременно был капитаном футбольной команды, президентом шахматного клуба и звездой драмкружка. Он подходит практически для любой задачи.
  • Богатая экосистема библиотек: Представьте супермаркет, где вместо продуктов — готовые решения для ваших IT-задач. Это и есть мир Python-библиотек.
  • Кроссплатформенность: Python работает везде. Даже там, где вы не ожидаете его увидеть. Как тараканы, только полезнее.
  • Поддержка сообщества: Застряли с проблемой? Просто прокричите «Помогите!» в интернет, и армия Python-энтузиастов примчится на помощь. Ну, или хотя бы оставит саркастичный комментарий на Stack Overflow.
  • Интеграция с другими языками: Python дружит со всеми. Он как дипломат в мире программирования, только без костюма и с более понятным синтаксисом.

Сравнивая Python с другими скриптовыми языками, можно сказать, что если bash — это молоток, то Python — это целый набор инструментов с электроприводом. Perl может быть мощным, но его код иногда выглядит как результат падения кота на клавиатуру. PowerShell? Отличный выбор, если вы фанат Microsoft и любите печатать в три раза больше символов, чем нужно.

Python же — это золотая середина. Достаточно мощный для серьёзных задач, но при этом не заставляет вас чувствовать себя будто вы разгадываете древние руны каждый раз, когда пытаетесь прочитать свой собственный код, написанный неделю назад.

В конце концов, выбор языка для автоматизации IT — это как выбор инструмента для починки: важно не только то, насколько он эффективен, но и насколько комфортно вам с ним работать. И если с Python вы чувствуете себя как рыба в воде (или как системный администратор в серверной с кондиционером), то почему бы и нет?

Помните: в мире IT главное — это эффективность. И если Python позволяет вам решать задачи быстрее и с меньшим количеством седых волос, то это определенно ваш инструмент. Даже если он иногда ведет себя как капризный кот, который то ластится, то вдруг решает проигнорировать все ваши команды.

Практические примеры

Скрипт для передачи файлов с Fabric

Представьте, что вам нужно скопировать файл на 100 серверов. Звучит как сюжет для фильма ужасов, не так ли? Но с Fabric это скорее комедия. Вот вам пример кода, который заставит вас почувствовать себя властелином серверов:

from fabric import Connection, task

@task
def copy_file(c, source, dest):
    c.put(source, dest)
    print(f"Файл {source} успешно скопирован в {dest}")

@task
def mass_copy(source, dest):
    for host in ['server1', 'server2', 'server3']:  # Представьте, что здесь 100 серверов
    	conn = Connection(host)
    	copy_file(conn, source, dest)

# Использование: fab mass_copy source_file.txt /path/on/remote/server/

Что здесь происходит? Мы создаем две функции: copy_file для копирования одного файла и mass_copy для массового копирования. Fabric берет на себя всю грязную работу по SSH-подключению и передаче файлов.

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

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

А теперь давайте представим, что вы — доктор, а ваш сервер — пациент. psutil — это ваш стетоскоп, термометр и рентген в одном флаконе. Вот пример кода, который позволит вам провести полный медосмотр вашего сервера:

import psutil
import time

def monitor_resources():
    while True:
    	cpu_percent = psutil.cpu_percent(interval=1)
    	mem = psutil.virtual_memory()
    	disk = psutil.disk_usage('/')
   	 
    	print(f"CPU загружен на: {cpu_percent}%")
    	print(f"Памяти использовано: {mem.percent}%")
    	print(f"Диск заполнен на: {disk.percent}%")
    	print("-----------------------------")
   	 
    	time.sleep(5)  # Пауза 5 секунд перед следующим замером

if __name__ == "__main__":
    monitor_resources()

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

Представьте, как вы запускаете этот скрипт и наблюдаете за жизнью вашего сервера в режиме реального времени. Это почти как реалити-шоу, только без драм и скандалов (ну, если только ваш сервер внезапно не решит устроить кризис среднего возраста и не начнет потреблять всю доступную память).

С помощью этих примеров вы можете почувствовать себя настоящим волшебником IT-мира. Только вместо волшебной палочки у вас Python, а вместо заклинаний — скрипты. И, поверьте, это гораздо эффективнее в современном мире. Хотя, признаюсь, иногда хочется просто крикнуть «Алохомора!» и чтобы все серверы сразу обновились…

Лучшие практики использования Python в IT

Управление версиями

Версии Python — это как модели iPhone. Кажется, только вчера вы освоили Python 2, а уже нужно переходить на Python 3. И вот вы сидите, окруженный разными версиями, словно коллекционер винтажных автомобилей, не знающий, на чем сегодня поехать на работу.

Но не паникуйте! Вот вам золотое правило: используйте Python 3. Серьезно, Python 2 уже настолько устарел, что его впору выставлять в музее рядом с перфокартами и дискетами.

А теперь — барабанная дробь — встречайте звезду нашего шоу: виртуальные окружения! Это как если бы у вас была возможность создать параллельную вселенную для каждого вашего проекта. В одной вселенной у вас Python 3.7 с одним набором библиотек, в другой — Python 3.9 с совершенно другим набором. И эти вселенные никогда не пересекаются, словно параллельные прямые в геометрии Евклида.

Вот вам простой рецепт создания виртуального окружения:

python3 -m venv myenv
source myenv/bin/activate  # Для Linux/Mac
myenv\Scripts\activate.bat  # Для Windows

Теперь вы в своей собственной Python-вселенной. Устанавливайте любые пакеты, экспериментируйте — ваша основная система останется нетронутой, словно вы никогда и не покидали мир стабильности и предсказуемости.

Соображения по безопасности

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

Во-первых, никогда (и я повторю для тех, кто в танке — НИКОГДА) не храните пароли и ключи API прямо в коде. Это все равно что написать свой пин-код на банковской карте. Вместо этого используйте переменные окружения или специальные файлы конфигурации, которые не попадают в систему контроля версий.

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

В-третьих, регулярно обновляйте свои зависимости. Да, я знаю, это звучит скучно, но поверьте, лучше потратить час на обновление, чем неделю на устранение последствий взлома из-за известной уязвимости.

И наконец, используйте SSL для всех сетевых соединений. Незашифрованные данные в сети — это как кричать свои секреты на весь офис. Кто-то обязательно услышит, и вряд ли это будет тот, кому вы хотели их доверить.

Помните, безопасность в IT — это не паранойя, а здоровый образ жизни. Ведь лучше быть параноиком, чем потом объяснять начальству, почему все данные компании внезапно оказались на форуме хакеров.

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

Тестирование и линтинг

Помните: код без тестов — как машина без тормозов. Может быть, доедете, но лучше не рисковать. Используйте pytest для написания тестов — это не просто хорошая практика, это ваша страховка от неожиданных сюрпризов в продакшене. А автоматические тесты — это как автопилот: пока они работают, вы можете спокойно пить кофе. Линтеры (flake8, pylint) — это ваши цифровые корректоры. Они найдут опечатки и стилистические ошибки быстрее, чем вы успеете сказать «PEP 8». Настройте pre-commit хуки, чтобы код проверялся автоматически перед каждым коммитом — это как иметь персонального редактора, который никогда не спит. Что касается безопасности, всегда помните золотое правило: не доверяйте входным данным. Используйте bandit для поиска уязвимостей в коде, храните секреты в переменных окружения или vault-системах, а не в коде, и регулярно обновляйте зависимости через safety и pip-audit. Безопасность — это не пункт назначения, а постоянный процесс.

Конкретные области применения и перспективы

Python открывает перед системными администраторами следующие возможности:

Автоматизация рутинных задач

  • Массовое обновление конфигураций на серверах
  • Автоматическое развертывание приложений
  • Регулярное резервное копирование и ротация логов
  • Управление учетными записями пользователей
  • Мониторинг и очистка дискового пространства Мониторинг и анализ:
  • Создание систем оповещения о критических событиях
  • Сбор и анализ метрик производительности
  • Мониторинг сетевого трафика и выявление аномалий
  • Генерация отчетов о состоянии инфраструктуры
  • Визуализация данных через веб-интерфейсы

Сетевое администрирование

  • Автоматическая настройка сетевого оборудования
  • Управление DHCP и DNS записями
  • Мониторинг доступности сервисов
  • Анализ сетевых логов
  • Автоматизация настройки файрволов

Управление облачными ресурсами

  • Автоматическое масштабирование инфраструктуры
  • Управление контейнерами и оркестрация
  • Автоматизация создания и удаления ресурсов
  • Оптимизация расходов на облачные сервисы
  • Интеграция с API облачных провайдеров

Карьерные перспективы

  • DevOps инженер
  • SRE (Site Reliability Engineer)
  • Cloud Infrastructure Engineer
  • Automation Engineer
  • Platform Engineer

С этими навыками системный администратор может:

  • Сократить время на рутинные операции на 60-80%
  • Минимизировать человеческий фактор в критических операциях
  • Создавать масштабируемые решения для растущей инфраструктуры
  • Эффективно управлять гибридными и мультиоблачными средами
  • Участвовать в более сложных и интересных проектах

Освоение Python позволяет перейти от реактивного администрирования («тушения пожаров») к проактивному управлению инфраструктурой, где большинство процессов автоматизировано и требует минимального ручного вмешательства.

Заключение

Итак, дорогие мои кибер-воины и диджитал-ниндзя, мы с вами прошли путь от простого «Hello, World!» до властелинов серверов и укротителей сетей. Python в мире IT — это как швейцарский нож в кармане Джеймса Бонда: многофункциональный, надежный и, черт возьми, чертовски крутой.

Мы увидели, как Python может превратить рутинные задачи в увлекательное приключение (ну, или по крайней мере в менее мучительный процесс). С его помощью вы можете автоматизировать все, от простой отправки файлов до управления целой армией серверов. Это словно иметь персонального ассистента, который никогда не спит, не ест и не просит повышения зарплаты.

Но давайте будем честными: Python — не панацея. Он не сделает вашу кофемашину умнее (хотя, кто знает, может, кто-то уже работает над этим), и он точно не заменит вас на рабочем месте. По крайней мере, пока. Python — это инструмент, и как любой инструмент, он эффективен настолько, насколько умело вы им пользуетесь.

Помните о лучших практиках, держите свой код чистым (и я не про регулярное мытье клавиатуры), и не забывайте о безопасности. Потому что взломанный сервер — это как несварение желудка: неприятно, болезненно и может серьезно испортить ваш день.

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

Если вас вдохновила мощь и гибкость Python в мире IT, и вы готовы начать свое путешествие в мир автоматизации и системного администрирования, то самое время подумать об углубленном изучении этого языка. На странице курсов Python вы найдете подборку образовательных программ по различным направлениям — от основ языка до специализированных курсов по автоматизации IT-процессов. Выберите свой путь развития и начните превращать рутинные задачи в элегантные автоматизированные решения уже сегодня.

Так что, дорогие мои, берите Python, экспериментируйте, создавайте, автоматизируйте. Превратите свою IT-инфраструктуру в симфонический оркестр, где вы — главный дирижер, а Python — ваша волшебная палочка.

И помните: в мире IT единственное постоянное — это изменения. Но с Python в вашем арсенале вы всегда будете на шаг впереди. Или, по крайней мере, не на два шага позади.

А теперь идите и покорите этот цифровой мир! И да пребудет с вами сила… я имею в виду, Python.

Learn how Python tools for IT can make your IT admin life easier. Before you start get our IT Admin Tools runtime environment for Mac and Linux, or IT Admin Tools-Win for Windows, which come with a recent version of Python and all of the tools listed in this post.

Why would one need Python Tools for IT administration? In the age of DevOps, a greater emphasis has been placed on utilizing tools that provide the means to automate both simple and complex administrative tasks. In doing so, IT personnel are freed from the responsibility of manually performing time-consuming and repetitive tasks, such as server configuration or application deployment. This allows IT teams to focus more on complex challenges, process improvement and providing greater value to end users. With a reasonably small learning curve and high-level of readability, Python is a great language for teams looking to automate their workflows and processes.

Today, there exist a plethora of Python apps for automating administrative tasks. Below, I will discuss (in no particular order) 10 of the most useful and valuable Python tools that support IT administration.

Fabric

Built on top of Paramiko and Invoke, Fabric is a Python tool for interacting with remote servers via Secure Shell (SSH), and performing tasks on these servers. Popularly used for automating application deployments, Fabric is also a valid option for the execution of other system administration-related tasks (file transfer, configuring servers, etc.) that need to be performed on one or more remote nodes.

After installing Fabric, the System Administrator creates a file called fabfile.py. Within this file, functions are defined to execute tasks on remote servers. These functions can later be executed via the fab Command Line Interface (CLI).

Consider the (very) simple example below, where I create a data directory (/home/scott/data_dir) on my remote node, and copy a CSV file from my host machine to the remote machine using Fabric:

from fabric import Connection, task
@task
def remote_copy(c):
  c.run('mkdir -p /home/scott/data_dir')
  c.put('data.csv', '/home/scott/data_dir')

I can list the tasks defined in my fabfile via the command fab --list:

C:\Users\Scott\code>fab --list
Available commands:
remote_copy

Next, I can execute my remote_copy task, connecting to my remote machine (remotenode), and using the option to prompt for my password for use with SSH authentication:

C:\Users\Scott\code>fab -H scott@remotenode remote-copy --prompt-for-login-password
Enter login password for use with SSH auth:

After entering the password, the directory data_dir is created on remotenode, and the CSV file is copied over.

The latest versions of Fabric require Python 3.4+. It is free to use, and its functionality is well-documented, allowing any developer or system administrator to wrap their heads around Fabric’s capabilities in a timely manner.

psutil

Another Python package quite useful for IT Administration is psutil. Short for “process and system utilities,” psutil is a library that enables admins and developers to quickly gather information on running processes and system utilization. It is cross-platform, and is typically used for monitoring the state of systems or managing processes.

For instance, an admin may need to pull some CPU statistics and disk usage for the C drive on a machine they are tasked with monitoring, or else during issue troubleshooting. With psutil, this can be accomplished with short code snippet:

import psutil
cpu_stats = psutil.cpu_stats();
print(cpu_stats)
disk_usage = psutil.disk_usage('C:/')
print(disk_usage)
C:\Users\Scott\code>python stats.py
scpustats(ctx_switches=269517545, interrupts=220192269, soft_interrupts=0, syscalls=1196023326)
sdiskusage(total=484993335296, used=84763840512, free=400229494784, percent=17.5)

Click

Click is a Python package for use in creating CLIs quickly and efficiently. In today’s world, System Administrators are writing scripts with greater frequency. Click enables them to do so in a manner that allows them easy access to parameterized functions via the command line, streamlining the process for gathering information or executing commonly performed tasks.

Taking the psutil use case above, where a sysadmin pulled cpu stats and disk usage information, we can now create a script using Click that gives us more control over what’s being pulled by leveraging an argument named task.
If we provide all as the value for the task argument, we will pull both cpu stats and disk usage information. On the other hand, cpu will simply pull cpu stats and disk will only pull disk usage information.

import click
import psutil
@click.command()
@click.option('--task', default='all', help='all, cpu or disk')
def get_stats(task):
  click.echo('getting stats %s' % task)
  if (task == 'cpu' or task == 'all'):
    cpu_stats = psutil.cpu_stats();
    click.echo(cpu_stats)
  if (task == 'disk' or task == 'all'):
    disk_usage = psutil.disk_usage('C:/')
    click.echo(disk_usage)
if __name__ == '__main__':
  get_stats()

The output when executing get_stats to pull cpu stats and disk usage information should like something like:

C:\Users\Scott\code>python get_stats.py --task all
getting stats all
scpustats(ctx_switches=303841026, interrupts=247996435, soft_interrupts=0, syscalls=1305170163)
sdiskusage(total=484993335296, used=85040525312, free=399952809984, percent=17.5)

The output when utilizing the help option, to provide further detail on how to use the CLI we’ve created should look similar to:

C:\Users\Scott\code>python get_stats.py --help
Usage: get_stats.py [OPTIONS]
Options:
  --task TEXT  all, cpu or disk
  --help       Show this message and exit.

Salt

Salt is a Python tool for infrastructure management. Similar to Fabric, Salt allows for a host machine (master) to manage remote nodes (minions).

One particularly advantageous feature offered by Salt is the ability to utilize its event infrastructure to drive reactive processes that enable the implementation of things like intuitive scalability, or even a self-healing infrastructure. SaltStack’s very thorough documentation is kept up-to-date, providing all that’s needed for an IT administration team to begin the adoption of infrastructure-as-code techniques in a manner that can help automate traditionally manual sysadmin responsibilities.

To get started, just follow along with their brief but instructive tutorials on:

  • Remote configuration
  • Event-driven Infrastructure
  • Configuration Management

Selenium

Automation is the name of the game in DevOps, and Selenium helps organizations do just that with their browser-based web applications. Automated testing via Selenium helps organizations build confidence in their software releases.

While IT administrators may not be directly involved in writing Selenium test scripts, they’re invaluable in terms of time savings for developers and admin personnel alike, since they go a long way toward ensuring the quality of the software being deployed.

Learn more about Selenium.

Ansible

Ansible is an open-source Python tool used to automate a variety of critical IT tasks, including application deployment, configuration management, server provisioning, and more.

At a very high-level, Ansible works by promoting the development of playbooks (written in YAML), while IT administrators write “plays” that are defined by tasks. These tasks dictate the instructions to be executed on the remote hosts.

For example, the following is an Ansible playbook designed to streamline the process for setting up an Apache web server on one or more remote hosts:

---
- hosts: all
  become: true
  vars:
    vars/variables.yml
  tasks:
    - name: Update apt-cache
      apt: update_cache=yes
    - name: Install apache web server
      apt: name=apache2 state=latest
    - name: Create document root
      file: path={{ document_root_path }} state=directory owner=www-data group=www-data
    - name: Copy index.html
      copy: src=index.html dest={{ document_root_path }}/index.html owner=”{{ owner }}” mode=0644
    - name: Set up virtual hosts file
      template: src=virtualhosts.conf dest=/etc/apache2/sites-available/000-default.conf
      notify: Restart Apache
  
  handlers:
    - name: Restart Apache
      service: name=apache2 state=restarted

Requests

Perfectly defined in the Requests documentation, the Requests library allows the user to simply and elegantly send HTTP requests. From an IT administration perspective, this library can help construct and retrieve results for highly-readable HTTP requests in a timely manner, and provide additional insight into issues with a web server or application that an administrator may be tasked with troubleshooting.

For example, if a resource located at URL is misbehaving, the following snippet is a good place to start gathering information on the issue:

req = requests.get(‘<url>’)
print(req.status_code)

Boto3

For administrators working with Windows, pywin32 is an invaluable package which you need to be familiar with. This library provides admins with pythonic access to many functions within the Win32 API, as well as the ability to create and use COM objects. This can prove useful to sys admins looking to build useful Python utilities that need to interact with Windows-specific components.

The pywin32 package allows admins to perform a number of use cases that can make their lives easier. One such use case would be to write a Python program that reads Windows event logs and takes some action based on what they contain. Consider the script below, which simply opens the System event log, prints out the number or records contained, and then closes the log:

import win32evtlog
system_event_log=win32evtlog.OpenEventLog(None, "System")
count = win32evtlog.GetNumberOfEventLogRecords(system_event_log)
print(count)
win32evtlog.CloseEventLog(system_event_log)

Our output:

C:\Users\Scott\code>py check_system_event_log.py
15874

2to3

With Python 2.7 no longer being maintained, it’s very likely your organization has already moved your Python 2 applications to Python 3. But as a system administrator who writes the occasional Python script to help streamline their daily responsibilities, you may still have some scripts that need to be migrated, in which case 2to3 can be a big help.

2to3 is a library that takes your Python 2-compatible code and migrates it for use with Python 3. In many scenarios, this can save you the headache of having to research any incompatibilities between the two versions of Python, and/or trial-and-erroring your way to a working script. The syntax is simple:

2to3 -w my_script.py

Keep in mind that the -w flag tells 2to3 to make the changes directly in my_script.py. If that’s a concern, ensure you make a copy of the original script first.

Read: Python 2 To 3 Migration: A Developer’s Experience

Next Steps

The simplest way to get started making your IT admin life easier with this set of tools is to get our IT Admin Tools runtime environment for Mac and Linux, or IT Admin Tools-Win for Windows, which come with a recent version of Python and all of the tools listed in this post.

The easiest way to get the IT Admin Tools runtime is to first install our State Tool CLI, which will automatically download and install it into a virtual environment for you.

To install the State Tool on Windows, run the following in Powershell:

IEX(New-Object Net.WebClient).downloadString('https://platform.www.activestate.com/dl/cli/install.ps1')

Then type the following at a cmd prompt to automatically install the runtime into a virtual environment:

state activate Pizza-Team/IT-Admin-Tools-Win

To install the State Tool on Linux or Mac, just run the following command in your terminal:

sh <(curl -q https://platform.www.activestate.com/dl/cli/install.sh)

Then run the following to automatically download and install the runtime into a virtual environment:

state activate Pizza-Team/IT-Admin-Tools

To learn more about working with the State Tool, refer to the documentation.

Related Blogs:

Top 10 Tasks to Automate with Python

Top 10 Python Tools To Make a Developer’s Life Easier

Python3 for Systems Administrator

Contents


Getting Started Standard Input, Output and Error

Standard input, output and error (commonly referred to as stdin, stdout and stderr) are what’s called pipes.

These pipes are normally connected to the terminal window where you are working.

When printing something (using print()), it goes to the stdout pipe by default; when your program needs to print errors (like a traceback in Python), it goes to the stderr pipe; and when your program requires input from a user or other programs, it goes to the stdin pipe.

$ cat /etc/passwd | grep /bin/bash
#  `\_ writes to stdout        `\_ reads from stdin

$ ls no_such_file.txt
#  `\_ writes to stderr

Python built-in sys module provides stdin, stdout and stderr as a file-objects, exposing read(), readlines(), write(), writelines() methods, as shown below:

#!/usr/bin/env python3
import sys

# writing to stdout pipe
print ('Hello, world')
sys.stdout.write('Hello, world\n')

# writing to stderr pipe
print("Error occured")
sys.stderr.write("Error occured\n")

# reading single line from stdin pipe
sys.stdout.write('Username: ')
username  = sys.stdin.readline()
print (username)

# reading 'n' number of characters from stdin
print ('Enter few characters and press Ctrl-D')
data = sys.stdin.read(1024)
print('len(data):', len(data))

# reading lines (separated by newlines) from stdin
print('Enter few lines and press Ctrl-D')
lines = sys.stdin.readlines()
print ('total lines read:', len(lines))

Getting Started Working with files

Python built-in open function is the standard interface for working with files. open returns a file object with familiar methods for performing read/write operations.

Common arguments:

  • file: absolute or relative path of the file. e.g: /etc/passwd, ./ip-list.txt
  • mode: an optional string specifying mode in which the file is opened. Default’s to r for reading in text mode. Common values are:
  • w write only (truncates the file already exists)
  • x create and write to a new file (if file already exists then open fails)
  • a append to a file (insert data to end of the file)
  • + updating a file (reading and writing). e.g: r+ w+
  • b binary mode for non-text files. Contents are returned as byte objects.
  • t text mode (default). Contents are returned as strings.
File object methods:

  • .close()
  • .read(size=-1) read at most n characters. If n is negative or ommited, reads the whole file until EOF.
  • .readline() Read single line until newline or EOF.
  • .readlines() Read all newlines and returns as a list.
  • .write(data) Write data to file. Returns number of characters written.
  • .writelines(list) Write all data in the list. Useful for writing multiple lines to a file.
Example

## Reading a file
r = open('/etc/passwd')
# same as:
# r = open('/etc/passwd', 'r')
passwd = r.readlines()
for line in passwd:
	line = line.strip()
	size = len(line)
	print(size, line)
r.close()

## Reading a file using `with` statement, automatically closes the file
with open('/etc/passwd') as f:
	pass

## Writing to a file
w = open('test.txt', 'w')
w.write('127.0.0.1\n')
w.flush()
lines = ['1.1.1.1\n', '2.2.2.2\n', '3.3.3.3\n']
w.writelines(lines)
w.close()

Handling Errors

All open related errors raises IOError exception.

try:
	f = open('/etc/passwd')
except IOError as e:
	print ('Opps, something went wrong.')
	print (e)

Reading /etc/passwd and search each line for /bin/bash shell; when found print the line number and the line

#!/usr/bin/env python3
# working-with-files-01.py

def main():
	try:
		with open('/etc/passwd') as f:
			for no, line in enumerate(f, 1):
				if '/bin/bash' in line:
					line = line.strip()
					print(f'{no} {line}')
	except IOError as e:
		print(e)

if __name__ == '__main__': main()

Using fileinput High-level module

fileinput module allows to quickly write a loop over standard input or a list of files.

Example

#!/usr/bin/env python3
# linescount-02.py

import fileinput

lines = 0
for line in fileinput.input():
	lines += 1

print('totat lines:', lines)
$ cat /etc/passwd | python3 linescount.py
totat lines: 86
$ python3 linescount.py /etc/services
totat lines: 13921
$ python3 linescount.py /etc/services /etc/passwd /etc/hosts
totat lines: 14023

By default, fileinput.input() will read all lines from files given as an argument to the script; if no arguments given then defaults to standard input.


Getting Started Command-line Arguments

sys module provides argv variable containing the list of arguments passed to the script when executed as a command-line application.

NOTE: The first argument sys.argv[0] is always the name of the script itself.

#!/usr/bin/env python3
# argv_01.py

import sys

print ('sys.argv:', sys.argv)
print ('length:', len(argv))
$ python3 args_01.py --help
['argv-01.py', '--help']
2
$ python3 args_01.py 1 2 3
['argv-01.py', '1', '2', '3']
4

Accept specific number of arguments and fail if not satistified.

#!/usr/bin/env python3
# args-02.py
import sys

# NOTE: [1:] excludes the first item at index 0, i.e script name
argv_len = len(sys.argv[1:])

if not argv_len == 2:
	sys.exit(f'invalid number of arguments (expected 2, given: {argv_len})')

print('two arguments are:', sys.argv[1:])
$ python args_02.py
invalid number of arguments (expected 2, given: 0)
$ python args_02.py 1
invalid number of arguments (expected 2, given: 1)
$ python args_02.py 1 2  
two arguments are: ['1', '2']
$ python args_02.py 1 2 3
invalid number of arguments (expected 2, given: 3)

Simple Implementation of `grep’ command

#!/usr/bin/env python3
# grep.py

import sys

script = sys.argv[0]

def print_usage():
	sys.exit(f'Usage: python {script} pattern')

def main(argv):
	if not len(argv) == 1:
		print_usage()

	pattern = argv[0]

	for line in sys.stdin:
		if pattern in line:
			print(line.strip())

if __name__ == '__main__':
	main(sys.argv[1:])
$ cat /etc/services | python3 grep.py 8080
http-alt	8080/udp     # HTTP Alternate (see port 80)
http-alt	8080/tcp     # HTTP Alternate (see port 80)

Improvement Exercises

  • Extend grep.py to read from a file instead of standard input, and can be run as:
$ python3 grep.py 8080 /etc/services
  • Extend grep.py to read from a file if given as a second argument or default back to read from standard input similar to what grep does.
$ cat /etc/services | python3 grep.py 8080
# and also should works as
$ python3 grep.py 8080 /etc/services

Exploring Standard Modules Operating System (OS) Module

Python built-in os module exposes operating system dependent functionality in a portable way, thus works across many different platforms.

Working with environmental variables:

  • os.environ a dictionary mapping system environment variables. e.g. os.environ.get('SHELL')
  • os.getenv(key) retrieve a specific variable.
  • os.putenv(key, value). change variable to specific value. e.g. os.putenv('HOME', '/opt')
Working with files and directories:

  • os.tmpnam returns a unique file name that can be used to create temporariry file. mktemp() from tempfile module is more secure.
  • os.mkdir(path) os.rmdir(path) os.chdir(path) os.listdir(path)
  • os.getcwd() returns current working directory as string. Similar to pwd command.
  • os.stat(path) similar to stat command
  • os.walk(path) recursively walk the dictionary tree, similar to ls -R. Returns generator yielding 3-tuple (dirpath, dirnames, files)
Example

>>> import os

# environment variables
>>> os.environ['SHELL'] # or os.environ.get('SHELL') or os.getenv('SHELL')
'bash'

# Get a temporary filename using `tempfile` module
>>> from tempfile import mktemp
>>> temp = mktemp()
'/var/folders/6s/4xn2fv852_1ghssypng0wwfw0000gn/T/tmp15O9aR'

# Create the temporary file and write 'test'
>>> with open(temp, 'w') as f:
... 	f.write('test\n')

# Get the file stat, such as creation timestamp (ctime)
>>> st = os.stat(temp)
>>> st.st_ctime
1436466688.0

# convert timestamp to human readable format, we'll cover date & time later.
>>> import datetime
>>> d = datetime.datetime.fromtimestamp(st.st_ctime)
>>> d.year # d.month, d.hour and so on...
2016

Working with Path names os.path:

  • os.path.abspath(path) get absolute path.
  • os.path.basename(path) get the filename excluding the directory part. Opposite of os.path.dirname which excludes filename part and returns directory path.
  • os.path.exists(path) returns True if path exists else False.
  • os.path.getsize(path) return size (in bytes) for a given path.
  • os.path.isfile(path), os.path.isdir(path) returns True or False if path is file or a directory.
  • os.path.getctime(path), os.path.getmtime(path) Similar to os.stat(path).ctime, os.stat(path).mtime()

Learn more at os.path documentation

Example

>>> os.path.isdir('/etc')
True

>>> os.chdir('/etc')

>>> os.getcwd()
'/etc'

>>> os.path.abspath('hosts')
'/etc/hosts'

>>> os.path.isfile('/etc/hosts')
True

>>> os.path.getsize('/etc/hosts')
475

>>> print (os.path.basename('/etc/passwd'))
'passwd'

>>> print (os.path.dirname('/etc/passwd'))
'/etc'
Process related functions:

  • os.getpid() get id of current process and os.getppid()to get parent process id.
  • os.system(command) execute a command and returns exit code.
Getting System Informations:

  • os.uname() returns a 5-tuple (sysname, nodename, release, version, machine) identifying the current OS. Similar to uname -a command.
  • os.getloadavg() returns 3-tuple containing 1-min, 5-min and 15-min load average.

Print size (in bytes) of all files in a given directory

#!/usr/bin/env python3
# filesizes.py

import os
import sys

script = sys.argv[0]

def print_usage():
	print(f' >> {sys.stderr}, "Usage: python3 {script} DIR"')
	sys.exit(1)

def filesizes(path):
	''' calculate and print size of each file in a given directory. '''

	for dirpath, dirnames, filenames in os.walk(path):
		for filename in filenames:
			filepath = os.path.join(dirpath, filename)
			_bytes = os.path.getsize(filepath)
			print (f'{_bytes}, {filepath}')

def main(argv):
	if not len(argv) == 1:
		print_usage()

	path = argv[0]
	filesizes(path)

if __name__ == '__main__':
	main(sys.argv[1:])
$ python3 filesizes.py .
678 ./filesizes.py
```

Learn more about OS module


Exploring Standard Modules System-specific Module

Python built-in sys module exposes system-specific parameters and functions. This module provides access to some variables used or maintained by the interpreter and functions that interact strongly with the interpreter. sys module is always available.

Commonly used variables and functions:

  • sys.argv contains list of command-line arguments. Already covered.
  • sys.exit([arg]) exit the program. arg is optional, can be 0 to indicate success, > 0 for failure or string to display the errors during exit.
  • sys.version stores version of Python installed.
  • sys.stdin sys.stdout sys.stderr File objects corresponding to the interpreter’s standard input, output and error pipes.
  • sys.platform stored the name of the platofrm Python is running. Such as darwin for MacOS, linux for Linux and others
  • sys.path A list of strings that specified the search path while importing modules via import statement.
  • sys.modules A dictionary mapping the { 'module_name': 'module_path', ... } which have already been loaded.

#!/usr/bin/env python3
# sys-01.py

import sys
from sys import argv

print (f'''
Python version installed: {sys.version}

Python running on platforn: {sys.platform}
''')

if len(argv) == 10:
	sys.exit('error: too many arguments')

print(f'''
argv = {argv}
len(argv) = {len(argv)}
''')

print ('Printing to stdout')
print (f'>> {sys.stderr}, "Printing to stderr"')

print(f'''
total modules search path: {len(sys.path)}
total modules loaded: {len(sys.modules)}
''')

# success
sys.exit(0)
Output should look like this

$ python3 sys-01.py

Python version installed: 3.7.4 (default, Jul  9 2019, 16:48:28)
[GCC 8.3.1 20190223 (Red Hat 8.3.1-2)]

Python running on platforn: linux


argv = ['sys_01.py']
len(argv) = 1

Printing to stdout
>> <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>, "Printing to stderr"

total modules search path: 7
total modules loaded: 57


$ echo $?
0

Learn more about sys module


Exploring Standard Modules Shell Modules

shutil module — High-level file operations

The shutil module provides high-level operations on files or collection of files.

Copy Operations:

  • shutil.copy(src, dst) Copy src file to dst file or directory.
  • shutil.copymode(src, dst) Copy permission mode of src file to dst file.
  • shutil.copystat(src, dst) Copy permission mode, modification and creation date from src file to dst file.
  • shutil.copy2(src, dst) Similar to cp -p command or equivalent of shutil.copy and shutil.copystat.
Move Operations:

  • shutil.move(src, dst) Move src file to dst file or directory.

Learn more about shutil module


glob module — Unix style pathname pattern expansion

The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell.

  • glob.glob(pattern) Return a list of path names that match the path pattern. Path can be absolute /usr/local/bin/*.py or relative local/bin/*.py.
Example

>>> import glob
>>> glob.glob('/etc/sysconfig/network-scripts/ifcfg*')
['/etc/sysconfig/network-scripts/ifcfg-venet0',
 '/etc/sysconfig/network-scripts/ifcfg-lo']

>>> glob.glob('/etc/*.conf')
['/etc/vnstat.conf',
 '/etc/sudo.conf',
 '/etc/resolv.conf',
 '/etc/host.conf',
 '/etc/logrotate.conf']

Learn more about glob module


Exploring Standard Modules Date and Time Modules

time module — Clock time

The time module exposes the time-related functions from the underlying C library.

Commonly used functions:

  • time.time() returns the number of seconds since the start of the epoch as a floating-point value.
  • time.ctime() returns a human-friendly date and time representation.
  • time.gmtime() returns an object containing current time in UTC format.
  • time.localtime() returns an object containing the current time in current time zone.
  • time.tzset() sets the time zone based on TZ environment variable: os.environ.get('TZ')
Example

>>> import time
>>> time.time()
1459924583.396017

>>> # current time in UTC
>>> utc = time.gmtime()
>>> dir(utc)
['tm_hour',
 'tm_isdst',
 'tm_mday',
 'tm_min',
 'tm_mon',
 'tm_sec',
 'tm_wday',
 'tm_yday',
 'tm_year']

>>> # current time in GMT by updating timezone
>>> import os
>>> os.putenv('TZ', 'GMT') # or os.environ['TZ'] = 'GMT'
>>> time.tzset()
>>> gmt = '{} {}'.format(time.ctime(), time.tzname[0])

Learn more about time module


datetime module — Date and Time Value Manipulation

The datetime module includes functions and classes for doing date and time parsing, formatting, and arithmetic.

Commonly used functions:

  • datetime.date.today() returns current date object without the time
  • datetime.datetime.today() returns current date and time object
  • datetime.datetime.fromtimestamp(float) convert unix timestamp to datetime object
  • datetime.timedelta future and past dates can be calculated using basic arithmetic (+, -) on two datetime objects, or by combining a datetime with a timedelta object.
Example

>>> import datetime
>>> today_date = datetime.date.today()
>>> ten_days = datetime.timedelta(days=10)
>>> today_date - ten_days # past
>>> today_date + ten_days # future
Alternate formats can be generated using strftime() and strptime to convert formatted string to datetime object.

>>> import datetime

# convert datetime to custom format
>>>  format = "%a %b %d %H:%M:%S %Y"
>>> today = datetime.datetime.today()
>>> today.strftime(format)
'Mon Oct 14 17:56:24 2019'

# convert formatted string to datetime object
>>> datetime.datetime.strptime('Mon Oct 14 17:56:24 2019', format)
datetime.datetime(2019, 10, 14, 17, 56, 24)

Learn more about datetime module


Exploring Standard Modules Subprocess Module

subprocess module — Subprocess management

The subprocess module allows to run new processes, connect to their input/output/error pipes, and obtain their return codes.

The module defines a many helper functions and a class called Popen which allows to set up the new process so the parent can communicate with it via pipes.

Running external commands

To run an external command without interacting with, use subprocess.call(command, shell=True) function.

>>> import subprocess
>>> rc = subprocess.call('ls -l /etc', shell=True)
0
>>> rc = subprocess.call('ls -l no_such_file.txt', shell=True)
1

Setting the shell argument to a True value causes subprocess to spawn a shell process (normally bash), which then runs the command. Using a shell means that variables, glob patterns, and other special shell features in the command string are processed before the command is run.

>>> import subprocess
>>> subprocess.call('echo $PATH' )

# will return error
subprocess.call('echo $PATH', shell=True)
# will print the shell PATH variable value

Error Handling

The return value from subprocess.call() is the exit code of the program and is used to detect errors. The subprocess.check_call() function works like call(), except that the exit code is checked, and if it returns non-zero, then a subprocess.CalledProcessError exception is raised.

#!/usr/bin/env python3
# check_call.py

import sys
import subprocess

try:
	cmd = 'false'
	print ('running command:',cmd)
	subprocess.check_call(cmd, shell=True)
except subprocess.CalledProcessError as error:
	sys.exit(f'error: {error}')
$ python3 check_call.py
running command: false
error: Command 'false' returned non-zero exit status 1

Capturing Command Output

To run an external command and capture it’s output, use check_output(command, shell=True) to capture the output for later processing. If command returns non-zero, then a CalledProcessError exception is raised similar to check_call.

Execute cat /etc/hosts and write the output to a file hosts.txt

#!/usr/bin/env python3
# capture_output.py

import subprocess
import sys

try:
	cmd = 'cat /etc/hosts'
	print('running command:', cmd)
	output = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as error:
	sys.exit('error: {error}')
else:
	print('success!')
	with open('hosts.txt', 'w') as f:
		f.write(output)
		#this should give an error in python3.6+

By default, check_output captures outputs written to stdout. Setting the stderr=subprocess.STDOUT causes stderr outputs to redirected to stdout, so errors can be captured as well.


Working directory with Popen

The call(), check_call(), and check_output() are wrappers around the Popen class. Using Popen directly gives more control over how the command is run and how its input and output streams are processed.

One-Way Communication with a Process

To run a process and capture it’s output, set the stdout and stderr arguments to subprocess.PIPE and call communicate().

communicate() returns 2-tuple (stderr_output, stderr_putput)

#!/usr/bin/env python3
# one-way.py
import subprocess
import sys

script = sys.argv[0]

def main(argv):
	if not len(argv) == 1:
		sys.exit(f'usage: python3 {script} command')
	cmd = sys.argv[1]
	print ('running command:', cmd)
	proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
	stdout, stderr = proc.communicate()
	print(f'''
exit code: {proc.poll()}

stdout:
{stdout or None}

stderr:
{stderr or None}
''')

if __name__ == '__main__':
	main(sys.argv[1:])
$ python3 one_way.py ls
running command: ls

exit code: 0

stdout:
b'capture_output.py\ncheck_call.py\nhosts.txt\none_way.py\nsys_01.py\n'

stderr:
None

Bidirectional Communication with a Process

To set up the Popen instance for reading and writing at the same time, pass additional argument stdin=subprocess.PIPE.

#!/usr/bin/env python3
# bidirectional.py
import subprocess
from subprocess import PIPE
import sys

cmd = 'bc'
send = '1 + 1\n'

print('running command:', cmd, 'and sending input:', send)

proc = subprocess.Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = proc.communicate(send)

print(f'''
exit code: {proc.poll()}

stdin:
{send}

stdout:
{stdout or None}

stderr:
{stderr or None}
''')
$ python3 bidirectional.py
running command: bc and sending input: 1 + 1

exit code: 0

stdin:
1 + 1

stdout:
2

stderr:
None

Learn more about subprocess module

Exploring Argparse Command-Line Option and Argument Parsing

Python built-in argparse is parser for command-line options, arguments and subcommands. The argparse module provides argument management just like sys.argv, but with options, e.g it generates help and usage messages and issues errors when users give the program invalid arguments.
Let’s show the sort of functionality by making use of the ls command:

$ ls
examples  LICENSE  README.md
$ ls -l
total 44
drwxrwxr-x.  4 que que  4096 Oct 14 18:05 .
drwxrwxr-x. 24 que que  4096 Oct 13 15:32 ..
drwxrwxr-x.  2 que que  4096 Oct 14 18:48 examples
drwxrwxr-x.  8 que que  4096 Oct 15 01:01 .git
-rw-rw-r--.  1 que que  1210 Oct 13 15:32 LICENSE
-rw-rw-r--.  1 que que 24357 Oct 15 01:02 README.md
$ ls --help
Usage: ls [OPTION]... [FILE]...
List information about the FILEs (the current directory by default).
Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.
...

A few concepts we can learn from the four commands:

  • When you run the «ls -l» command with options, it will default displaying the contents of the current directory
  • The «-l» is knowns as an «optional argument»
  • If you want to display the help text of the ls command, you would type «ls —help»

To start using the argparse module, we first have to import it.

Intro to positional arguments

The following code is a Python program that takes a list of integers and produces either the sum or the max:

Example

#!/usr/bin/env python3
#app.py
import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))

Assuming the Python code above is saved into a file called app.py, it can be run at the command line and provides useful help messages

$ app.py -h
usage: prog.py [-h] [--sum] N [N ...]

Process some integers.

positional arguments:
 N           an integer for the accumulator

optional arguments:
 -h, --help  show this help message and exit
 --sum       sum the integers (default: find the max)

$ app.py 1 2 3 4
4

$ app.py 1 2 3 4 --sum
10

Creating a parser

The first step in using the argparse is creating an ArgumentParser object:

>>> parser = argparse.ArgumentParser(description='Process some integers.')

The ArgumentParser object will hold all the information necessary to parse the command line into python data types.

Adding arguments

Filling anArgumentParser with information about program arguments is done by making calls to the ArgumentParser.add_argument method. Generally, these calls tell the ArgumentParser how to take the strings on the command line and turn them into objects. This information is stored and used when ArgumentParser.parse_args is called. For example:

>>> parser.add_argument('integers', metavar='N', type=int, nargs='+',
...                     help='an integer for the accumulator')
>>> parser.add_argument('--sum', dest='accumulate', action='store_const',
...                     const=sum, default=max,
...                     help='sum the integers (default: find the max)')

Later, calling parse_args will return an object with two attributes, integers and accumulate. The integers attribute will be a list of one or more ints, and the accumulate attribute will be either the sum function, if —sum was specified at the command line, or the max function if it was not.

Parsing arguments

ArgumentParser parses args through the ArgumentParser.parse_args method. This will inspect the command-line, convert each arg to the appropriate type and then invoke the appropriate action. In most cases, this means a simple namespace object will be built up from attributes parsed out of the command-line:

>>> parser.parse_args(['--sum', '7', '-1', '42'])
Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])

In a script,ArgumentParser.parse_args will typically be called with no arguments, and the ArgumentParser will automatically determine the command-line args from sys.argv.

ArgumentParser objects

Create a new ArgumentParser object. Each parameter has its own more detailed description below, but in short they are:

  • description — Text to display before the argument help.
  • epilog — Text to display after the argument help.
  • add_help — Add a -h/—help option to the parser. (default: True)
  • argument_default — Set the global default value for arguments. (default: None)
  • parents — A list of ArgumentParser objects whose arguments should also be included.
  • prefix_chars — The set of characters that prefix optional arguments. (default: ‘-‘)
  • fromfile_prefix_chars — The set of characters that prefix files from which additional arguments should be read. (default: None)
  • formatter_class — A class for customizing the help output.
  • conflict_handler — Usually unnecessary, defines strategy for resolving conflicting optionals.
  • prog — The name of the program (default:sys.argv[0])
  • usage — The string describing the program usage (default: generated)

Learn more about argparse module

Exploring SQLite Module exploring-standard-modules-embedded-relational-database-module

SQLite is a C-language library that implements a SQL like database engine which is relatively quick, serverless and self-contained, high-reliable. SQLite comes built-in with most of the moden software, hardware devices and browsers, thus Python also has embedded SQLite engine named sqlite3.

To Start using the sqlite3 library:

Commonly used functions:

  • sqlite3.connect() — A connection object is created using the connect() function e.g connection = sqlite.connect(‘name_of_file_db.db’)
  • connection.cursor() — To execute SQLite statements, cursor object is needed. You can create it using the cursor() method. e.g cursor_object = connection.cursor()
  • connection.execute() — To create a table in SQLite3, you can use the Create Table, Insert Into Table, Update Table, or Select query with the execute() method of SQLite library. For example cursor_object.execute(«CREATE TABLE employees()»); connection.commit()
  • connection.commit() — The commit() method saves all the changes we make.
  • cursor_object.fetchall() — To fetch the data from a database we will execute the SELECT statement and then will use the fetchall() method of the cursor object to store the values into a variable, e.g cursor_object.execute(‘SELECT * FROM employees’) ; rows = cursor_object.fetchall()
  • cursor_object.rowcount() — The SQLite3 rowcount is used to return the number of rows that are affected or selected by the latest executed SQL query
  • cursor_object.executemany() — It can use the executemany statement to insert multiple rows at once.
  • connection.close() — You are done with your database, it is a good practice to close the connection with close() method. e.g. connection.close()

Learn More about SQLite3 Module

Exploring XmlTree Module exploring-xmltree-module

Learn More about XmlTree Module

Exploring JSON Module exploring-json-module

JSON is text, written with JavaScript object notation. JSON is a syntax for storing and exchanging data.
It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page
and vice versa

  • json.loads()

  • take a file object and returns the json object. A JSON object contains data in the form of key/value pair. The keys are strings and the values are the JSON types

  • json.dumps()
    -json.dumps() function converts a Python object into a json string
    .It is the exact opposite of json.loads.

THIS IS THE ENCODING DECODING LIST

JSON -Python

1)object- DICT
2)array — list
3)string — str
4)int — int
5)real — float
6)true — true
7)False — False
8)NULL — NONE

  • Encoding is from python to JSON(final type)

json.JSONEncoder().encode({«foo»: [«bar», «baz»]})
‘{«foo»: [«bar», «baz»]}’

  • Decoding is from JSON to python(final type)

Encoding functions

  • iterencode(o)
    -Encode the given object, o, and yield each string representation as available. For example:

for chunk in json.JSONEncoder().iterencode(bigobject):
mysocket.write(chunk)]

-sort-keys -Sort the output of dictionaries alphabetically by key.

-h, --help¶— help box

infile-to check your Json file for syntax

outfile-Write the output of the infile to the given outfile

Note

If the optional infile and outfile arguments are not specified, sys.stdin and sys.stdout will be used respectively:

json.tool — to validate and pretty-print JSON objects.

raw_decode— This can be used to decode a JSON document from a string that may have extraneous data at the end.

Learn More about JSON Module

Exploring CSV Module exploring-csv-module

CSV — comma-separated values file is a text file with it’s content delimited by comma (most often but any other delimiter is acceptable, yet it is advised to stick to the standards) defined by RFC 4180.
These files are really useful when it comes to share, read and save data. Structure of such file is very simple:

header1,header2,header3
datacell11,datacell12,datacell13
datacell21,datacell22,datacell23
datacell31,datacell32,datacell33

You can easily read and write CSV files with Python using csv module. To open CSV file we need code like this:

import csv
with open('file.csv') as f:
    f_csv = csv.reader(f, delimiter=',', quotechar='"')
    headers = next(f_csv)   # this line uses next() function to save first row of the file and skip it. Rest is our data.
    # now we are ready to process our rows. Example:
    for row in f_csv:
        print(row[0], row[1], row[2])

Script would just print data like this:

$> datacell11 datacell12 datacell13
$> datacell21 datacell22 datacell23
$> datacell31 datacell32 datacell33

Here’s explanation for some parameters of csv.reader:

delimiter — is as it name shows — character or set of them that determines where are columns of value and how they are separated

quotechar — is a char starting and ending a quote in our CSV file. It prevents our script from breaking output when we would have somethin like: datacell21,"datacell22",datacell23

If the file is more complicated than this (and it probably will) it is advised to use DictReader. It would look like this:

import csv
with open('file.csv') as f:
    f_csv = csv.DictReader(f, delimiter=',', quotechar='"')
    headers = next(f_csv)   # this line uses next() function to save first row of the file and skip it. Rest is our data.
    # now we are ready to process our rows. Example:
    for row in f_csv:
        print(row['header1'], row['header2'], row['header3'])

Instead of column indexes it is possible to use their names from header.

To write file we can simply do this:

import csv
data = [
    ['data1', 'data2', 'data3'],
    ['data4', 'data5', 'data6']
    # ...
]
with open('newfile.csv', 'w') as nf:
    headers = ['header_1', 'header_2', 'header_3']
    csv_writer = csv.writer(nf)
    csv_writer.writerow(headers)
    csv_writer.writerows(data)

We use writerow for writing header for our data and then writerows to simply handle a few(hundred) rows of data

Alternatively we DictWriter can be used:

import csv

data = [
    {'header_1': 'data1', 'header_2': 'data2', 'header_3': 'data3'},
    {'header_1': 'data4', 'header_2': 'data5', 'header_3': 'data6'},
    {'header_1': 'data7', 'header_2': 'data8', 'header_3': 'data9'}
]
with open('countries.csv', 'w', encoding='UTF8', newline='') as f:
    headers = ['header_1', 'header_2', 'header_3']
    writer = csv.DictWriter(f, fieldnames=headers)
    writer.writeheader()
    writer.writerows(data)

Learn More about CSV Module

Tired of managing Windows system administration tasks manually? Wish you could set up a few Python scripts instead? Where there’s a will, there’s a way! In this article, we’ll show you how to install Python’s WMI module and how you can use it to perform
system administration processes.

Windows Management Instrumentation (WMI) is Microsoft’s implementation to the DMTF’s Common Information Model (CIM) which
is a vendor-neutral, industry standard way of representing management information. It allows you to query almost any piece of information from any computer which is running the necessary agent with the right permissions.

Python has module named: ‘wmi’ which is light weight wrapper around available WMI classes and functionalities and could be used by systems administrators
to query information from local or remote Windows machines.

Installing the Module

Before you can install the Python module, we require ‘pip’ which is package management framework required to install the modules from
trusted public repositories, once you have ‘pip’ you can install the module using following command from a Windows command prompt (CMD).

python.exe -m pip install wmi

Establishing a Connection

After installing the module, we will try to establish a connection to a machine. Most of the time we will connect to our local machine, using the following code sample in Python:

# connecting to local machine
conn = wmi.WMI()

If you want to connect to a remote machine, then you have to provide a machine name/IP Address, and use named parameters ‘user’ and ‘password’ to pass your credentials, so that your account can be authenticated to establish a remote WMI connection.

# connecting to remote machines
import wmi
conn = wmi.WMI("13.76.128.231", user=r"prateek", password="P@ssw0rd@123")

Finding a WMI Class

Now we have the connection established, but in order to query specific system information, we have to first find out the WMI class that can provide that information. In order to achieve that we utilize the ‘classes’ property of WMI object like wmi.WMI().classes,
which will return the list of WMI classes.

You can filter out specific keywords from these to find the exact class you are looking for, like in the following example.

import wmi

conn = wmi.WMI()

for class_name in conn.classes:

    if 'Process' in class_name:

        print(class_name)

prateek-wmi-sysadmin-python-1

Finding Properties and Methods of WMI Class

Even if you know the name of WMI Class, you will still require the exact name of the property these classes offer and methods that can perform specific operations. In order to get properties and methods of as specific WMI class, create a WMI connection
and use the ( ‘.’ ) Dot operator and ‘Class Name’ to access WMI namespace, then ‘methods’ or ‘properties’ attribute to return a Python List of property/method names.

import wmi
# prints all properties
wmi.WMI().Win32_Process.methods.keys()

# prints all methods
wmi.WMI().Win32_Process.properties.keys()

python-wmi-sysadmins1

Handling Process

Now we know the properties and methods of class ‘Win32_Process’, so we will use the WMI class name followed by an open & close parenthesis to return objects of the WMI class, like in the following example:

# list processes
import wmi
conn = wmi.WMI()
for process in conn.Win32_Process():
print("ID: {0}\nHandleCount: {1}\nProcessName: {2}\n".format(
process.ProcessId, process.HandleCount, process.Name
)
)

python-wmi-sysadmins

You can even filter processes with name and properties to print only selected process(es), like in the following example we selected all ‘Chrome.exe’ processes running locally and then filtered out the processes that have handle count more than 1000 using
a conditional statement: if

# filtering specific processes
import wmi
conn = wmi.WMI()
for process in conn.Win32_Process(name="chrome.exe"):
if process.HandleCount > 1000: # only processes with handle count above 1000
print(process.ProcessID, process.HandleCount, process.Name)

python-wmi-sysadmin2

WMI Module also allows to start new process and kill any existing one, like in the following code sample we created a new notepad process then stored the Process ID to uniquely identify the process, so that it can be terminated later using the id.

# start a new process and capture the process id
import wmi
conn = wmi.WMI()
pid, returnval= conn.Win32_Process.Create(CommandLine="notepad.exe")

# kill the process using process id
conn.Win32_Process(ProcessId=pid)[0].Terminate()

python-wmi-sysadmin3

Handling Services

 In a similar approach we can also list and filter out services running on a machine using WMI class: ‘Win32_Service’

# list services
import wmi
conn = wmi.WMI()
for s in conn.Win32_Service(StartMode="Auto", State="Running"):
# filter service names
if 'Update' in s.Name:
print(s.State, s.StartMode, s.Name, s.DisplayName)

python-wmi-sysadmin4

And even perform start and stop operations on target service(s), like in the following example we first filtered out all Windows services that are stopped and in startup mode ‘Automatic’, then use the ‘StartService()’ method to start the window service.
In case you want to stop the service you can use the ‘StopService()’ method.

# start target service
import wmi
conn = wmi.WMI()
for s in conn.Win32_Service(StartMode="Auto", State="Stopped"):
if 'Update' in s.Name:
result, = s.StartService()
if result == 0:
print("Successfully started service:", s.Name)

python-wmi-sysadmin5

Get Disk Space

You can also use WMI Class: Win32_LogicalDisk to get the free space on each logical disk attached to the system.

import wmi
conn = wmi.WMI ()
for disk in conn.Win32_LogicalDisk():
if disk.size != None:
print(disk.Caption, "is {0:.2f}% free".format(
100*float(disk.FreeSpace)/float(disk.Size))
)

python-wmi-sysadmin6

Get Local Users and Groups

System administrators can also use WMI module to list local users and groups, in the following example we are using Associators, which are classes which links two classes together like: Win32_Group and Win32_UserAccount

import wmi
conn = wmi.WMI()
for group in conn.Win32_Group():
print(group.Caption)
for user in group.associators(wmi_result_class="Win32_UserAccount"):
print(" [+]", user.Caption)

python-wmi-sysadmins8

In this article we’ve covered how to install Python’s ‘wmi’ module, how to create a connection to a local or remote machine to retrieve system information like processes, service, disks and user/group using WMI classes, and even how to perform system
administration tasks like starting/stopping targeted services and processes.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Код ошибки 0xc0000001 при загрузке компьютера windows 10 x64
  • Как починить загрузку windows 7
  • Путь сбойного модуля c windows syswow64 kernelbase dll
  • Как открыть файл iso на windows 10 без программ
  • Supportedos id windows 10