Skip to content

Instantly share code, notes, and snippets.

@omz

omz/sshshell.py Secret

Last active December 14, 2015 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omz/d608c0469a66ce745c55 to your computer and use it in GitHub Desktop.
Save omz/d608c0469a66ce745c55 to your computer and use it in GitHub Desktop.
sshshell
#!/usr/bin/python
import paramiko
import cmd
class RunCommand(cmd.Cmd):
""" Simple shell to run a command on the host """
prompt = 'ssh > '
def __init__(self):
cmd.Cmd.__init__(self)
self.hosts = []
self.connections = []
def do_exit(self, args=None):
return True
def do_EOF(self, args=None):
return True
def do_addhost(self, args):
"""add_host
Add the host to the host list"""
if args:
self.hosts.append(args.split(','))
else:
print "usage: host,username,password,port"
def do_listhosts(self, args):
"""Lists all hosts in the hosts list"""
for host in self.hosts:
print host[0]+","+host[1]+","+host[2]+","+host[3]
def do_connect(self, args):
"""Connect to all hosts in the hosts list"""
for host in self.hosts:
client = paramiko.SSHClient()
client.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
client.connect(host[0],
username=host[1],
password=host[2],
port=int(host[3]))
self.connections.append(client)
def do_run(self, command):
"""run
Execute this command on all hosts in the list"""
if command:
for host, conn in zip(self.hosts, self.connections):
stdin, stdout, stderr = conn.exec_command(command)
stdin.close()
for line in stdout.read().splitlines():
print 'host: %s: %s' % (host[0], line)
else:
print "usage: run "
def do_close(self, args=None):
for conn in self.connections:
conn.close()
if __name__ == '__main__':
shell = RunCommand()
try:
shell.cmdloop()
except:
import traceback
traceback.print_exc()
finally:
shell.do_close()
shell.do_exit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment