SSH - Run local Python Script on remote server

Preface

Sometime it’s needed to run python script on SSH Server even this script is located on client site.
May be you’re just looking for a way how to centralize your task management, without copping all your scripts to all managed servers.

In cases like this, it’s handy to know that SSH Protocol can help you.

Script – located on SSH Client

In our case we’ll create just simple pythonl script just to demonstrate the idea.

[root@SSH_Client ~]# cat script.py

import socket
print(socket.gethostname())

Execute local Python Script on remote SSH Server

To execute local Python Script on remote SSH Server we’ll need to:
- Establish SSH connection.
- To start “python” on Remote SSH Server, that will listen at standard input (STDIN)
- To read the script and transfer each command with help of SSH, to python that is listening on remote SSH server.

Example

[root@SSH_Client ~]# ssh root@SSH_Server "python - " <./script.py
SSH_Server
Navigation
Print/export
QR Code
QR Code wiki:infrastructure_tools:ssh:ssh-run_local_python_script_on_remote_server (generated for current page)