How to Use SSH in Your Python Application


If you need to make an SSH connection and issues commands over SSH using your Python application, then you can do the following:

Option 1 – Using the paramiko library

ssh = paramiko.SSHClient()
ssh.connect(server, username=username, password=password)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd_to_execute)

Option 2 – Using the subprocess module

subprocess.check_output(['ssh', 'my_server', 'echo /*/'])

Option 3 – Using the subprocess module

subprocess.Popen("ssh {user}@{host} {cmd}".format(user=user, host=host, cmd='ls -l'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()