Windows powershell with python

Мониторинг сервисов Windows средствами PowerShell и Python


Предыстория:
Сам я работаю в техотделе одной брокерской компании в Торонто, Канаде. Так же у нас есть еще один офис в Калгари. Как-то после планового установления Windows обновлений на единственном доменном контроллере в удаленном офисе не запустился W32Time сервис, который отвечает за синхронизацию времени с внешним источником. Таким образом в течение около недели время на сервере сбилось приблизительно на 20 секунд. Наши рабочие станции на тот момент времени по умолчанию получали время с контроллера. Сами понимаете, что случилось. В торгах время очень важно, разница в секунды может решить многое. Первыми расхождение во времени, к сожалению, заметили наши брокеры. Наш отдел техподдержки, состоящий по сути из 3 человек за это распекли. Надо было срочно что-то делать. Решением было применение групповой политики, которая отсылала все машины к внутреннему NTP серверу, работающему на CentOS. Еще были проблемы с DC Barracuda Agent, сервисом, отвечающим за соединение контроллеров домена с нашим Веб фильтром, и еще парочка сервисов причиняла нам порой беспокойство. Тем не менее решили что-то придумать, чтобы следить за пару сервисами. Я немного погуглил и понял, что есть много решений, в основном коммерчиских для данной проблемы, но так как я хотел научиться какому-нибудь скриптовому языку, то вызвался написать скрипт на Питоне с помощью нашего местного линукс-гуру. В последствие это переросло в скрипт, который проверяет все сервисы, сравнивая их наличие и состояние со списком желаемых сервисов, которые к сожалению надо делать вручную отдельно для каждой машины.

Решение:

На одном из Windows серверов я создал PowerShell скрипт такого вида:

В моем случае таких кусков получилось 10 для каждого сервера

В Task Scheduler добавил следующий батник (мне это показлось легче, чем пытаться запусить оттуда PowerShell скрипт напрямую):

Теперь каждый день я получал список со всеми сервисами в отдельном файле для каждого сервера в подобном формате:

Теперь самая главная часть. На отдельной машине с CentOS на борту я написал сей скрипт:

Файлы дампов и списков с желаемыми сервисами должны иметь одинаковые имена. Список с сервисами, за которыми мы следим (desiredServices) должен быть вот такого вида:

Скрипт будет проверять сервисы, а потом компоновать все это в одно email сообщение, которое в зависимости от результата будет говорить, что все в порядке в теме сообщения или, что есть ошибки, а в теле сообщения раскрывать, какие это ошибки. Для нас одной проверки в день достаточно, поэтому ранним утром мы получаем уведомление о состоянии наших Windows серверов. Чтобы скопировать файлы с Windows сервера на машину с линуксом, мой коллега помог мне со следующим баш скриптом:

Этот скрипт так же меняет кодировку, ибо на моей машине Linux не очень хотел работать с UTF16. Далее, чтобы отчищать папку от дампов с сервисами я добавил батник в Task Scheduler чтобы запускать PowerShell скрипт, который стирает дампы.
Батник:

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

Читайте также:  Kali linux обзор возможностей

I’m trying to use python in powershell

I’m trying to follow Zed Shaw’s guide for Learning Python the Hard Way. I need to use python in Powershell. I have Python 2.7.3 installed in C:\Python27 . Whenever I type python into Powershell, I get an error that says the term ‘python’ is not recognized as the name of a cmdlet, function, script file, or operable program. I also typed in this: [Environment]::SetEnvironmentVariable(«Path», «$env:Path;C:\Python27», «User») That was a suggested solution provided, but typing python into Powershell still does nothing. I can type in «start python» and it opens up a window with python but I need it in Powershell. Thanks.

13 Answers 13

Try setting the path this way:

For what’s worth, this command did it for me (Python3.3) :

I just had to restart the Powershell after that.

$env:path=»$env:Path;C:\Python27″ will only set it for the current session. Next time you open Powershell, you will have to do the same thing again.

The [Environment]::SetEnvironmentVariable() is the right way, and it would have set your PATH environment variable permanently. You just have to start Powershell again to see the effect in this case.

The Directory is not set correctly so Please follow these steps.

  1. «MyComputer»>Right Click>Properties>»System Properties»>»Advanced» tab
  2. «Environment Variables»>»Path»>»Edit»

In the «Variable value» box, Make sure you see following:

Click «OK», Test this change by restarting your windows powershell. Type

Now python version 2 runs! yay!

For a permanent solution I found the following worked:

This works for me permanently:

From the Python Guide, this is what worked for me (Python 2.7.9): [Environment]::SetEnvironmentVariable(«Path», «$env:Path;C:\Python27\;C:\Python27\Scripts\», «User»)

Sometimes you install Python on Windows and it doesn’t configure the path correctly.

Make sure you enter [Environment]::SetEnvironmentVariable(«Path», «$env:Path;C:\Python27», «User»)
in PowerShell to configure it correctly.

You also have to either restart PowerShell or your whole computer to get it to really be fixed.

Try the Command this way:

Just a note to anyone landing here from google, the answers setting path are all correct, but this problem probably stems from not giving the python installer administrative rights it needs to set the path itself. An alternative may be to simply right click the installer and select run as administrator, then repair the installation. If that still doesn’t work, choose the [Environment] answer below that corresponds to your python version and installation directory. – MaxPRafferty Nov 18 ’15 at 20:06

Maybe it is wise to let Python installer to add the path itself. The trap here is that by default Python installer does NOT add path for you. You should look carefully (by scrolling down to see what has been installed) during the installation process instead of directly next ing to the end.

What he missed saying is that you cannot run as administrator once you have installed it. Uninstall and reinstall may do, but the simplest is to right click and Troubleshoot compatibility , being careful this time to check the ‘add path’ in the «what to install» dialog before hiting next . Then restart powershell. Voilà. It works for me.

virtualenv in PowerShell?

Hi fellow pythonistas, there seems to be a problem when virtualenv is used in PowerShell.

When I try to activate my environment in PowerShell like..

.. nothing happens. (the shell prompt should have changed as well as the PATH env. variable .)

I guess the problem is that PowerShell spawns a new cmd. process just for running the activate.bat thus rendering the changes activate.bat does to the shell dead after it completes.

Do you have any workarounds for the issue? (I’m sticking with cmd.exe for now)

14 Answers 14

Update: The answer below is out of date. Now, just use activate.ps1 (rather than activate.bat ) to activate from a Powershell environment.

Here’s a post which contains a Powershell script which allows you to run batch files that persistently modify their environment variables. The script propagates any environment variable changes back to the calling PowerShell environment.

The latest version of virtualenv supports PowerShell out-of-the-box.

Just make sure you run:

The latter will execute activate.bat , which doesn’t work on PowerShell.

A quick work-around would be to invoke cmd and then run your activate.bat from within the cmd session. For example:

Inside of the Scripts directory of your virtual environments folder there are several activation scripts that can be used depending on where you are executing the command. If you are trying to activate your virtual env from the Windows PowerShell, try using the following command:

In the event you receive an error about the activation script being disabled on your system, you will first need to invoke an execution policy change on your system. This will need to be done as the administrator.

To do this:

1) Right click on the PowerShell application and select Run as Administrator

2) Run the following command: Set-ExecutionPolicy Unrestricted

3) Rerun the activation command: . .\env\Scripts\activate.ps1

try this: . .\env\Scripts\activate.ps1 watch dots and spaces

This error happens due to a security measure which won’t let scripts be executed on your system without you having approved of it. You can do so by opening up a powershell with administrative rights (search for powershell in the main menu and select Run as administrator from the context menu) and entering:

Windows users

  1. Run Powershell as an administrator
  2. copy and paste this command: set-executionpolicy remotesigned
  3. Agree to the message.

I wrote this quick little script to handle my activation and startup of a dev server.

On Windows PowerShell, I have to type from the venv/Scripts folder :

I had that problem too! and finally found out what should we do in windows.

ok, follow these steps:

1)Type powershell in search bar of windows then right click on it and select Run as Administrator

(if you have problem in that check this)

2) Run the following command in powershell: Set-ExecutionPolicy Unrestricted

3) Rerun the activation command: .\\env\Scripts\activate.ps1

(just run the exact command! be careful about name of your environment.)

I wrote a little script to activate it.

Remember to save file with PowerShell extension .ps1 .

Just 2 more suggestions:

Because it is always problematic to weaken a security policy i would advice to do it the minimal way for Powershell: invoke Powershell not as administrator but as the user who wants to use the virtualenv functions. Type «set-executionpolicy -executionpolicy unrestricted -scope currentuser». This way the policy is changed only for one user and not for the whole machine.

Secondly I would advice to download from github the sources «regisf/virtualenvwrapper-powershell». After download unpack the zip-file to a local directory and run the file «Install.ps1» inside. This will expand the Powershell profile permanently on your machine and hence enable the use of all «virtalenvwrapper-win» commands including «workon». After that you will not notice any difference in the behaviour of Powershell and the Commandshell concerning virtualenv.

Windows Power shell is consider powerful and «turbo-charged» than the normal command prompt shell. In an instance you are using visual studio code (VScode), running power shell to launch Python Virtual Environment may throw error especially on windows 10, as shown below.

\Activate : File C:\users\titus\django1\Scripts\Activate.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:1

To solve this, you can do the following:

  1. Go to windows Setting
  2. Open update & Security
  3. Select «For Developers»
  4. Enable the developers mode
  5. accept all the terms

Install Python on Windows with Powershell without administrator privileges

Created: June 26, 2018 | Updated: December 30, 2019 | 4 minute read

As a Windows DevOps, I often use Powershell and Python, Powershell is installed by Windows out of box, but this is not for Python. And for my working environment, I don’t have the administrator privileges on some servers. I will show you in this post how to rapidly deploy Python on Windows as a standard user by using Powershell with Nuget.

Update 2019-12-30 Installing Python by Scoop

Installing Python on Windows by Scoop is the simplest way so far if you have Internet access.

To switch between different Python versions, please check this doc.

Finding Python packages

If you cannot use Find-Package to search pacakges in Nuget repository, please check my post on Setting Up Nuget for Powershell.

We will install python with version 3.6.5 and python2 with version 2.7.15.

Installing Python

Note 2018-08-29: Current Find-Package python* -AllVersion gives the lastest python version is v3.7.0 , but this version doesn’t work, the last worked Nuget python version is v3.6.6

Adding Python to user path

I will show you the way to add Python3 into the user PATH, it will be the same way for Python2. I use the user PATH because I’m not admin on the Windows server, I cannot modify the system PATH.

Reinstalling pip

The default pip3.exe and pip2.exe have some strange behavior that just don’t work :

You can bypass the issue by using python -m pip , but I like to use pip directly without python -m , the trick is just reinstalling the pip:

Normally python -m ensurepip will install pip v9, if you want to install pip v10, just upgrade the v9:

And we can find that when installing pip v10, the pip.exe is installed too, while in pip v9, we only have pip3.exe.

Update on 2018-07-27: The pip version has been jumped from v10 to v18 directly, because PyPA switches the software versioning to CalVer

Configuring pip for PyPI

If you’re in enterprise environment, you may probably dont have access to the public Python packages repository https://pypi.org/, and in this case, your enterprise should have a local Artifactory which mirrors the public https://pypi.org/. So you need to add your enterprise Artifactory PyPI URL to you Python pip conf.

You can find all the pip configuration details here.

Читайте также:  Microsoft windows security scanner
Оцените статью