Created
September 22, 2021 02:47
-
-
Save alongthecloud/fc2eae04c1322be6be85d06e4ef211c2 to your computer and use it in GitHub Desktop.
to connect ssh by paramiko library
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import paramiko | |
import re | |
import time | |
# reference sites | |
# * https://stackoverflow.com/questions/1911690/nested-ssh-session-with-paramiko | |
# * https://stackoverflow.com/questions/53707630/paramiko-how-to-detect-if-command-executed-using-invoke-shell-has-finished | |
# use paramiko library | |
class SSHConnect: | |
def __init__(self): | |
self.client = paramiko.SSHClient() | |
self.transport = None | |
def connectAndOpen(self, host, port, username, password): | |
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy) | |
self.client.connect( hostname = host, port = port, username = username, password = password, allow_agent = True ) | |
print ("Connected to %s" % host) | |
self.transport = self.client.get_transport() | |
self.password = password | |
return | |
def runCommand(self, commandText): | |
print("> %s" % commandText) | |
self.session = self.transport.open_session() | |
self.session.set_combine_stderr(True) | |
self.session.get_pty() | |
self.session.setblocking(1) | |
self.session.exec_command(commandText) | |
loop = 1 | |
while loop > 0: | |
loop = loop - 1 | |
while self.session.exit_status_ready()==False: | |
stdout = self.session.recv(1024).decode("utf-8") | |
# When requesting password input, put the stored password. | |
if re.search('[Pp]assword', stdout): | |
self.session.send(self.password+'\n') | |
loop = loop + 1 | |
else: | |
print(stdout, end='') | |
self.session.close() | |
return | |
def close(self): | |
self.transport.close() | |
self.transport = None | |
self.client.close() | |
self.client = None | |
Host = '127.0.0.1' | |
Port = 22 | |
ID = '' | |
Password = '' | |
con = SSHConnect() | |
con.connectAndOpen(Host, Port, ID, Password) | |
print("Start") | |
con.runCommand("df -h") | |
time.sleep(1) | |
con.runCommand("sudo apt update && sudo apt upgrade -y") | |
print("End") | |
con.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment