Sample code for 30+ languages & platforms
CkPython

Run a Single SSH Command and Get the Output

See more SSH Examples

Demonstrates the Chilkat Ssh.QuickCommand method, which runs one noninteractive remote command and returns its stdout as text. The first argument is the command and the second is the charset used to decode the output. Internally it opens a session channel, sends an exec request, and receives the output through EOF.

Background: This collapses the whole open-channel / exec / receive / retrieve sequence into a single call, and it is the right choice for the common case of "run one command and give me the output." Because no PTY is involved the output is clean and parseable, with no prompt or echoed input. Reach for the individual channel methods only when you need stderr separately, the exit status, or an interactive session.

Chilkat CkPython Downloads

CkPython
import sys
import chilkat

success = False

#  Demonstrates the Ssh.QuickCommand method, which runs one noninteractive remote command and
#  returns its stdout as text.  The 1st argument is the command and the 2nd is the charset used
#  to decode the output.  Internally it opens a session channel, sends an exec request, and
#  receives the output through EOF.

ssh = chilkat.CkSsh()

sshPort = 22
success = ssh.Connect("ssh.example.com",sshPort)
if (success == False):
    print(ssh.lastErrorText())
    sys.exit()

#  Normally you would not hard-code the password in source.  You should instead obtain it
#  from an interactive prompt, environment variable, or a secrets vault.
password = "mySshPassword"

success = ssh.AuthenticatePw("mySshLogin",password)
if (success == False):
    print(ssh.lastErrorText())
    sys.exit()

#  Run a single command and collect its output in one call.
output = ssh.quickCommand("uname -a","utf-8")
if (ssh.get_LastMethodSuccess() == False):
    print(ssh.lastErrorText())
    sys.exit()

print(output)

ssh.Disconnect()