How can I use putty.exe with python to run remote unix commands like "mail" "cat" etc? I have a file on my unix machine, I want to send that file content as an email
Asked
Active
Viewed 312 times
2 Answers
2
you dont
(or at least you shouldnt)
... instead use paramiko
here is a helper class I use with paramiko (see example use at the bottom) ... im pretty sure i found most of this class in some other stack overflow answer years ago
from contextlib import contextmanager
import os
import re
import paramiko
import time
class SshClient:
"""A wrapper of paramiko.SSHClient"""
TIMEOUT = 10
def __init__(self, connection_string,**kwargs):
self.key = kwargs.pop("key",None)
self.client = kwargs.pop("client",None)
self.connection_string = connection_string
try:
self.username,self.password,self.host = re.search("(\w+):(\w+)@(.*)",connection_string).groups()
except (TypeError,ValueError):
raise Exception("Invalid connection sting should be 'user:pass@ip'")
try:
self.host,self.port = self.host.split(":",1)
except (TypeError,ValueError):
self.port = "22"
self.connect(self.host,int(self.port),self.username,self.password,self.key)
def reconnect(self):
self.connect(self.host,int(self.port),self.username,self.password,self.key)
def connect(self, host, port, username, password, key=None):
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.client.connect(host, port, username=username, password=password, pkey=key, timeout=self.TIMEOUT)
def close(self):
if self.client is not None:
self.client.close()
self.client = None
def execute(self, command, sudo=False,**kwargs):
should_close=False
if not self.is_connected():
self.reconnect()
should_close = True
feed_password = False
if sudo and self.username != "root":
command = "sudo -S -p '' %s" % command
feed_password = self.password is not None and len(self.password) > 0
stdin, stdout, stderr = self.client.exec_command(command,**kwargs)
if feed_password:
stdin.write(self.password + "\n")
stdin.flush()
result = {'out': stdout.readlines(),
'err': stderr.readlines(),
'retval': stdout.channel.recv_exit_status()}
if should_close:
self.close()
return result
@contextmanager
def _get_sftp(self):
yield paramiko.SFTPClient.from_transport(self.client.get_transport())
def put_in_dir(self, src, dst):
if not isinstance(src,(list,tuple)):
src = [src]
print self.execute('''python -c "import os;os.makedirs('%s')"'''%dst)
with self._get_sftp() as sftp:
for s in src:
sftp.put(s, dst+os.path.basename(s))
def get(self, src, dst):
with self._get_sftp() as sftp:
sftp.get(src, dst)
def rm(self,*remote_paths):
for p in remote_paths:
self.execute("rm -rf {0}".format(p),sudo=True)
def mkdir(self,dirname):
print self.execute("mkdir {0}".format(dirname))
def remote_open(self,remote_file_path,open_mode):
with self._get_sftp() as sftp:
return sftp.open(remote_file_path,open_mode)
def is_connected(self):
transport = self.client.get_transport() if self.client else None
return transport and transport.is_active()
if __name__ == "__main__":
s = SshClient("user:password@192.168.1.125")
print s.execute("ls")
print s.execute("ls /etc",sudo=True)

Community
- 1
- 1

Joran Beasley
- 110,522
- 12
- 160
- 179
1
The subprocess
module is what you're looking for.
Here is a helpful tutorial on using it http://sharats.me/the-ever-useful-and-neat-subprocess-module.html
Beyond that, without specifics, we're not going to be much help to you.

Patrick Haugh
- 59,226
- 13
- 88
- 96
-
this would be really really painful to do with subprocess ... im pretty sure putty does not provide a command line option to run a remote command (you can put the remote command in a file and give it the file name ... that would sort of work I guess) +1 all the same ... but it would be pain to implement – Joran Beasley Sep 22 '16 at 19:08