Esempio n. 1
0
def search_atlas(ra, dec):
    atlas_info = lc_cfg['atlas_info']
    gateway_session1 = SSHSession(atlas_info[0]['address'],atlas_info[0]['username'], password=atlas_info[0]['password']).open()
    if len(atlas_info)==3:
        gateway_session2 = gateway_session1.get_remote_session(atlas_info[1]['address'],atlas_info[1]['username'], password=atlas_info[2]['password'])
        remote_session = gateway_session2.get_remote_session(atlas_info[2]['address'], password=atlas_info[2]['password'])
    elif len(atlas_info)==2:
        remote_session = gateway_session1.get_remote_session(atlas_info[1]['address'], password=atlas_info[1]['password'])
    else: 
        print('wrong format for atlas_params: too many jump connection')

    today = dt.today()
    con = sqlite3.connect(":memory:")
    tdate = '  '+str(list(con.execute("select julianday('"+today.strftime("%Y-%m-%d")+"')"))[0][0]-lc_cfg['lookback_days']-2400000)

    result=remote_session.get_cmd_output('./mod_force.sh '+str(ra)+' '+ str(dec)+tdate)

    atlas_lc = at.Table(names=('jd','mag', 'mag_err','flux', 'fluxerr', 'filter','maj', 'min', 'apfit', 'sky', 'zp', 'zpsys'), dtype=('f8', 'f8', 'f8', 'f8', 'f8', 'S1' , 'f8', 'f8', 'f8', 'f8','f8', 'U8'))

    split = result.split('\r\n')

    for i in split[1:]:
        k = i.split()
#        if int(k[3])>int(k[4]):
        atlas_lc.add_row([float(k[0]), float(k[1]), float(k[2]), float(k[3]), float(k[4]), k[5], float(k[12]), float(k[13]), float(k[15]), float(k[16]),  float(k[17]), 'ab'])

    return atlas_lc
Esempio n. 2
0
def test_file(docker_env):
    gateway_ip, gateway_port = docker_env.get_host_ip_port('gateway')
    gateway_session = SSHSession(host=gateway_ip,
                                 port=gateway_port,
                                 username='******',
                                 password='******').open()

    remotehost_ip, remotehost_port = docker_env.get_host_ip_port('remotehost')
    remotehost_session = gateway_session.get_remote_session(
        host=tests_util.get_host_ip(),
        port=remotehost_port,
        username='******',
        password='******')
    file_content = json.dumps(tests_util.create_random_json())

    # create file in a location with root access needed should fail by default
    with pytest.raises(IOError) as excinfo:
        remotehost_session.file(remote_path='/etc/a_file',
                                content=file_content)
    assert excinfo.value.errno == errno.EACCES
    assert excinfo.value.strerror == 'Permission denied'

    # do same command with root access
    remotehost_session.file(remote_path='/etc/a_file',
                            content=file_content,
                            use_sudo=True)
Esempio n. 3
0
def test_ssh_connection_error(docker_env):
    gateway_ip, gateway_port = docker_env.get_host_ip_port('gateway')

    # open first ssh session to gateway
    gateway_session1 = SSHSession(host=gateway_ip,
                                  port=gateway_port,
                                  username='******',
                                  password='******').open()

    # modify password from session 1
    gateway_session1.run_cmd('echo "user1:newpassword" | sudo -S chpasswd')

    # try to open 2nd session
    with pytest.raises(exception.ConnectionError) as excinfo:
        SSHSession(host=gateway_ip,
                   port=gateway_port,
                   username='******',
                   password='******').open()
    assert type(excinfo.value.__cause__
                ) == paramiko.ssh_exception.AuthenticationException

    # set back correct password from session 1
    gateway_session1.run_cmd('echo "user1:password1" | sudo -S chpasswd')

    # try again to open 2nd session
    gateway_session2 = SSHSession(host=gateway_ip,
                                  port=gateway_port,
                                  username='******',
                                  password='******').open()
    assert gateway_session2.is_active()
Esempio n. 4
0
def test_get_cmd_output(docker_env):
    gateway_ip, gateway_port = docker_env.get_host_ip_port('gateway')
    gateway_session = SSHSession(host=gateway_ip,
                                 port=gateway_port,
                                 username='******',
                                 password='******').open()

    assert gateway_session.get_cmd_output('hostname') == 'gateway.example.com'
Esempio n. 5
0
def test_unknown_host():
    with pytest.raises(exception.ConnectionError) as excinfo:
        SSHSession(host='unknown_host', username='******').open()
    assert type(excinfo.value.__cause__) == socket.gaierror

    with pytest.raises(exception.ConnectionError) as excinfo:
        SSHSession(host='unknown_host', username='******').open(retry=2)
    assert type(excinfo.value.__cause__) == socket.gaierror
Esempio n. 6
0
def test_get_exit_code(docker_env):
    gateway_ip, gateway_port = docker_env.get_host_ip_port('gateway')

    gateway_session = SSHSession(host=gateway_ip,
                                 port=gateway_port,
                                 username='******',
                                 password='******').open()
    assert gateway_session.get_exit_code('ls') == 0
    assert gateway_session.get_exit_code('dummy commmand') == 127
Esempio n. 7
0
	def connect(self, address, username=None, passwd=None):
		if self.verbose:
			print('Connecting session...')

		self.gateway_session = SSHSession(address, username, password=passwd).open()

		if self.verbose:
			print('session %s@%s' % ( username, address ))
		
		self.remote_session = self.gateway_session.get_remote_session(address, password=passwd)
		
		return(self.check_connection())
Esempio n. 8
0
def create_new_cert_on_host(host_session: SSHSession, certificate_file: CertificateFile, ca_cert: str, ca_key: str):
    try:
        ca_cert_file_path = '/tmp/ca.cert.pem'

        ca_key_file_path = '/tmp/ca.key.pem'
        host_session.run_cmd(f'echo "{ca_cert}" > {ca_cert_file_path}; echo "{ca_key}" > {ca_key_file_path} ')
        host_session.run_cmd(f'openssl x509 -in {ca_cert_file_path} -out {certificate_file.file_path}.new -days 365  \
                                -signkey {ca_key_file_path} -sha256')

    except Exception as e:
        print("Could not create new certificate file")
        raise e
Esempio n. 9
0
    def ConnectViaJH(self, JHname, user, pswd):
        print("connecting the jumphost...")
        gateway_session = SSHSession(JHname, user, password=pswd).open()
        print("connecting the device...")
        nexthop = '2a0b:2900:114a:50b::1:10'
        self.remote_session = gateway_session.get_remote_session(
            nexthop,
            username='******',
            private_key_file='D:\code\ssh\cso_id_rsa')
        print("try pwd")
        feedback = self.remote_session.get_cmd_output("bash -lc 'pwd'")

        print(feedback)
Esempio n. 10
0
def ssh_jumpserver_to_server():
    """ create SSH client with jump server"""
    from jumpssh import SSHSession
    # establish ssh connection between your local machine and the jump server
    gateway_session = SSHSession('steppingstone',
                                 'my_user',
                                 password='******').open()
    # from jump server, establish connection with a remote server
    remote_session = gateway_session.get_remote_session(
        'remote.example.com', password='******')

    #execute command on end server
    remote_session.get_cmd_output('ls -lta')
Esempio n. 11
0
def change_link(*args, **kwargs):
    target_link = kwargs.get('link', 'T33L')
    version = kwargs.get('version')
    if kwargs.get('server').startswith('192'):
        gateway_session = SSHSession('173.36.203.62',
                                     'wbxbuilds',
                                     password='******').open()
        print("Connected to sshlogin server.")
        remote_session = gateway_session.get_remote_session(
            kwargs.get('server'),
            kwargs.get('user', 'shuqli'),
            password=kwargs.get('pass', 'wbx@Aa$hfcm'))
        print(f"Connected to target server {kwargs.get('server')}.")
    else:
        remote_session = SSHSession(kwargs.get('server'),
                                    kwargs.get('user', 'wbxroot'),
                                    password=kwargs.get('pass',
                                                        'wbx@AaR00t')).open()

    print("Starting to change link ...")
    remote_session.get_cmd_output(
        "cd /www/htdocs/client; sudo rm -f {target_link}; sudo ln -sf "
        "`ls -lrt|grep WBXclient-{version}|grep ^d|tail -n1|awk '{{"
        "print $NF}}'`  {target_link}; sudo chown -h nobody.nobody "
        "{target_link};".format(version=version, target_link=target_link))
    ret = remote_session.get_exit_code(
        f"test -e /www/htdocs/client/{target_link}")

    print(ret)

    if ret == 0:
        return True
    else:
        return False
Esempio n. 12
0
def test_request_with_body(docker_env):
    gateway_ip, gateway_port = docker_env.get_host_ip_port('gateway')
    gateway_session = SSHSession(host=gateway_ip,
                                 port=gateway_port,
                                 username='******',
                                 password='******').open()
    remotehost_ip, remotehost_port = docker_env.get_host_ip_port(
        'remotehost', private_port=5000)
    rest_client = RestSshClient(gateway_session)

    uri = 'http://%s:%s/echo-body' % (tests_util.get_host_ip(),
                                      remotehost_port)

    json_file_content = tests_util.create_random_json(5)

    # test body specified in input
    http_response = rest_client.post(uri, data=json.dumps(json_file_content))
    assert http_response.status_code == 200
    assert http_response.json() == json_file_content

    # test body from local file
    # 1. error raised when local file does not exist
    with pytest.raises(exception.RestClientError) as exc_info:
        rest_client.post(uri, local_file='missing_file')
    assert 'Invalid file path given' in str(exc_info.value)
    # 2. create file locally
    with tempfile.NamedTemporaryFile() as tmp_local_file:
        tmp_local_file.write(json.dumps(json_file_content).encode('utf-8'))
        tmp_local_file.seek(0)

        http_response = rest_client.post(uri, local_file=tmp_local_file.name)
        assert http_response.status_code == 200
        assert http_response.json() == json_file_content

        # check file copied on remote host has been properly removed
        assert not gateway_session.exists(path=tmp_local_file.name)

    # test body from remote file
    remote_file = 'remote_file.json'
    # 1. error raised when remote file does not exist
    with pytest.raises(exception.RestClientError) as exc_info:
        rest_client.post(uri, remote_file=remote_file)
    assert 'Invalid remote file path given' in str(exc_info.value)
    # 2. create file remotely
    gateway_session.file(remote_path=remote_file,
                         content=json.dumps(json_file_content))
    http_response = rest_client.post(uri, remote_file=remote_file)
    assert http_response.status_code == 200
    assert http_response.json() == json_file_content
Esempio n. 13
0
def test_put(docker_env):
    gateway_ip, gateway_port = docker_env.get_host_ip_port('gateway')
    gateway_session = SSHSession(host=gateway_ip,
                                 port=gateway_port,
                                 username='******',
                                 password='******').open()

    remotehost_ip, remotehost_port = docker_env.get_host_ip_port('remotehost')
    remotehost_session = gateway_session.get_remote_session(
        host=tests_util.get_host_ip(),
        port=remotehost_port,
        username='******',
        password='******')
    # exception is raised when local file does not exist
    local_path = 'missing_folder/missing_path'
    with pytest.raises(IOError) as excinfo:
        remotehost_session.put(local_path=local_path,
                               remote_path='/tmp/my_file')
    assert excinfo.value.errno == errno.ENOENT
    assert excinfo.value.strerror == "Local file '%s' does not exist" % local_path

    # create random file locally
    local_path = os.path.join(os.path.dirname(__file__), 'random_file')
    dummy_json = tests_util.create_random_json()
    with open(local_path, 'wb') as random_file:
        random_file.write(json.dumps(dummy_json).encode('utf-8'))
    try:
        # copy file on remote session
        remote_path = '/tmp/random_file'
        assert remotehost_session.exists(remote_path) is False
        remotehost_session.close()
        remotehost_session.put(local_path=local_path, remote_path=remote_path)
        assert remotehost_session.exists(remote_path) is True

        # copy file on remote session as user2 with specific file permissions
        remote_path = '/tmp/random_file2'
        assert remotehost_session.exists(remote_path) is False
        remotehost_session.put(local_path=local_path,
                               remote_path=remote_path,
                               owner='user2',
                               permissions='600')
        assert remotehost_session.exists(remote_path) is True
        assert remotehost_session.get_cmd_output(
            "ls -l %s | awk '{print $3}'" % remote_path) == 'user2'
        assert remotehost_session.get_cmd_output(
            "stat -c '%a %n' " + remote_path + " | awk '{print $1}'") == '600'
    finally:
        os.remove(local_path)
Esempio n. 14
0
def test_response_methods(docker_env):
    gateway_ip, gateway_port = docker_env.get_host_ip_port('gateway')
    gateway_session = SSHSession(host=gateway_ip,
                                 port=gateway_port,
                                 username='******',
                                 password='******').open()
    remotehost_ip, remotehost_port = docker_env.get_host_ip_port(
        'remotehost', private_port=5000)
    rest_client = RestSshClient(gateway_session)

    endpoint = 'http://%s:%s' % (tests_util.get_host_ip(), remotehost_port)

    # check_for_success
    with pytest.raises(exception.RestClientError):
        rest_client.get(endpoint + '/dummy-uri').check_for_success()

    # is_valid_json_body
    assert rest_client.get(endpoint + '/json').is_valid_json_body() is True
    assert rest_client.get(endpoint + '/').is_valid_json_body() is False

    # json
    with pytest.raises(exception.RestClientError) as exc_info:
        rest_client.get(endpoint + '/').json()
    assert 'http response body is not in a valid json format' in str(
        exc_info.value)
Esempio n. 15
0
def test_active_close_session_with_context_manager(docker_env):
    gateway_ip, gateway_port = docker_env.get_host_ip_port('gateway')

    with SSHSession(host=gateway_ip,
                    port=gateway_port,
                    username='******',
                    password='******') as gateway_session:
        assert gateway_session.is_active()

        remotehost_ip, remotehost_port = docker_env.get_host_ip_port(
            'remotehost')
        remotehost_session = gateway_session.get_remote_session(
            host=tests_util.get_host_ip(),
            port=remotehost_port,
            username='******',
            password='******')
        assert remotehost_session.is_active()

    # check that gateway session is well closed
    assert not gateway_session.is_active()

    # remote session is also automatically closed
    assert not remotehost_session.is_active()

    # try reopening same session
    gateway_session.open()

    assert gateway_session.is_active()

    assert gateway_session.get_exit_code('ls') == 0
Esempio n. 16
0
def test_methods(docker_env):
    gateway_ip, gateway_port = docker_env.get_host_ip_port('gateway')
    gateway_session = SSHSession(host=gateway_ip,
                                 port=gateway_port,
                                 username='******',
                                 password='******').open()
    remotehost_ip, remotehost_port = docker_env.get_host_ip_port(
        'remotehost', private_port=5000)
    rest_client = RestSshClient(gateway_session)

    uri = 'http://%s:%s/echo-method' % (tests_util.get_host_ip(),
                                        remotehost_port)

    # check proper http method is used for each function
    header_name = 'Request-Method'
    if sys.version_info[0] == 2:
        # HTTP header names in the response are all lowercase in Python 2.x.
        header_name = 'request-method'
    assert rest_client.get(uri).headers[header_name] == 'GET'
    assert rest_client.options(uri).headers[header_name] == 'OPTIONS'
    assert rest_client.post(uri).headers[header_name] == 'POST'
    assert rest_client.put(uri).headers[header_name] == 'PUT'
    assert rest_client.patch(uri).headers[header_name] == 'PATCH'
    assert rest_client.delete(uri).headers[header_name] == 'DELETE'
    assert rest_client.head(uri).headers[header_name] == 'HEAD'
Esempio n. 17
0
def get_remote_session(tunnel_session: SSHSession, host_address: str, host_user: str,
                       host_key_path: str = ID_RSA_PATH) -> SSHSession:
    try:
        return tunnel_session.get_remote_session(host_address, host_user, private_key_file=host_key_path)
    except Exception as e:
        print("Could not connect to remote host")
        raise e
Esempio n. 18
0
def test_basic_auth(docker_env):
    gateway_ip, gateway_port = docker_env.get_host_ip_port('gateway')
    gateway_session = SSHSession(host=gateway_ip,
                                 port=gateway_port,
                                 username='******',
                                 password='******').open()
    rest_client = RestSshClient(gateway_session)

    uri = 'http://%s/authentication-required' % REMOTE_HOST_IP_PORT

    # wrong auth param format
    with pytest.raises(exception.RestClientError) as exc_info:
        rest_client.request('GET', uri, auth="invalid_auth_format")
    assert 'Invalid auth parameter' in str(exc_info.value)

    # authentication in error
    http_response = rest_client.request('GET',
                                        uri,
                                        auth=("wrong_user", "wrong_password"))
    assert http_response.status_code == 401
    assert 'You have to login with proper credentials' in http_response.text

    # authentication in success
    http_response = rest_client.request('GET', uri, auth=("admin", "secret"))
    assert http_response.status_code == 200
    assert http_response.text == "Authentication successful"
Esempio n. 19
0
def test_get(docker_env):
    gateway_ip, gateway_port = docker_env.get_host_ip_port('gateway')
    gateway_session = SSHSession(host=gateway_ip,
                                 port=gateway_port,
                                 username='******',
                                 password='******').open()

    remotehost_ip, remotehost_port = docker_env.get_host_ip_port('remotehost')
    remotehost_session = gateway_session.get_remote_session(
        host=tests_util.get_host_ip(),
        port=remotehost_port,
        username='******',
        password='******')

    # create random file on remote host and ensure it is properly there
    remote_path = "remote_file"
    remotehost_session.file(remote_path=remote_path,
                            content=json.dumps(
                                tests_util.create_random_json()))
    assert remotehost_session.exists(remote_path)

    # download that file in local folder
    local_folder = '/tmp/'
    remotehost_session.get(remote_path=remote_path, local_path=local_folder)
    local_file_path = os.path.join(local_folder, os.path.basename(remote_path))
    assert os.path.isfile(local_file_path)
    os.remove(local_file_path)

    # download that file locally specifying local filename
    local_file_path = '/tmp/downloaded_file_' + util.id_generator(size=20)
    remotehost_session.get(remote_path=remote_path, local_path=local_file_path)
    os.remove(local_file_path)

    # get remote file from location not accessible from current user and owned by root
    local_folder = '/tmp/'
    restricted_remote_path = os.path.join('/etc', remote_path)
    remotehost_session.run_cmd([
        'sudo mv %s %s' % (remote_path, restricted_remote_path),
        'sudo chown root:root %s' % restricted_remote_path,
        'sudo chmod 700 %s' % restricted_remote_path,
    ])
    remotehost_session.get(remote_path=restricted_remote_path,
                           local_path=local_folder,
                           use_sudo=True)
    local_file_path = os.path.join(local_folder, os.path.basename(remote_path))
    assert os.path.isfile(local_file_path)
    os.remove(local_file_path)
Esempio n. 20
0
def get_cert_expiration_date(host_session: SSHSession, certificate_file: CertificateFile, ) -> datetime:
    try:
        date_from_host = host_session.get_cmd_output(
            f'openssl x509 -enddate -noout -in "{certificate_file.file_path}" |cut -d= -f 2)')
        return convert_pem_date_to_datetime(date_from_host)
    except Exception as e:
        print("Could not get certificate expiration date")
        raise e
Esempio n. 21
0
 def config(self, hostname, username, password, workstation_id):
     host_session = SSHSession(hostname, username, password=password).open()
     self.host = {
         'id': workstation_id,
         'hostname': hostname,
         'username': username,
         'password': password,
         'session': host_session
     }
Esempio n. 22
0
def test_init_from_session(docker_env):
    gateway_ip, gateway_port = docker_env.get_host_ip_port('gateway')
    gateway_session = SSHSession(host=gateway_ip, port=gateway_port, username='******', password='******')

    with RestSshClient(gateway_session) as rest_client:
        http_response = rest_client.get('http://' + REMOTE_HOST_IP_PORT)

    assert http_response.status_code == 200
    assert http_response.text == 'Hello, World!'
Esempio n. 23
0
def login():

	for widget in frame.winfo_children():
		widget.destroy()
	
	gatewaySession = SSHSession('users.isi.deterlab.net', entryUsername.get(), password=entryPassword.get()).open()
	ltmap = gatewaySession.get_cmd_output('cat /proj/' + entryProject.get() + '/exp/' + entryExperiment.get() + '/tbdata/ltmap')

	if not os.path.isfile('img/' + entryExperiment.get()  + '.png'):
		gatewaySession.get(remote_path='/proj/' + entryProject.get() + '/exp/' + entryExperiment.get() + '/tbdata/' + entryExperiment.get() + '.png', local_path='img/')

	experimentLabel = tk.Label(frame, text="Experiment: " + entryExperiment.get() + " Project: " + entryProject.get(), bg="white", pady=30)
	experimentLabel.pack()

	for line in ltmap.split('\n'):
		#check if first character is h
		count = 1
		if line[0] == 'h':
			nodeName=line[line.find(' ')+1:-1]

			label = tk.Label(frame, text="Node " + nodeName, bg="gray")
			label.pack()

			buttonNew = tk.Button(
				frame,
				text="Login to " + nodeName,
				width=15,
				padx=10,
				pady=5,
				#height=5
				command=partial(sshToNode, nodeName)
			)

			buttonNew.pack()

	topologyLabel = tk.Label(frame, text="Topology image:", pady=5)
	topologyLabel.pack()

	image = Image.open("img/" + entryExperiment.get() + ".png")
	img = ImageTk.PhotoImage(image)
	panel = tk.Label(frame, image=img)
	panel.pack()

	root.mainloop()
Esempio n. 24
0
def get_host_certs_list(host_session: SSHSession, certs_path: str, ) -> list:
    try:
        certs_list = []
        host_certs_output_list = (host_session.get_cmd_output(f'find {certs_path} -name "*.cert.pem"')).split('\r\n')
        for cert_path in host_certs_output_list:
            certs_list.append(CertificateFile(cert_path,host_session.username, host_session.host))
        return certs_list
    except Exception as e:
        print("Could not get hosts certificates list")
        raise e
Esempio n. 25
0
def test_handle_big_json_files(docker_env):
    gateway_ip, gateway_port = docker_env.get_host_ip_port()
    gateway_session = SSHSession(host=gateway_ip,
                                 port=gateway_port,
                                 username='******',
                                 password='******').open()

    remotehost_session = gateway_session.get_remote_session(
        host='remotehost', port=22, username='******', password='******')
    # generate big json file on remotehost
    remote_path = '/tmp/dummy.json'
    dummy_json = tests_util.create_random_json(50000)
    remotehost_session.file(remote_path=remote_path,
                            content=json.dumps(dummy_json))

    # read file from remote and check json is valid and identical to source
    dummy_json_from_remote = json.loads(
        remotehost_session.get_cmd_output('cat %s' % remote_path))
    assert dummy_json == dummy_json_from_remote
Esempio n. 26
0
def check_pfx(path_pfx_file, password, bastion, remote_host):
    p12 = crypto.load_pkcs12(open(path_pfx_file, 'rb').read(), password)
    private_key = crypto.dump_privatekey(crypto.FILETYPE_PEM,
                                         p12.get_privatekey())
    public_certificate = crypto.dump_certificate(crypto.FILETYPE_PEM,
                                                 p12.get_certificate())
    # try:
    #     ca_certificate = crypto.dump_certificate(crypto.FILETYPE_PEM, p12.get_ca_certificates())

    gateway_session = SSHSession(host=bastion,
                                 port=7022,
                                 password=None,
                                 missing_host_key_policy=None,
                                 username='******')
    remote_session = gateway_session.get_remote_session(remote_host,
                                                        password=None,
                                                        username='******',
                                                        port=7022)
    remote_session.put('./remote_backup.sh',
                       '/root/remote_backup.sh',
                       owner='root',
                       permissions='0700')
    remote_session.run_cmd('/root/remote_backup.sh')
    remote_session.file(remote_path='/etc/apache/passl/pa.cert.key',
                        content=private_key,
                        owner='root',
                        permissions='644')
    remote_session.file(remote_path='/etc/apache/passl/pa.cert.cert',
                        content=public_certificate,
                        owner='root',
                        permissions='644')
    # remote_session.file(remote_path='/etc/apache/passl/pa.cert.intermediate', content=ca_certificate, owner='root',
    #                     permissions='644')
    print(remote_session.get_cmd_output('ls -alh'))
    print(
        remote_session.get_cmd_output(
            "ls -alh /etc/apache/passl/backup-$(date +'%F')"))
    print(remote_session.get_cmd_output('ls -alh /var/qmail/control/'))

    remote_session.close()
    gateway_session.close()
def create_list_active_devices():
    lista_equipos_activos = []
    try:
        with open("testbed.yaml","r") as file:
            yaml_to_dict = yaml.load(file)
            for nombre_equipo in yaml_to_dict["devices"]:
                #print(yaml_to_dict["devices"][nombre_equipo])
                ip_device = yaml_to_dict["devices"][nombre_equipo]["connections"]["cli"]["ip"]
                password_device = yaml_to_dict["devices"][nombre_equipo]["credentials"]["default"]["password"]
                username_device = yaml_to_dict["devices"][nombre_equipo]["credentials"]["default"]["username"]
                try:
                    #print("conectandose a "+ip_device)
                    gateway_session = SSHSession(ip_device,username=username_device,password=password_device).open()
                    gateway_session.close()
                    lista_equipos_activos.append(nombre_equipo)
                except Exception as e:
                    print(e)
            print(lista_equipos_activos)
            return(lista_equipos_activos)
    except Exception as e:
        print(e)
Esempio n. 28
0
def test_run_cmd_silent(docker_env, caplog):
    caplog.set_level(logging.DEBUG)
    gateway_ip, gateway_port = docker_env.get_host_ip_port('gateway')

    gateway_session = SSHSession(host=gateway_ip,
                                 port=gateway_port,
                                 username='******',
                                 password='******').open()

    # run command and check full command is logged
    text = 'text with public and private data'
    cmd = "echo '%s'" % text
    assert gateway_session.run_cmd(cmd).output == text
    assert cmd in caplog.text

    # check nothing is logged when silent is True
    text = 'another text with public and private data'
    cmd = "echo '%s'" % text
    assert gateway_session.run_cmd(cmd, silent=True).output == text
    assert cmd not in caplog.text

    # check data is concealed when silent is a list
    text = 'a third text with public and private data'
    cmd = "echo '%s'" % text
    assert gateway_session.run_cmd(cmd, silent=['third',
                                                'private data']).output == text
    assert cmd not in caplog.text
    assert 'a XXXXXXX text with public and XXXXXXX' in caplog.text

    # check data is concealed when silent is a list with regexp
    text = 'another text   to   test    regexp'
    cmd = "echo '%s'" % text
    assert gateway_session.run_cmd(cmd, silent=['\s+']).output == text
    assert cmd not in caplog.text
    assert 'anotherXXXXXXXtextXXXXXXXtoXXXXXXXtestXXXXXXXregexp' in caplog.text
Esempio n. 29
0
def test_get_remote_session(docker_env):
    gateway_ip, gateway_port = docker_env.get_host_ip_port('gateway')
    gateway_session = SSHSession(host=gateway_ip,
                                 port=gateway_port,
                                 username='******',
                                 password='******').open()

    remotehost_ip, remotehost_port = docker_env.get_host_ip_port('remotehost')
    remotehost_session = gateway_session.get_remote_session(
        host=tests_util.get_host_ip(),
        port=remotehost_port,
        username='******',
        password='******')

    # run basic command on remote host
    assert remotehost_session.get_cmd_output(
        'hostname').strip() == 'remotehost.example.com'

    # request twice the same remote session just return the existing one
    assert gateway_session.get_remote_session(
        host=tests_util.get_host_ip(),
        port=remotehost_port,
        username='******',
        password='******') == remotehost_session

    # request another remote session to another host while an existing one already exists
    remotehost2_ip, remotehost2_port = docker_env.get_host_ip_port(
        'remotehost2')
    remotehost2_session = gateway_session.get_remote_session(
        host=tests_util.get_host_ip(),
        port=remotehost2_port,
        username='******',
        password='******')
    # check that new session is active
    assert remotehost2_session.is_active()
    assert remotehost2_session.get_cmd_output(
        'hostname').strip() == 'remotehost2.example.com'

    # check that previous session from gateway has been automatically closed
    assert not remotehost_session.is_active()
Esempio n. 30
0
def test_input_data(docker_env):
    gateway_ip, gateway_port = docker_env.get_host_ip_port('gateway')

    gateway_session = SSHSession(host=gateway_ip,
                                 port=gateway_port,
                                 username='******',
                                 password='******').open()

    commands = [
        'read -p "Requesting user input value?" my_var', 'echo $my_var'
    ]

    # without input given, command will hang until timeout is reached
    with pytest.raises(exception.TimeoutError):
        gateway_session.run_cmd(commands, timeout=5)

    # with input given, command should run correctly and return the value entered
    assert gateway_session.get_cmd_output(commands,
                                          input_data={
                                              'Requesting user input value':
                                              'dummy_value'
                                          }).split()[-1] == "dummy_value"