Skip to content

Instantly share code, notes, and snippets.

@wention
Created July 16, 2021 02:58
Show Gist options
  • Select an option

  • Save wention/824dce8f9a2826b7c7ff40dfbc3634d6 to your computer and use it in GitHub Desktop.

Select an option

Save wention/824dce8f9a2826b7c7ff40dfbc3634d6 to your computer and use it in GitHub Desktop.
python snippet run command via ssh
import os
import paramiko
class SSHClient(paramiko.SSHClient):
def run_cmd(
self,
command,
bufsize=-1,
timeout=None,
get_pty=False,
environment=None,
):
chan = self._transport.open_session(timeout=timeout)
if get_pty:
chan.get_pty()
chan.settimeout(timeout)
if environment:
chan.update_environment(environment)
chan.exec_command(command)
stdout = chan.makefile("r", bufsize)
stderr = chan.makefile_stderr("r", bufsize)
exit_status = chan.recv_exit_status()
return stdout.read().decode(), stderr.read().decode(), exit_status
def trace_cmd(ssh, cmd):
out, err, rc = client.run_cmd(cmd)
print("exit status: %s" % rc)
print("out: %s" % out)
print("err: %s" % err)
if __name__ == "__main__":
client = SSHClient()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
client.connect('192.168.5.17', username="root")
trace_cmd(client, "ls -lha /sr/vm/abc")
trace_cmd(client, "ls -lha /sr/vm")
client.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment