Beispiel #1
0
 def __init__(self, host, user, password):
     self.host = host
     self.user = user
     self.password = password
     self.lib = SSHLibrary()
     self.lib.open_connection(self.host,port=810)
     self.lib.login(username=self.user, password=self.password)
class TestSSH(unittest.TestCase):

    encryptionInstance = RsaLibrary.keywords()
    sshSession = SSHLibrary()

    def setUp(self):
        self.keyStoreDir = os.path.join(os.path.expanduser('~'),
                                        "keyStoreSSHTest")
        self.encryptionInstance.RSA_generate_new_keys(
            self.keyStoreDir)  # Creates new set of keys
        self.encryptionInstance.RSA_set_keystore_location(self.keyStoreDir)
        self.hostName = "localhost"
        self.hostUser = "******"
        self.hostPass = "******"

    def testSSHToServer(self):
        self.encryptionInstance.RSA_ssh_copy_key(self.hostName, self.hostUser,
                                                 self.hostPass)
        keys = self.encryptionInstance.RSA_get_key_locations()
        self.sshSession.open_connection(self.hostName)
        self.sshSession.login_with_public_key(self.hostUser,
                                              keys["privateKey"],
                                              keys["privateKeyPass"])
        self.assertEqual(self.sshSession.execute_command("uname"), "Linux")

    def tearDown(self):
        shutil.rmtree(self.keyStoreDir)
Beispiel #3
0
 def __init__(self,hostname,username,password,port,timeout=60,prompt="#"):
     self.host = hostname
     self.user = username
     self.passwd=password
     self.port=port
     self.timeout=timeout
     self.prompt=prompt
     self.ssh_agent = SSHLibrary(timeout=self.timeout, prompt=self.prompt)
Beispiel #4
0
 def __init__(self, parameters: DotDict, data_handler, *user_args,
              **user_options):
     self._sudo_expected = is_truthy(user_options.pop('sudo', False))
     self._sudo_password_expected = is_truthy(
         user_options.pop('sudo_password', False))
     super().__init__(parameters, data_handler, *user_args, **user_options)
     self._execution_counter = 0
     self._ssh = SSHLibrary()
Beispiel #5
0
    def __init__(self):
        # загрузка встроенных библиотек
        self.bi = BuiltIn()
        self.ssh = SSHLibrary()
        self.adv_log = AdvancedLogging()

        # словарь с подготовленными логами
        self.prepared_logs = dict()
Beispiel #6
0
 def test_set_default_confguarition(self):
     timeout, newline, prompt, level = 1, '\r\n', '>', 'DEBUG'
     lib = SSHLibrary()
     lib.set_default_configuration(timeout=timeout,
                                   newline=newline,
                                   prompt=prompt,
                                   loglevel=level)
     self._assert_config(lib._config, timeout, newline, prompt, level)
Beispiel #7
0
 def test_set_client_confguration(self):
     timeout, term_type = 23, 'ansi'
     lib = SSHLibrary()
     lib.open_connection(HOSTNAME)
     lib.set_client_configuration(timeout=timeout, term_type=term_type)
     self._assert_config(lib.current.config,
                         timeout=timeout,
                         term_type=term_type)
Beispiel #8
0
 def __init__(self, host, user, password, rootdir):
     self.host = host
     self.user = user
     self.password = password
     self.rootdir = rootdir
     self.lib = SSHLibrary()
     self.lib.open_connection(self.host)
     self.lib.login(username=self.user, password=self.password)
def execute_ssh_command(ip, username, password, command):
    print "executing ssh command"
    lib = SSHLibrary()
    lib.open_connection(ip)
    lib.login(username=username, password=password)
    print "login done"
    lib.execute_command(command)
    print "command executed : " + command
    lib.close_connection()
 def __create_ssh_connection_and_login(self, host, username='******', password='******'):
     """ Create a new SSH connection and log in """
     try:
         self._ssh = SSHLibrary()
         self._ssh.set_default_configuration(timeout='15 seconds', term_type='xterm', prompt='#')
         self._ssh.open_connection(host)
         self._ssh.login(username, password)
     except:     # noqa
         e = sys.exc_info()[0]
         logger._log_to_console_and_log_file("unable to connect ssh: {} {}".format(host, e))
         self._ssh = None
Beispiel #11
0
 def ssh_(self, host, user, password):
     self.ssh = SSHLibrary(timeout=10)
     try:
         self.ssh.open_connection(host)
         self.ssh.login(user, password)
         command = [
             'show card', 'paginate false', 'show run vlan', 'show version'
         ]
         self.session_command(command)
     except ValueError as e:
         raise e
     return self.ssh
Beispiel #12
0
 def _create_ssh_connection_and_login(host,
                                      username='******',
                                      password='******'):
     try:
         ssh = SSHLibrary()
         ssh.set_default_configuration(timeout='30 seconds')
         ssh.open_connection(host)
         ssh.login(username, password)
         return ssh
     except:
         raise AssertionError("Failed to successfully login via ssh to %s" %
                              host)
Beispiel #13
0
 def __init__(self, host, user, password, rootdir, keyfile=None):
     self.host = host
     self.user = user
     self.password = password
     self.rootdir = rootdir
     self.keyfile = keyfile
     self.lib = SSHLibrary()
     self.lib.open_connection(self.host)
     if self.keyfile is not None:
         self.lib.login_with_public_key(username=self.user, keyfile=self.keyfile)
     else:
         self.lib.login(username=self.user, password=self.password)
def execute_ssh_command(ip, username, password, command):
    """Execute SSH Command

    use username and password of controller server for ssh and need
    karaf distribution location like /root/Documents/dist
    """
    print("executing ssh command")
    lib = SSHLibrary()
    lib.open_connection(ip)
    lib.login(username=username, password=password)
    print("login done")
    cmd_response = lib.execute_command(command)
    print("command executed : " + command)
    lib.close_connection()
    return cmd_response
 def RSA_ssh_copy_key(self, host, username, password):
     """
     Login With Public Key(username,
                           keyLocations['privateKey'],
                           'passphrase')
     """
     sshLibSession = SSHLibrary(loglevel='WARN')
     fo = open(os.path.join(self.keyStore, self.opensshKeyName), "rb")
     sshKey = fo.read()
     fo.close()
     sshLibSession.open_connection(host)
     sshLibSession.login(username, password)
     sshLibSession.execute_command("mkdir .ssh")
     sshLibSession.execute_command((("echo %s > .ssh/authorized_keys")
                                    % (sshKey)))
     sshLibSession.execute_command("chmod 700 .ssh")
     sshLibSession.execute_command("chmod 600 .ssh/authorized_keys")
     sshLibSession.close_connection()
Beispiel #16
0
def service_check(hostname, login, password):

    ssh = SSHLibrary()

    try:
        ssh.open_connection(hostname)
        ssh.login(login, password)
    except:
        print('Erro ao conectar no host!')

    ssh_command = ssh.execute_command('systemctl status nginx')

    if str(ssh_command).find('(running)') != -1:
        status = 'Servico ok!'
    else:
        status = 'Servico com problemas!'

    return status
Beispiel #17
0
    def __init__(self, host, username=None, password=None):
        # Default properties
        self.properties = {
            'init_login_prompt': 'login: '******'init_username': None,
            'login_prompt': 'Please give the username:'******'login_timeout': '3 second',
            'password_prompt': 'Please give the password for user',
            'port': 22,
            'prompt': '\n# ',
            'prompt_is_regexp': True,
            'timeout': '2 minutes',
            'max_conn_attempts': 3,
            'ssh_log_file': None,
            'ssh_key_file': None,
        }

        self.host = host
        self.username = username
        self.password = password
        self.conn = SSHLibrary()
        self.conn_open = False
Beispiel #18
0
def wait_for_controller_stopped(ip, username, password, karafHome):
    lib = SSHLibrary()
    lib.open_connection(ip)
    lib.login(username=username, password=password)

    # Wait 1 minute for the controller to stop gracefully
    tries = 20
    i = 1
    while i <= tries:
        stdout = lib.execute_command("ps -axf | grep karaf | grep -v grep | wc -l")
        processCnt = stdout[0].strip('\n')
        print("processCnt: " + processCnt)
        if processCnt == '0':
            break
        i = i + 1
        time.sleep(3)

    lib.close_connection()

    if i > tries:
        print("Killing controller")
        kill_controller(ip, username, password, karafHome)
Beispiel #19
0
def issue_cmd_via_root(command,
                       host,
                       username=HOST_USER,
                       pwd=HOST_PWD,
                       timeout=300,
                       prompt='$ ',
                       sudo=False,
                       sudo_password=None):
    """
    The return value is ["standard output", "error output", return_value]
    """
    sshLib = SSHLibrary()
    try:
        # print "[INFO] Begin to open the connection of", str(host)
        sshLib.open_connection(host)
        sshLib.login(username, pwd)
    # http://docs.paramiko.org/en/1.15/api/client.html#paramiko.client.SSHClient.connect
    except (SSHClientException, paramiko.SSHException, socket.error,
            socket.timeout) as se:
        errmsg = "[Error] Failed to connect to {host}".format(host=str(host))
        print errmsg
        os.environ["OUTPUT"] = errmsg
        sshLib.close_connection()
        return ["", "", -1]
    ret = sshLib.execute_command(command,
                                 return_stdout=True,
                                 return_stderr=True,
                                 return_rc=True,
                                 sudo=sudo,
                                 sudo_password=sudo_password)
    sshLib.close_connection()
    if ret[2] == 0:
        os.environ["OUTPUT"] = ret[0]
    else:
        os.environ["OUTPUT"] = ret[1]
    return ret
Beispiel #20
0
 def __init__(self, ci_addr="10.10.17.49", ci_user="******", ci_passwd="passw0rd"):
     self.ci_addr = ci_addr
     self.ci_user = ci_user
     self.ci_passwd = ci_passwd
     from SSHLibrary import SSHLibrary
     self.sshLib = SSHLibrary()
 def __init__(self):
     super(PublicKeywords, self).__init__(timeout=10)
     self.blt = BuiltIn()
     # self.s2l = self.get_library_instance("Selenium2Library")
     # self.ssh = self.blt.get_library_instance("SSHLibrary")
     self.ssh = SSHLibrary()
import traceback
import re
import socket
import paramiko
try:
    import exceptions
except ImportError:
    import builtins as exceptions

import gen_print as gp
import func_timer as ft
func_timer = ft.func_timer_class()

from robot.libraries.BuiltIn import BuiltIn
from SSHLibrary import SSHLibrary
sshlib = SSHLibrary()


def sprint_connection(connection, indent=0):
    r"""
    sprint data from the connection object to a string and return it.

    connection                      A connection object which is created by
                                    the SSHlibrary open_connection() function.
    indent                          The number of characters to indent the
                                    output.
    """

    buffer = gp.sindent("", indent)
    buffer += "connection:\n"
    indent += 2
Beispiel #23
0
 def __init__(self):
     self._ssh_lib = SSHLibrary()
Beispiel #24
0
 def test_default_confguration(self):
     self._assert_config(SSHLibrary()._config)
Beispiel #25
0
 def test_overriding_client_configuration(self):
     lib = SSHLibrary(timeout=4)
     lib.open_connection(HOSTNAME, timeout=5)
     self._assert_config(lib.current.config, timeout=5)
Beispiel #26
0
 def test_default_client_configuration(self):
     lib = SSHLibrary()
     lib.open_connection(HOSTNAME)
     self._assert_config(lib.current.config)
### Required dependency ###
# robotframework-sshlibrary

from SSHLibrary import SSHLibrary
import time
import os, subprocess
ssh = SSHLibrary()
ssh.open_connection("10.156.4.65")
username = input("Username: "******"Password: "******"\033c")
ssh.login(username, password)


def restartNetAdapter():
    p = subprocess.Popen(
        'powershell.exe Invoke-Command -Computername JJ-PSRV1 -ScriptBlock {Restart-NetAdapter -Name "Ethernet0"}'
    )
    time.sleep(7)
    p.terminate()


#The loop
while True:
    PSRV1 = ssh.execute_command("vim-cmd vmsvc/power.getstate 20",
                                return_stdout=True)
    PSRV2 = ssh.execute_command("vim-cmd vmsvc/power.getstate 24",
                                return_stdout=True)
    time.sleep(2)
    print("\033c")
    if "Powered on" in PSRV1:
Beispiel #28
0
 def test_setting_configruation_values(self):
     cfg = SSHLibrary(newline='CRLF', prompt='$')._config
     self._assert_config(cfg, newline='\r\n', prompt='$')
Beispiel #29
0
 def create_ssh_connection(self, server, uname, psky):
     obj = SSHLibrary()
     obj.open_connection(server)
     obj.login_with_public_key(uname, psky)
     return obj