xxxxxxxxxx
from paramiko.client import SSHClient, AutoAddPolicy
class SSHCmd(object):
def __init__(self,server1,password1):
self.server1 = server1
self.password1 = password1
self.ssh = SSHClient()
self.chan = None
self.connect()
def connect(self):#connect to the first One ( server1 )
self.ssh.set_missing_host_key_policy(AutoAddPolicy())
self.ssh.connect(self.server1, username='USERNME', password='PASS')
self.chan = self.ssh.invoke_shell()
def sendCMD(self,cmd,endswith):
if cmd[-1]!='\n':
cmd+='\n'
buff = ''
while not buff.endswith(endswith):
resp = self.chan.recv(9999)
buff += str(resp.decode())
print(buff)
self.chan.send(cmd)
return buff
def getBuffer(self,ends='> '):
buff = ''
while not buff.endswith(ends):
resp = self.chan.recv(9999)
buff+= resp.decode()
return buff
def close(self):
self.ssh.close()
xxxxxxxxxx
#ssh client in python example
pip install paramiko
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(server,port,username,password)
dir = directory
command = command
#change directory to the location of where you want to run the command and
#change command to the command you want to execute
client.exec_command(f'cd {dir}; {command}')
client.close()
xxxxxxxxxx
import pxssh
s = pxssh.pxssh()
if not s.login ('localhost', 'myusername', 'mypassword'):
print "SSH session failed on login."
print str(s)
else:
print "SSH session login successful"
s.sendline ('mycommand')
s.prompt() # match the prompt
print s.before # print everything before the prompt.
s.logout()
#We can also execute multiple command like this:
s.sendline ('uptime;df -h')
xxxxxxxxxx
stdouts = []
clients = []
# Start the commands
commands = zip(ip_list[1:], user_list[1:], password_list[1:])
for i, (ip, user, password) in enumerate(commands, 1):
print("Open session in: " + ip + "...")
client = paramiko.SSHClient()
client.connect(ip, user, password)
command = \
f"cd {path} && " + \
f"python {python_script} {cluster} -type worker -index {i} -batch 64 " + \
f"> {path}/logs/'command output'/{ip_list[i]}.log 2>&1"
stdin, stdout, stderr = client.exec_command(command)
clients.append(client)
stdouts.append(stdout)
# Wait for commands to complete
for i in range(len(stdouts)):
stdouts[i].read()
clients[i].close()