Python ssh subprocess popen

josephcoombe / ssh_from_windows_with_subprocess_openssh_example.py

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters

# SSH from Windows 10 using Python subprocess + built-in OpenSSH
#
# Alternatives to using subprocess include:
# Fabric: http://www.fabfile.org/
# Paramiko: http://www.paramiko.org/
#
# References:
# OpenSSH in Windows 10: https://blogs.msdn.microsoft.com/commandline/2018/01/22/openssh-in-windows-10/
# The only simple way to do SSH in Python today is to use subprocess + OpenSSH. https://gist.github.com/bortzmeyer/1284249
# Issue8557 — subprocess PATH semantics and portability: https://bugs.python.org/issue8557
# Python does not find System32: https://stackoverflow.com/a/41631476/8670609
import os
import subprocess
import platform
PRIVATE_KEY_LOCATION = «C:/Users/johndoe/.ssh/id_rsa» # private key location here
USER = «johndoe» # username here
HOST = «192.168.1.1» # address here
COMMAND = «uname -a» # command here
# Ports are handled in ~/.ssh/config since we use OpenSSH
# Handle execution of 32-bit Python on 64-bit Windows
system32 = os . path . join ( os . environ [ ‘SystemRoot’ ], ‘SysNative’ if platform . architecture ()[ 0 ] == ’32bit’ else ‘System32’ )
ssh_path = os . path . join ( system32 , ‘OpenSSH/ssh.exe’ )
ssh = subprocess . Popen ([ ssh_path , ‘-i’ , PRIVATE_KEY_LOCATION , «<>@<>» . format ( USER , HOST )],
stdin = subprocess . PIPE ,
stdout = subprocess . PIPE ,
stderr = subprocess . PIPE )
std_data = ssh . communicate ( COMMAND )
print ( «ssh stdout: \n <>» . format ( std_data [ 0 ]))
print ( «ssh stderr: \n <>» . format ( std_data [ 1 ]))
Читайте также:  Javascript to use cookies to

Источник

Remote control of hosts over SSH¶

It is possible to control a local ssh session using subprocess.Popen() if no libraries are available. This is a super primative way to do things, and not recommended if you can avoid it.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
import subprocess import sys HOST="www.example.org" # Ports are handled in ~/.ssh/config since we use OpenSSH COMMAND="uname -a" ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) result = ssh.stdout.readlines() if result == []: error = ssh.stderr.readlines() print >>sys.stderr, "ERROR: %s" % error else: print result 

Fabric¶

Fabric is a library and command-line tool for streamlining the use of SSH for application deployment or systems administration tasks.

It provides a basic suite of operations for executing local or remote shell commands (normally or via sudo) and uploading/downloading files, as well as auxiliary functionality such as prompting the running user for input, or aborting execution.

Basic Usage¶

Typical use involves creating a Python file named fabfile.py , containing one or more functions, then executing them via the fab command-line tool. Below is a small but complete fabfile.py containing a single task:

from fabric.api import run def host_type(): run('uname -s') 

Once a task is defined, it may be run on one or more servers, like so:

(sysadmin)$ fab -H applebox,linuxbox host_type [applebox] run: uname -s [applebox] out: Darwin [linuxbox] run: uname -s [linuxbox] out: Linux Done. Disconnecting from localhost. done. Disconnecting from linuxbox. done. 

Task arguments¶

It’s often useful to pass runtime parameters into your tasks, just as you might during regular Python programming. Fabric has basic support for this using a shell-compatible notation: :,=. . It’s contrived, but let’s extend the above example to say hello to you personally: [2]

def hello(name="world"): print("Hello %s!" % name) 

By default, calling fab hello will still behave as it did before; but now we can personalize it:

(sysadmin)$ fab hello:name=Jeff Hello Jeff! Done. 

Those already used to programming in Python might have guessed that this invocation behaves exactly the same way:

(sysadmin)$ fab hello:Jeff Hello Jeff! Done. 

For the time being, your argument values will always show up in Python as strings and may require a bit of string manipulation for complex types such as lists. Future versions may add a typecasting system to make this easier.

Library Usage¶

In addition to use via the fab tool, Fabric’s components may be imported into other Python code, providing a Pythonic interface to the SSH protocol suite at a higher level than that provided by e.g. the ssh library (which Fabric itself uses.) [3]

Consider the case where we want to collect average uptime from a list of hosts:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
from fabric import tasks env.hosts = ['localhost', 'sunflower.heliotropic.us'] pattern = re.compile(r'up (\d+) days') # No need to decorate this function with @task def uptime(): res = run('uptime') match = pattern.search(res) if match: days = int(match.group(1)) env['uts'].append(days) def main(): env['uts'] = [] tasks.execute(uptime) uts_list = env['uts'] if not uts_list:  return # Perhaps we should print a notice here? avg = sum(uts_list) / float(len(uts_list)) print '-' * 80 print 'Average uptime: %s days' % avg print '-' * 80 if __name__ == '__main__': main() 

© Copyright 2012, Jason McVetta.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Python module that provides subprocess-like execution of commands over SSH

License

tsaarni/ssh-subprocess

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

ssh-subprocess is a small Python module that provides subprocess -like API for executing commands remotely over SSH. The module depends on OpenSSH for the SSH functionality and requires non-interactive (e.g. public key) authentication.

The module also supports SCP file transfer for uploading and downloading files and directories.

First establish connection towards remote server:

import ssh_subprocess ssh = ssh_subprocess.Ssh(host='hostname', user='joe', host_key_checking='no')
result = ssh.call('echo "Hello world!" > message')

just like call() in subprocess, call() in ssh-subprocess returns the exit status of the command. In this case it is the exit status of echo command. Also check_call() variant is available. It raises subprocess.CalledProcessError in case of non-zero exit status.

If you want to read the output printed by the remotely executed command:

message = ssh.check_output('cat message') print message

This will print out the contents of the remote text file:

Lastly, popen() allows also writing to stdin of remotely executed command:

p = ssh.popen('cat', stdout=subprocess.PIPE, stdin=subprocess.PIPE) out, err = p.communicate('Hello world!\n') # write 'Hello world!\n' to stdin of 'cat' print out

See the documentation of subprocess for more information.

Files and directories can be uploaded and downloaded by using upload() and download() :

ssh.upload('myfile', '/tmp/myfile.txt') ssh.download('/home/joe/myfiles', '.', recursive=True)

About

Python module that provides subprocess-like execution of commands over SSH

Источник

SSH Using Python

SSH Using Python

  1. Use the paramiko Library in Python to Create SSH Connections and Run Commands
  2. Use the subprocess Module to Create SSH Connections and Run Commands

SSH (stands for Secure Socket Shell ) is a highly used network protocol for secure, encrypted communication services over an unknown and insecure network. It allows us to send commands between two devices over such a network remotely and has many applications.

Python has modules available that allow such SSH execution. This tutorial will discuss how to run shell commands to a remote device after securing the SSH connection.

Use the paramiko Library in Python to Create SSH Connections and Run Commands

The paramiko module is frequently used for implementing SSH protocols in Python. It allows both server and client-side communication.

Check the code below for running shell commands on a remote device using this module.

ssh = paramiko.SSHClient() ssh.connect(server, username=username, password=password) ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd_to_execute) 

The SSHClient() function specifies an SSH server session. We connect to the device using the proper authentication details in the connect function. The required commands can be executed on this device using the exec_command() function.

Another module named spur is derived from this module but has a slightly better interface.

Use the subprocess Module to Create SSH Connections and Run Commands

The check_output() function from the subprocess module can be used to run commands passed to it, and the function returns the output of this command. We can create passwordless SSH connections with this function to execute the required commands.

The following code shows an example of this.

subprocess.check_output(['ssh', 'my_server', 'echo /*/']) 

Another method that can be used from this module is the Popen() . It is similar to the os.Popen() function from the os module to run commands and external programs. In this module, the Popen is a class and not a method. It is a little complicated to use this due to various parameters that need to be specified along with the required command. It combines all the 4 os.popen() functions into one. It also executes the command as a separate process. We can use it to create SSH connections and run commands, as shown below.

subprocess.Popen("ssh @  ".format(user=user, host=host, cmd='ls -l'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 

Manav is a IT Professional who has a lot of experience as a core developer in many live projects. He is an avid learner who enjoys learning new things and sharing his findings whenever possible.

Источник

Оцените статью