Skip to content

Commit

Permalink
Remove commented old code
Browse files Browse the repository at this point in the history
Signed-off-by: Noah Solomon <t-nosolomon@microsoft.com>
  • Loading branch information
noahsolomon-ms committed Aug 9, 2022
1 parent 2e57621 commit b932d80
Show file tree
Hide file tree
Showing 5 changed files with 43 additions and 121 deletions.
134 changes: 29 additions & 105 deletions rcli/linecard.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import time
import paramiko
from rich.console import Console

from getpass import getpass
from .utils import get_linecard_ip
Expand All @@ -10,73 +8,53 @@

class Linecard:

# def __init__(self, hostname, username, console):
# """Initialize Linecard object and store credentials, connection, and channel."""
# # Store credentials
# self.hostname = hostname
# self.username = username
# self.console = console

def __init__(self, hostname, username, console, print_login=True):
def __init__(self, linecard_name, username, password=None):
"""Initialize Linecard object and store credentials, connection, and channel."""
self.hostname = hostname
self.linecard_name = linecard_name
self.ip = get_linecard_ip(linecard_name)
self.username = username
self.console = console

if not os.path.exists(os.path.expanduser(f"~/.ssh/id_rsa")):
os.system(f'ssh-keygen -f {os.path.expanduser(f"~/.ssh/id_rsa")} -N ""')

try:
self.connect(print_login=print_login)
except paramiko.ssh_exception.AuthenticationException:
# host does not trust this client, perform a ssh-copy-id
password = getpass(f"Password for '{hostname}': ")
pub_key = open(os.path.expanduser(f"~/.ssh/id_rsa.pub"), "rt")
pub_key_contents = pub_key.read()
pub_key.close()
self.connect(password, print_login=print_login)
self.channel.send(f'mkdir ~/.ssh \n')
self.get_channel_output()
self.channel.send(f'echo \'{pub_key_contents}\' >> ~/.ssh/authorized_keys \n')
self.get_channel_output()
password = password if password is not None else getpass(
"Password for '{}': ".format(username)
)

self.connect(password)

# come back later for ssh-agent
#
# if not os.path.exists(os.path.expanduser(f"~/.ssh/id_rsa")):
# os.system(f'ssh-keygen -f {os.path.expanduser(f"~/.ssh/id_rsa")} -N ""')

# try:
# self.connect(print_login=print_login)
# except paramiko.ssh_exception.AuthenticationException:
# # host does not trust this client, perform a ssh-copy-id
# password = getpass(f"Password for '{hostname}': ")
# pub_key = open(os.path.expanduser(f"~/.ssh/id_rsa.pub"), "rt")
# pub_key_contents = pub_key.read()
# pub_key.close()
# self.connect(password, print_login=print_login)
# self.channel.send(f'mkdir ~/.ssh \n')
# self.get_channel_output()
# self.channel.send(f'echo \'{pub_key_contents}\' >> ~/.ssh/authorized_keys \n')
# self.get_channel_output()

def connect(self, password=None, print_login=True):
def connect(self, password):
# Create connection to server and initialize shell channel
self.connection = paramiko.SSHClient()
self.connection.load_system_host_keys()
pkey = paramiko.RSAKey.from_private_key_file(os.path.expanduser("~/.ssh/id_rsa"))
# pkey = paramiko.RSAKey.from_private_key_file(os.path.expanduser("~/.ssh/id_rsa"))
self.connection.set_missing_host_key_policy(paramiko.AutoAddPolicy())

self.connection.connect(self.ip, username=self.username, password=password)
self.channel = "hi"

# Create channel for shell input/output
# self.channel = self.connection.get_transport().open_session()
# self.channel.get_pty()
# self.channel.invoke_shell()
# self.channel.send("stty -echo\n")

# if print_login:
# # Print initial SONiC login message
# print(self.get_channel_output())
# else:
# # Flush output
# self.get_channel_output()

def start_shell(self):
"""Continuously wait for a command to be inputted, execute that command on remote shell, and print output."""
self.channel = self.connection.get_transport().open_session()
self.channel.get_pty()
self.channel.invoke_shell()
interactive.interactive_shell(self.channel)
# command = ""
# while command not in EXIT_KEYWORDS:
# self.channel.send(command + "\n")
# output = self.get_channel_output(with_prompt=True)
# prompt_index = max(0, output.rfind("\n"))
# prompt = output[prompt_index:]
# print("{}".format(output[:prompt_index]))
# command = input(prompt.replace("\n",""))

self.connection.close()

Expand All @@ -87,57 +65,3 @@ def execute_cmd(self, command):
output = stdout.read().decode('utf-8')
self.connection.close()
return output
self.connection.exec_command(command + "\n")
output = self.get_channel_output()
self.connection.close()
return output


def get_channel_output(self):
"""Helper method to print output from remote shell session."""
output = ''
while self.channel.recv_ready() or output in EMPTY_OUTPUTS:
if self.channel.recv_ready():
# Add additional bytes of STDOUT to existing output
output += self.channel.recv(6144).decode('utf-8')
else:
# Channel has no output yet, wait for command to finish running
time.sleep(0.1)

# Return output without default prompt (i.e. `admin@vlab-t2-sup:~$`)
end_index = output.rfind("\n")
return output[:max(end_index, 0)]


# @staticmethod
# def get_linecard(linecard_name: str, username, console, print_login=True):
# """Get a linecard and try to ssh without password. If auth fails, ask for password and ssh-copy-id."""

# if not os.path.exists(os.path.expanduser(f"~/.ssh/id_rsa")):
# os.system(f'ssh-keygen -f {os.path.expanduser(f"~/.ssh/id_rsa")} -N ""')

# new_linecard = Linecard(linecard_name, username, console)
# try:
# new_linecard.connect(print_login=print_login)
# except paramiko.ssh_exception.AuthenticationException:
# # host does not trust this client, perform a ssh-copy-id
# password = getpass(f"Password for '{linecard_name}': ")
# pub_key = open(os.path.expanduser(f"~/.ssh/id_rsa.pub"), "rt")
# pub_key_contents = pub_key.read()
# pub_key.close()
# new_linecard = Linecard(linecard_name, username, console)
# new_linecard.connect(password, print_login=print_login)
# new_linecard.channel.send(f'mkdir ~/.ssh \n')
# new_linecard.get_channel_output()
# new_linecard.channel.send(f'echo \'{pub_key_contents}\' >> ~/.ssh/authorized_keys \n')
# new_linecard.get_channel_output()

return new_linecard

# Example usage
if __name__=="__main__":
hostname = '10.250.0.121'
username = 'admin'
password = 'password'
client = Linecard(hostname, username, Console())
client.start_shell()
8 changes: 2 additions & 6 deletions rcli/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import click
import execute
import shell


#
# 'rcli' group (root group)
Expand All @@ -11,7 +10,4 @@
# @click.pass_context
def cli():
"""SONiC command line - 'rcli' command"""
pass

cli.add_command(execute.execute)
cli.add_command(shell.shell)
pass
10 changes: 5 additions & 5 deletions rcli/rexec.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,16 @@
def rexec(linecards, command, username):
"""Execute a command on one (or many) linecards."""
username = username if username else os.getlogin()
password = getpass("Password for '{}': ".format(username))
password = getpass("Password for username '{}': ".format(username))

shells = []
# Collect linecards
for linecard_name in linecards:
try:
lc = Linecard(linecard_name, username, password, print_login=False)
lc = Linecard(linecard_name, username, password)
shells.append(lc)
except paramiko.ssh_exception.AuthenticationException:
print("Login failed on '{}' with username '{}'".format(linecard_name, username))
click.echo("Login failed on '{}' with username '{}'".format(linecard_name, username))

# Delay for linecards to flush output
time.sleep(0.5)
Expand All @@ -32,8 +32,8 @@ def rexec(linecards, command, username):
for linecard in shells:
if linecard.channel:
# If channel was created, connection exists. Otherwise, user will see an error message.
print("======== {} output: ========".format(linecard.linecard_name))
print(linecard.execute_cmd(command))
click.echo("======== {} output: ========".format(linecard.linecard_name))
click.echo(linecard.execute_cmd(command))

if __name__=="__main__":
rexec(prog_name='rexec')
2 changes: 1 addition & 1 deletion rcli/rshell.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def rshell(linecard_name, username):
# If channel was created, connection exists. Otherwise, user will see an error message.
lc.start_shell()
except paramiko.ssh_exception.AuthenticationException:
print("Login failed on '{}' with username '{}'".format(linecard_name, username))
click.echo("Login failed on '{}' with username '{}'".format(linecard_name, username))


if __name__=="__main__":
Expand Down
10 changes: 6 additions & 4 deletions rcli/utils.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import click

from swsscommon.swsscommon import SonicV2Connector

CHASSIS_MODULE_INFO_TABLE = 'CHASSIS_MODULE_TABLE'
Expand All @@ -21,13 +23,13 @@ def get_linecard_ip(linecard_name: str):

keys = state_db.keys(state_db.STATE_DB, CHASSIS_MIDPLANE_INFO_TABLE + key_pattern)
if not keys:
print('{} table is empty'.format(key_pattern, CHASSIS_MIDPLANE_INFO_TABLE))
click.echo('{} table is empty'.format(key_pattern, CHASSIS_MIDPLANE_INFO_TABLE))
return

for key in keys:
key_list = key.split('|')
if len(key_list) != 2: # error data in DB, log it and ignore
print('Warn: Invalid Key {} in {} table'.format(key, CHASSIS_MIDPLANE_INFO_TABLE))
click.echo('Warn: Invalid Key {} in {} table'.format(key, CHASSIS_MIDPLANE_INFO_TABLE))
continue

data_dict = state_db.get_all(state_db.STATE_DB, key)
Expand All @@ -49,15 +51,15 @@ def get_all_linecards(ctx, args, incomplete):

keys = state_db.keys(state_db.STATE_DB, CHASSIS_MIDPLANE_INFO_TABLE + key_pattern)
if not keys:
print('{} table is empty'.format(key_pattern, CHASSIS_MIDPLANE_INFO_TABLE))
click.echo('{} table is empty'.format(key_pattern, CHASSIS_MIDPLANE_INFO_TABLE))
return []

linecards = []

for key in keys:
key_list = key.split('|')
if len(key_list) != 2: # error data in DB, log it and ignore
print('Warn: Invalid Key {} in {} table'.format(key, CHASSIS_MIDPLANE_INFO_TABLE))
click.echo('Warn: Invalid Key {} in {} table'.format(key, CHASSIS_MIDPLANE_INFO_TABLE))
continue

data_dict = state_db.get_all(state_db.STATE_DB, key)
Expand Down

0 comments on commit b932d80

Please sign in to comment.