Есть отдельный модуль paramiko, позволяет выполнять удаленный код по ssh внутри питон программы
Например так:
import paramiko
from paramiko import SSHClient, AutoAddPolicy
def open_ssh_session(ip, password="", user="root"):
"""Open SSH connection using password or key to ip"""
flag = 1
# Add key if not exist
ssh.set_missing_host_key_policy(AutoAddPolicy())
print "\n", datetime.datetime.now(), "Connecting.. " + ip
try:
ssh.connect(hostname=ip, username=user, password=password, timeout=5)
print datetime.datetime.now(), "%s connected" % ip
except paramiko.AuthenticationException:
print datetime.datetime.now(), "Authentication into %s FAILED" % ip
flag = 0
except paramiko.SSHException:
print datetime.datetime.now(), "%s Negotiation FAILED" % ip
flag = 0
except socket.error:
print datetime.datetime.now(), "Host %s is UNREACHABLE" % ip
flag = 0
except socket.timeout:
print datetime.datetime.now(), "Connecting to host %s TIMEDOUT" % ip
flag = 0
if ssh.get_transport():
ssh.get_transport().window_size = 3 * 1024 * 1024
else:
print datetime.datetime.now(), "%s SSH connection FAILED" % ip
return flag
def close_ssh_session():
"""Close SSH connection"""
ssh.close()
print datetime.datetime.now(), "SSH connection closed"
return
def ssh_cmd_exec(cmd):
"""Executes command on remote host and returns output as ssh_out"""
try:
stdin, stdout, stderr = ssh.exec_command(cmd, timeout=15)
ssh_out = stdout.read() + stderr.read()
except paramiko.SSHException:
print datetime.datetime.now(), 'Executing "%s" FAILED' % cmd
ssh_out = ""
except socket.timeout:
print datetime.datetime.now(), 'Executing "%s" TIMEDOUT' % cmd
ssh_out = ""
return ssh_out
open_ssh_session('127.0.0.1', 'some_pass')
print ssh_cmd_exec('df -h')
close_ssh_session()