Удаленный запуск в PyCharm Community Edition
PyCharm — самая удобная, на мой взгляд, IDE для Python’a от авторов великолепного PhpStorm. В отличие от средства разработки на PHP, имеет бесплатную версию с несколько урезанным функционалом, в частности без шикарного модуля для запуска и отладки скриптов на удаленном сервере. Тем не менее, стандартных возможностей хватает и для создания настольных windows-приложений, и для скриптинга, и для серверного кода.
Критичной эта особенность стала в тот момент, когда мне захотелось писать скрипты на ПК и получать результат их выполнения на Raspberry Pi без копирования и запуска вручную. Дальше мой рецепт для Windows 8.1 (только запуск).
Да, пойдем по сложному пути и используем в качестве рабочего места машину с запущенным Windows. Провернуть подобное на Linux было бы проще, но я решил заодно посмотреть возможности нового для меня Windows PowerShell вместо bash’a. Удивительно, но он справился. Так же можно использовать cmd.exe и bat-файлы.
Итак, железо — Raspberry Pi любой модели с raspbian на борту, доступом к локальной сети и работающим ssh. ПК с окнами подключен в эту же сеть, на нем уже установлены PyCharm и Python (на момент написания, актуальная версия в репозиториях Raspbian — 3.2, лучше установить такую же).
Коммуникации
sgtatham/putty/download.html. Кстати, сама pytty тоже достаточно удобна.
Python на плате
Я буду выполнять скрипты от имени root. Нельзя так делать.
Включаем клиент (Xshell), подключаемся к raspberry, ставим
«Поддельный» интерпретатор
Для начала создадим фейковый интерпретатор. Запускаем Windows PowerShell от имени администратора, создаем папочку.
Чтобы не потерять и не мусорить в PATH, закидываем сюда же pscp и plink:
PyCharm принимает в качестве исполняющегося файла интерпретатора только файлы с именем python.exe, так что сделаем такую нехорошую вещь:
Вероятно, придется отключить проверки подписи скриптов:
Создаем файл скрипта для загрузки проекта на сервер, например такой (пусть зовется deploy.ps1):
Где 192.168.1.230 — адрес удаленного сервера, root и passw0rd — логин и пароль. На один раз хватит и хардкода.
Эта версия принимает адрес до локальной папки и имя папки, которую требуется создать на сервере, и просто копирует все содержимое из первой во вторую. Для проектов больше сотни килобайт стоит оптимизировать это место.
Создаем файл передачи и запуска кода на сервере (пусть python.ps1). В простейшем случае такой:
Где testProject — название будущего проекта.
Настройка IDE
Сделаем так, чтоб вместо интерпретатора пайтона запускался интерпретатор оболочки.
Создав проект, заходим в настройки File->Settings или Ctrl-Alt-S. В вкладке проекта — Project Interpreter. Нажимаем Add Local:

IDE ругается, но добавляет в список. Нажмем «More..» и переименуем в wrapper:

Лучше вернуть Project Interpreter обратно на версию 3.2 (у меня стоит 3.4), иначе отвалятся подсказки и автодополнение.
Здесь всё, откроем конфигурации запуска Run->Edit Configurations. И добавим два конфига:
— Обычный для локальной отладки:

— И нашего монстра для удаленного запуска:

Где выбираем в качестве интерпретатора наш wrapper и задаем постоянный параметр — путь до файла python.ps1. Таким образом на самом деле будет вызван powershell, который выполнит переданный ему скрипт python.ps1 с передачей всех последующих параметров.
Сейчас уже можно написать Hello World и выполнить на целевой машине, но в таком виде мы сможем тестировать только проекты из одного файла. Для выгрузки на сервер всего проекта добавим здесь же внешний инструмент.

Все. Теперь при выбранной конфигурации remote после нажатия кнопки Run проект зальется на удаленный сервер, где будет запущен скрипт main.py, stdout которого будет выводиться обратно в консоль pycharm.
Улучшение
Для некоторой гибкости и удобства настройки можно добавить генерацию скрипта python.ps1 с использованием имени проекта, а данные об удаленном хосте перенести в одно место
Теперь для настройки под новый сервер надо будет поменять только три строки, а при создании нового проекта — добавить в него конфигурацию remote.
Remotely running commands or scripts with python
Learn how to run commands or entire local scripts (python, bash, etc.) on a remote server from your local machine using python.
The task of communicating and running complex operations between servers can be a difficult and tedious process. Running commands or scripts remotely on a server from your local machine can usually be done quite easily using a scripting language such as bash, but doing this from within a Python application can be quite difficult. Luckily there are Python modules we can use that make the job significantly more easy, namely Paramiko and SCP.
Running commands remotely on another host from your local machine
Using the Paramiko module in Python, you can create an SSH connection to another host from within your application, with this connection you can send your commands to the host and retrieve the output.
Paramiko doesn’t come installed by default in Python, but can be easily installed with pip like so:
The first thing you need to do when running a command remotely is create an SSH connection, this can be done with Paramiko’s SSHClient object like so:
Here we are importing Paramiko, instantiating an SSHClient object, loading the system’s host information(known hosts, keys, etc.) then connecting to it using your credentials.
If you have an SSH key set up on the remote server for the root user, you will not need to specify a username and password. If you have your server set up differently with other options such as a passphrase, the connect method can cater for that as it has several other arguments to suit your needs, these can be found on the official documentation page.
Once you’ve created a connection, you can now use it to run commands on a remote server using the exec_command method. This method takes a command as its main argument and returns the stdin, stdout and stderr of the completed command. The stdout and stderr values are file-like objects and can be interacted with just like you would with files.
As an example, let’s run a simple command to list the contents in the /tmp folder on our remote server.
In the above example we use the ls command with the -1 argument to list the files in the /tmp directory on separate lines. Once the command is complete we can see whether or not is was successful by checking the stderr value. if it is empty we know the command was successful and we can print out the files contained in stdout. If we supply an invalid directory such as /test then stderr will have a value (telling us the directory does not exist) and we can print out the error.
note: if you are accepting user input and using it in your remote commands, make sure you are properly filtering and validating that input as this method of running remote commands is susceptible to command injections.
Running scripts remotely on another host from your local machine
If you want to run an entire script (such as a bash or even a python application) on another server from your local machine, you can make use of the SCP module to upload your script, then simply execute it using the same technique we used above with Paramiko.
The SCP module requires an SSH connection to copy a file to a server, for this we can simply use the connection created with Paramiko’s SSH client which we can also use to run the command to execute the script.
As with Paramiko, SCP does not come installed with Python by default, it can be installed using the following command:
To copy your file across, you’ll need to import the SCPClient object from SCP, this takes the SSH connection from Paramiko as an argument, you can the use the ‘put’ method to upload your file.
Once you’ve uploaded your file, you can execute it on the server using exec_command just like we did in the first example.
As an example, let’s upload and execute a simple bash script on our server that will create a file and write a «hello world» to it once executed.
If we run this script- assuming it connects properly and the the permissions of the source file and destination directory are set correctly- you’ll find a new file has been created in the /tmp directory called test.txt that contains the string «hello world».
Running a lengthy command remotely and polling for its completion
If you need to run a command that may take a while to finish processing, you can run it as a background task on the remote server using ‘&’, fetch its process ID using ‘$!’ and then poll for its completion using the ‘ps’ command.
Providing input for any arguments your remote script may ask for
If you are running a remote script that requires you to pass it arguments, you can simply pipe a list of arguments in the order they are asked for separated by line separators ‘\n’.
Say we have the following script on the remote server which sequentially asks for 2 arguments:
We can provide the arguments it needs using exec_command like this:
This will return the following output:
If you have any questions or want to know more about the topic, please leave a comment below!
Christopher Thornton @Instructobit 4 years ago
How to connect to a remote Windows machine to execute commands using python?
I am new to Python and I am trying to make a script that connects to a remote windows machine and execute commands there and test ports connectivity.
Here is the code that I am writing but it is not working. Basically, I want to and it returns with the local machine data, not the remote one.
11 Answers 11
You can connect one computer to another computer in a network by using these two methods:
- Use WMI library.
- Netuse method.
Here is the example to connect using wmi module:
netuse
The second method is to use netuse module.
By Netuse, you can connect to remote computer. And you can access all data of the remote computer. It is possible in the following two ways:
Connect by virtual connection.
Mount remote computer drive in local system.
To unmount remote computer drive in local system:
Before using netuse you should have pywin32 install in your system with python also.
![]()
![]()
You can use pywinrm library instead which is cross-platform compatible.
Here is a simple code example:
Install library via: pip install pywinrm requests_kerberos .
Here is another example from this page to run Powershell script on a remote host:
Maybe you can use SSH to connect to a remote server.
Install freeSSHd on your windows server.
SSH Client connection Code:
Execution Command and get feedback:
do the client machines have python loaded? if so, I’m doing this with psexec
On my local machine, I use subprocess in my .py file to call a command line.
the -c copies the file to the server so i can run any executable file (which in your case could be a .bat full of connection tests or your .py file from above).
![]()
I have personally found pywinrm library to be very effective. However, it does require some commands to be run on the machine and some other setup before it will work.
I don’t know WMI but if you want a simple Server/Client, You can use this simple code from tutorialspoint
Server:
Client
it also have all the needed information for simple client/server applications.
Just convert the server and use some simple protocol to call a function from python.
P.S: i’m sure there are a lot of better options, it’s just a simple one if you want.
The best way to connect to the remote server and execute commands is by using "wmiexec.py"
Just run pip install impacket
Which will create "wmiexec.py" file under the scripts folder in python
Inside the python > Scripts > wmiexec.py
we need to run the wmiexec.py in the following way
Pleae change the wmiexec.py location according to yours
Like im using python 3.8.5 and my wmiexec.py location will be C:\python3.8.5\Scripts\wmiexec.py
Modify TargetUser, TargetPassword ,TargetHostname and OS command according to your remote machine
Note: Above method is used to run the commands on remote server.
But if you need to capture the output from remote server we need to create an python code.
способы удаленного запуска python-скриптов
допустим, у меня есть набор консольных команд, которые должны быть извлечены на целевой линукс машине (машин может быть несколько), команды засунуты в питон. как лучше запускать и доставлять скрипт?
- запускать программу на «запускаторе», который через ssh будет отправлять последовательно команды на целевые машинки
- разлить скрипт по машинкам по ssh и уже локальный скрипт дергать удаленно
- использовать монструозную систему управления конфигурациями
или это зависит требований и контекста? какие еще варианты?


это третий пункт, ок. а с какого количества целевых машин ансибль имеет смысл?

а с какого количества целевых машин имеет смысл ssh ?

сейчас я обкатываю скрипт и целевая машина одна. это быстро и удобно, вполне устраивает. поэтому здесь и сейчас нет смысла в ансибле. я вот и думаю, что делать когда машин станет больше.
Была такая штука fabric, может и сейчас есть. Там все как тебе нужно, наверное.
Нет, это четвертый.
Ansible становится монструозным когда на нем делаются монструозные вещи.
А для твоей задачи ansible playbook будет в три раза короче и проще чем любой баш-скрипт который ты попробуешь написать самостоятельно. Строчек в пять можно уложиться.
Плюс не будет мучительно больно потом, когда осознаешь что и парк машин вырос и хотелки заметно увеличились и пора таки браться за ум.

Как будто это что-то плохое.
Часто написать скрипт намного проще.
Зачем городить огород, который нужен только для 1.5 землекопа.
А если машин станет больше, обход скриптом по списку машин не сильно изменит трудоемкость.
Часто написать скрипт намного проще.
Не в случае ansible.
А если машин станет больше, обход скриптом по списку машин не сильно изменит трудоемкость.
И добавление retry не сильно изменит, и параметризация машин, и чуть-чуть разные версии систем. и таймаут, и debug-лог. и потом раз: и у тебя нечитаемая простыня на 100500 строк на баше. Откуда ж она взялась, вроде всё «просто» было?

И добавление retry не сильно изменит, и параметризация машин, и чуть-чуть разные версии систем. и таймаут, и debug-лог..
А в случае Ansible открывать все эти радости жизни ему не придется? Ansible это выжимка лучшего опыта, это ему поможет, но на это тоже придется немало потратить времени.

А в случае Ansible открывать все эти радости жизни ему не придется?
Придётся, в доке на первой странице, минут за 10. В stackoverflow за 3.

придется. но времени на это уйдёт явно меньше, чем на написание шелл-скрипта с retry и логами.

чем ансибль лучше дженкинса, папета и тд?
чем ансибль лучше дженкинса, папета и тд?
Это совсем разные категории
Дженкинс — это java-комбайн: планировщик, очередь, обработчики, пост-хуки, web UI, groovy и нечитаемые exceptions.
Puppet — это мастер-слейв, программирование на ruby, ООП, сложные зависимости..
ansible, в своем простейшем варианте, без Tower и фишечек, это по сути аннотированный баш-скрипт. То есть берешь свой скрипт и из каждой строчки делаешь шаг в yaml-е добавив строку описания.
Потом конечно чуть подумаешь и заменишь стандартные команды на готовые обертки.
и пошла эволюция.
И он не требует никакой предварительной инфраструктуры кроме ssh-доступа на сервер.
Использовать ansible. Он не монструозный, умеет первые два пункта в любых комбинациях и делает это заведомо лучше чем набыдлокодишь ты.