Pages

Monday, July 13, 2020

Python client for ssh


Sample code to access ssh by providing username and password 
#!/usr/bin/python3

#from __future__ import print_function

import os
import socket
from ssh2.session import Session


host = 'myserver'
user = os.getlogin()

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, 22))

session = Session()
session.handshake(sock)
session.userauth_password('oracle', 'mypassword')

channel = session.open_session()
channel.execute('date ')
print (channel.read())

#size, data = channel.read()   ## More managed reading like size etc 
#while size > 0:
#    print(data)
#    size, data = channel.read()

channel.close()



#print("Exit status: %s" % channel.get_exit_status())  ## Shows exit status
## pip install ssh2-python