Example #1
0
def test():
    """Perform ls and copy file with SSHClient on localhost"""
    client = SSHClient('localhost')
    channel, host, stdout, stderr = client.exec_command('ls -ltrh')
    for line in stdout:
        pprint(line.strip())
    client.copy_file('../test', 'test_dir/test')
Example #2
0
 def test_ssh_client_directory(self):
     """Tests copying directories with SSH client. Copy all the files from
     local directory to server, then make sure they are all present."""
     test_file_data = 'test'
     local_test_path = 'directory_test'
     remote_test_path = 'directory_test_copied'
     for path in [local_test_path, remote_test_path]:
         try:
             shutil.rmtree(path)
         except OSError:
             pass
     os.mkdir(local_test_path)
     remote_file_paths = []
     for i in range(0, 10):
         local_file_path = os.path.join(local_test_path, 'foo' + str(i))
         remote_file_path = os.path.join(remote_test_path, 'foo' + str(i))
         remote_file_paths.append(remote_file_path)
         test_file = open(local_file_path, 'w')
         test_file.write(test_file_data)
         test_file.close()
     client = SSHClient(self.host, port=self.listen_port,
                        pkey=self.user_key)
     client.copy_file(local_test_path, remote_test_path, recurse=True)
     for path in remote_file_paths:
         self.assertTrue(os.path.isfile(path))
     shutil.rmtree(local_test_path)
     shutil.rmtree(remote_test_path)
Example #3
0
 def test_ssh_client_pty(self):
     """Test that running command sans shell works as expected
     and that shell commands fail accordingly"""
     client = SSHClient(self.host,
                        port=self.listen_port,
                        pkey=self.user_key)
     channel, host, stdout, stderr = client.exec_command(self.fake_cmd,
                                                         use_shell=False)
     output = list(stdout)
     stderr = list(stderr)
     expected = []
     exit_code = channel.recv_exit_status()
     self.assertEqual(expected,
                      output,
                      msg="Got unexpected command output - %s" % (output, ))
     self.assertTrue(
         exit_code == 127,
         msg="Expected cmd not found error code 127, got %s instead" %
         (exit_code, ))
     channel, host, stdout, stderr = client.exec_command('id',
                                                         use_shell=False)
     output = list(stdout)
     exit_code = channel.recv_exit_status()
     self.assertTrue(output,
                     msg="Got no output from cmd executed without shell")
     self.assertTrue(
         exit_code == 0,
         msg="Cmd executed with shell failed with error code %s" %
         (exit_code, ))
     del client
Example #4
0
 def test_ssh_client_local_directory(self):
     """Tests copying directories with SSH client. Copy all the files from
     local directory to server, then make sure they are all present."""
     test_file_data = 'test'
     local_test_path = 'directory_test'
     remote_test_path = 'directory_test_copied'
     for path in [local_test_path, remote_test_path]:
         try:
             shutil.rmtree(path)
         except OSError:
             pass
     os.mkdir(local_test_path)
     remote_file_paths = []
     for i in range(0, 10):
         local_file_path = os.path.join(local_test_path, 'foo' + str(i))
         remote_file_path = os.path.join(remote_test_path, 'foo' + str(i))
         remote_file_paths.append(remote_file_path)
         test_file = open(local_file_path, 'w')
         test_file.write(test_file_data)
         test_file.close()
     client = SSHClient(self.host,
                        port=self.listen_port,
                        pkey=self.user_key)
     client.copy_file(local_test_path, remote_test_path, recurse=True)
     for path in remote_file_paths:
         self.assertTrue(os.path.isfile(path))
     shutil.rmtree(local_test_path)
     shutil.rmtree(remote_test_path)
Example #5
0
def test():
    """Perform ls and copy file with SSHClient on localhost"""
    client = SSHClient('localhost')
    channel, host, stdout, stderr = client.exec_command('ls -ltrh')
    for line in stdout:
        print line.strip()
    client.copy_file('../test', 'test_dir/test')
Example #6
0
 def test_ssh_client_utf_encoding(self):
     """Test that unicode output works"""
     client = SSHClient(self.host, port=self.listen_port,
                        pkey=self.user_key)
     expected = [u'é']
     cmd = u"echo 'é'"
     channel, host, stdout, stderr, stdin = client.exec_command(cmd)
     output = list(stdout)
     self.assertEqual(expected, output,
                      msg="Got unexpected unicode output %s - expected %s" % (
                          output, expected,))
     del client
 def test_ssh_client_mkdir_single(self):
     """Test SFTP mkdir of SSHClient"""
     remote_dir = "remote_test_dir1"
     try:
         shutil.rmtree(remote_dir)
     except OSError:
         pass
     client = SSHClient(self.host, port=self.listen_port, pkey=self.user_key)
     client.mkdir(client._make_sftp(), remote_dir)
     self.assertTrue(os.path.isdir(remote_dir), msg="SFTP recursive mkdir failed")
     shutil.rmtree(remote_dir)
     del client
 def test_ssh_client_mkdir_recursive(self):
     """Test SFTP mkdir of SSHClient"""
     base_path = "remote_test_dir1"
     remote_dir = os.path.sep.join([base_path, "remote_test_dir2", "remote_test_dir3"])
     try:
         shutil.rmtree(base_path)
     except OSError:
         pass
     client = SSHClient(self.host, port=self.listen_port, pkey=self.user_key)
     client.mkdir(client._make_sftp(), remote_dir)
     self.assertTrue(os.path.isdir(remote_dir), msg="SFTP recursive mkdir failed")
     shutil.rmtree(base_path)
     del client
Example #9
0
 def test_ssh_client_mkdir_single(self):
     """Test SFTP mkdir of SSHClient"""
     remote_dir = 'remote_test_dir1'
     try:
         shutil.rmtree(remote_dir)
     except OSError:
         pass
     client = SSHClient(self.host, port=self.listen_port,
                        pkey=self.user_key)
     client.mkdir(client._make_sftp(), remote_dir)
     self.assertTrue(os.path.isdir(remote_dir),
                     msg="SFTP recursive mkdir failed")
     shutil.rmtree(remote_dir)
     del client
 def test_ssh_agent_authentication(self):
     """Test authentication via SSH agent.
     Do not provide public key to use when creating SSHClient,
     instead override the client's agent with our own fake SSH agent,
     add our to key to agent and try to login to server.
     Key should be automatically picked up from the overriden agent"""
     agent = FakeAgent()
     agent.add_key(USER_KEY)
     client = SSHClient(self.host, port=self.listen_port, _agent=agent)
     channel, host, stdout, stderr = client.exec_command(self.fake_cmd)
     channel.close()
     output = list(stdout)
     stderr = list(stderr)
     expected = [self.fake_resp]
     self.assertEqual(expected, output, msg="Got unexpected command output - %s" % (output,))
     del client
Example #11
0
 def test_openssh_config_missing(self):
     client = SSHClient(self.host,
                        port=self.listen_port,
                        pkey=self.user_key,
                        _openssh_config_file='fake',
                        num_retries=1)
     self.assertTrue(client)
Example #12
0
 def test_openssh_config(self):
     """Test reading and using OpenSSH config file"""
     config_file = tempfile.NamedTemporaryFile()
     _host = "127.0.0.2"
     _user = "******"
     _listen_socket = make_socket(_host)
     _server = start_server(_listen_socket)
     _port = _listen_socket.getsockname()[1]
     _key = USER_KEY_PATH
     content = [
         ("""Host %s\n""" % (_host, )),
         ("""  User %s\n""" % (_user, )),
         ("""  Port %s\n""" % (_port, )),
         ("""  IdentityFile %s\n""" % (_key, )),
     ]
     config_file.writelines([s.encode('utf-8') for s in content])
     config_file.flush()
     host, user, port, pkey = utils.read_openssh_config(
         _host, config_file=config_file.name)
     client = SSHClient(_host, _openssh_config_file=config_file.name)
     config_file.close()
     self.assertEqual(host, _host)
     self.assertEqual(user, _user)
     self.assertEqual(port, _port)
     self.assertTrue(pkey)
     self.assertEqual(client.host, _host)
     self.assertEqual(client.user, _user)
     self.assertEqual(client.port, _port)
     self.assertTrue(client.pkey)
     del _server, _listen_socket
Example #13
0
 def test_ssh_agent_authentication(self):
     """Test authentication via SSH agent.
     Do not provide public key to use when creating SSHClient,
     instead override the client's agent with our own fake SSH agent,
     add our to key to agent and try to login to server.
     Key should be automatically picked up from the overriden agent"""
     agent = FakeAgent()
     agent.add_key(USER_KEY)
     client = SSHClient(self.host, port=self.listen_port, agent=agent)
     channel, host, stdout, stderr = client.exec_command(self.fake_cmd)
     output = list(stdout)
     stderr = list(stderr)
     expected = [self.fake_resp]
     self.assertEqual(expected,
                      output,
                      msg="Got unexpected command output - %s" % (output, ))
     del client
 def test_ssh_client_mkdir_recursive_abspath(self):
     """Test SFTP mkdir of SSHClient with absolute path
     
     Absolute SFTP paths resolve under the users' home directory,
     not the root filesystem
     """
     base_path = "tmp"
     remote_dir = os.path.sep.join([base_path, "remote_test_dir2", "remote_test_dir3"])
     try:
         shutil.rmtree(base_path)
     except OSError:
         pass
     client = SSHClient(self.host, port=self.listen_port, pkey=self.user_key)
     client.mkdir(client._make_sftp(), "/" + remote_dir)
     self.assertTrue(os.path.isdir(remote_dir), msg="SFTP recursive mkdir failed")
     shutil.rmtree(base_path)
     del client
Example #15
0
 def test_ssh_client_mkdir_recursive(self):
     """Test SFTP mkdir of SSHClient"""
     base_path = 'remote_test_dir1'
     remote_dir = os.path.sep.join(
         [base_path, 'remote_test_dir2', 'remote_test_dir3'])
     try:
         shutil.rmtree(base_path)
     except OSError:
         pass
     client = SSHClient(self.host,
                        port=self.listen_port,
                        pkey=self.user_key)
     client.mkdir(client._make_sftp(), remote_dir)
     self.assertTrue(os.path.isdir(remote_dir),
                     msg="SFTP recursive mkdir failed")
     shutil.rmtree(base_path)
     del client
Example #16
0
    def test_ssh_client_sftp(self):
        """Test SFTP features of SSHClient. Copy local filename to server,
        check that data in both files is the same, make new directory on
        server, remove files and directory."""
        test_file_data = 'test'
        local_filename = 'test_file'
        remote_test_dir, remote_filename = 'remote_test_dir', 'test_file_copy'
        remote_filename = os.path.sep.join([remote_test_dir, remote_filename])
        remote_dir = 'remote_dir'
        test_file = open(local_filename, 'w')
        test_file.writelines([test_file_data + os.linesep])
        test_file.close()
        client = SSHClient(self.host,
                           port=self.listen_port,
                           pkey=self.user_key)
        client.copy_file(local_filename, remote_filename)
        self.assertTrue(os.path.isdir(remote_test_dir),
                        msg="SFTP create remote directory failed")
        self.assertTrue(os.path.isfile(remote_filename),
                        msg="SFTP copy failed")
        copied_file = open(remote_filename, 'r')
        copied_file_data = copied_file.readlines()[0].strip()
        copied_file.close()
        self.assertEqual(test_file_data,
                         copied_file_data,
                         msg="Data in destination file %s does \
not match source %s" % (copied_file_data, test_file_data))
        for filepath in [local_filename, remote_filename]:
            os.unlink(filepath)
        client.mkdir(client._make_sftp(), remote_dir)
        self.assertTrue(os.path.isdir(remote_dir))
        for dirpath in [remote_dir, remote_test_dir]:
            os.rmdir(dirpath)
        del client
Example #17
0
 def test_ssh_client_copy_remote_directory(self):
     """Tests copying a remote directory to the localhost"""
     remote_test_directory = 'remote_test_dir'
     local_test_directory = 'local_test_dir'
     for path in [remote_test_directory, local_test_directory]:
         try:
             shutil.rmtree(path)
         except OSError:
             pass
     os.mkdir(remote_test_directory)
     test_files = []
     test_file_data = 'test'
     for i in range(0, 10):
         file_name = 'foo' + str(i)
         test_files.append(file_name)
         file_path = os.path.join(remote_test_directory, file_name)
         test_file = open(file_path, 'w')
         test_file.write(test_file_data)
         test_file.close()
     client = SSHClient(self.host,
                        port=self.listen_port,
                        pkey=self.user_key)
     try:
         self.assertRaises(ValueError, client.copy_remote_file,
                           remote_test_directory, local_test_directory)
         client.copy_remote_file(remote_test_directory,
                                 local_test_directory,
                                 recurse=True)
         for test_file in test_files:
             file_path = os.path.join(local_test_directory, test_file)
             self.assertTrue(os.path.isfile(file_path))
             copied_file = open(file_path, 'r')
             copied_file_data = copied_file.read().strip()
             copied_file.close()
             self.assertEqual(test_file_data,
                              copied_file_data,
                              msg="Data in destination file %s does "
                              "not match source %s" %
                              (copied_file_data, test_file_data))
     finally:
         shutil.rmtree(remote_test_directory)
         shutil.rmtree(local_test_directory)
Example #18
0
 def test_ssh_client_mkdir_recursive_abspath(self):
     """Test SFTP mkdir of SSHClient with absolute path
     
     Absolute SFTP paths resolve under the users' home directory,
     not the root filesystem
     """
     base_path = 'tmp'
     remote_dir = os.path.sep.join(
         [base_path, 'remote_test_dir2', 'remote_test_dir3'])
     try:
         shutil.rmtree(base_path)
     except OSError:
         pass
     client = SSHClient(self.host,
                        port=self.listen_port,
                        pkey=self.user_key)
     client.mkdir(client._make_sftp(), '/' + remote_dir)
     self.assertTrue(os.path.isdir(remote_dir),
                     msg="SFTP recursive mkdir failed")
     shutil.rmtree(base_path)
     del client
Example #19
0
    def test_ssh_client_sftp(self):
        """Test SFTP features of SSHClient. Copy local filename to server,
        check that data in both files is the same, make new directory on
        server, remove files and directory."""
        test_file_data = 'test'
        local_filename = 'test_file'
        remote_test_dir, remote_filename = 'remote_test_dir', 'test_file_copy'
        remote_filename = os.path.sep.join([remote_test_dir, remote_filename])
        remote_dir = 'remote_dir'
        test_file = open(local_filename, 'w')
        test_file.writelines([test_file_data + os.linesep])
        test_file.close()
        server = start_server({ self.fake_cmd : self.fake_resp },
                              self.listen_socket)
        client = SSHClient('127.0.0.1', port=self.listen_port,
                           pkey=self.user_key)
        client.copy_file(local_filename, remote_filename)
        self.assertTrue(os.path.isdir(remote_test_dir),
                        msg="SFTP create remote directory failed")
        self.assertTrue(os.path.isfile(remote_filename),
                        msg="SFTP copy failed")
        copied_file = open(remote_filename, 'r')
        copied_file_data = copied_file.readlines()[0].strip()
        copied_file.close()
        self.assertEqual(test_file_data, copied_file_data,
                         msg="Data in destination file %s does \
not match source %s" % (copied_file_data, test_file_data))
        for filepath in [local_filename, remote_filename]:
            os.unlink(filepath)
        client.mkdir(client._make_sftp(), remote_dir)
        self.assertTrue(os.path.isdir(remote_dir))
        for dirpath in [remote_dir, remote_test_dir]:
            os.rmdir(dirpath)
        del client
        server.join()
Example #20
0
def open_movies():
    choices = list(values)

    for x in range(len(hosts)):
        one_client = SSHClient('client' + str(x))
        prompt = "Type "
        for v in choices:
            prompt += v + ", "
        prompt = prompt[:-2]
        prompt += " :"
        choice = get_valid_input(prompt)
        choices.remove(choice.lower())
        num = random.randint(0, 2)
        command = "~/dbuscontrol.sh stop"
        one_client.exec_command(command)
        command = "omxplayer /mnt/usb/media/" + choice + "/mov_" + str(
            num) + ".mp4 --aspect-mode=stretch --loop"
        one_client.exec_command(command)
        print("Opening a " + choice + " movie, number " + str(num) +
              " on client " + str(x) + "!")
    time.sleep(15)
    print("done playing movie")
    cmds = [
        "~/dbuscontrol.sh stop", "sleep 2",
        "omxplayer /mnt/usb/media/intro.mp4 --aspect-mode=stretch --loop"
    ]
    for cmd in cmds:
        client.run_command(cmd, stop_on_errors=False)
    next = raw_input("Hit return to continue or 'Q' to quit:")
    if next == "Q":
        print("quitting")
    else:
        open_movies()
Example #21
0
 def scp(self, src, dst):
     """Copy file to hosts using Parallel SSH copy_file"""
     sites = ['{}.iot-lab.info'.format(site) for site in self.groups]
     for site in sites:
         try:
             ssh = SSHClient(site, user=self.config_ssh['user'])
         except AuthenticationException:
             raise OpenA8SshAuthenticationException(site)
         else:
             with SCPClient(ssh.client.get_transport()) as scp:
                 scp.put(src, dst)
             ssh.client.close()
     return
Example #22
0
 def test_ssh_client_pty(self):
     """Test that we get a new pty for our non-interactive SSH sessions"""
     client = SSHClient(self.host, port=self.listen_port,
                        pkey=self.user_key)
     channel = client.client.get_transport().open_session()
     self.assertFalse(channel.event.is_set(),
                      msg="Got pty without requesting it")
     channel.get_pty()
     self.assertTrue(channel.event.is_set(),
                     msg="Requested pty but got none")
     channel.close()
     del channel
     del client
Example #23
0
 def test_ssh_client_shell(self):
     """Test that running command sans shell works as expected
     and that shell commands fail accordingly"""
     client = SSHClient(self.host, port=self.listen_port,
                        pkey=self.user_key)
     channel, host, stdout, stderr, stdin = client.exec_command(self.fake_cmd, use_shell=False)
     output = list(stdout)
     stderr = list(stderr)
     expected = []
     exit_code = channel.recv_exit_status()
     self.assertEqual(expected, output,
                      msg = "Got unexpected command output - %s" % (output,))
     self.assertTrue(exit_code == 127,
                     msg="Expected cmd not found error code 127, got %s instead" % (
                         exit_code,))
     channel, host, stdout, stderr, stdin = client.exec_command('id', use_shell=False)
     output = list(stdout)
     exit_code = channel.recv_exit_status()
     self.assertTrue(output,
                     msg="Got no output from cmd executed without shell")
     self.assertTrue(exit_code==0,
                     msg="Cmd executed with shell failed with error code %s" % (
                         exit_code,))
     del client
def open_movie(choice, clientID):
    one_client = SSHClient(hosts[clientID])
    num = random.randint(0, 2)
    command = "~/dbuscontrol.sh stop"
    one_client.exec_command(command)
    command = "omxplayer /mnt/usb/media/" + choice + "/mov_" + str(
        num) + ".mp4 --aspect-mode=stretch --loop"
    one_client.exec_command(command)
    print("Opening a " + choice + " movie, number " + str(num) + " on " +
          hosts[clientID] + "!")
Example #25
0
 def test_ssh_client_pty(self):
     """Test that we get a new pty for our non-interactive SSH sessions"""
     server = start_server({self.fake_cmd: self.fake_resp},
                           self.listen_socket)
     client = SSHClient('127.0.0.1',
                        port=self.listen_port,
                        pkey=self.user_key)
     channel = client.client.get_transport().open_session()
     self.assertFalse(channel.event.is_set(),
                      msg="Got pty without requesting it")
     channel.get_pty()
     self.assertTrue(channel.event.is_set(),
                     msg="Requested pty but got none")
     channel.close()
     del channel
     del client
     server.join()
Example #26
0
    def _try_connection(self, node, site):
        dev_null = sys.stderr = open('/dev/null', 'w')
        result = False
        try:
            client = SSHClient(node,
                               user='******',
                               proxy_host='{}.iot-lab.info'.format(site),
                               proxy_user=self.config_ssh['user'])
        except AuthenticationException:
            raise OpenA8SshAuthenticationException(site)
        except ConnectionErrorException:
            if self.verbose:
                print("Node {} not ready.".format(_node_fqdn(node, site)))
        else:
            client.client.close()
            if self.verbose:
                print("Node {} ready.".format(_node_fqdn(node, site)))
            result = True
        finally:
            dev_null.close()

        return result
Example #27
0
 def test_ssh_client(self):
     try:
         client = SSHClient('testy')
     except UnknownHostException, e:
         print e
         return
import random
import sys
import time

output = []
hosts = [
    'client0.local', 'client1.local', 'client2.local', 'client3.local',
    'client4.local'
]
client = ParallelSSHClient(hosts)

ssh_clients = []

#open a ssh connection for each host
for host in hosts:
    one_client = SSHClient(host, user="******")
    print("Connecting to ", host)
    #time.sleep(.5)
    ssh_clients.append(one_client)


def open_movie(choice, clientID):
    num = random.randint(1, 30)
    num = "%02d" % (num, )
    command = "~/dbuscontrol.sh stop"
    ssh_clients[clientID].exec_command(command, user="******")
    command = "omxplayer /mnt/usb/media/" + choice + "/mov_" + str(
        num) + ".mp4 --aspect-mode=stretch --amp=1000 --no-osd"
    ssh_clients[clientID].exec_command(command, user="******")
    print("Opening a " + choice + " movie, number " + str(num) + " on " +
          hosts[clientID] + "!\r")