123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434 |
- # -*- coding: utf-8 -*-
- """
- :codeauthor: :email:`Daniel Wallace <dwallace@saltstack.com`
- """
- from __future__ import absolute_import, print_function, unicode_literals
- import os
- import re
- import shutil
- import tempfile
- import salt.config
- import salt.roster
- import salt.utils.files
- import salt.utils.path
- import salt.utils.thin
- import salt.utils.yaml
- from salt.client import ssh
- from tests.support.case import ShellCase
- from tests.support.helpers import slowTest
- from tests.support.mock import MagicMock, call, patch
- from tests.support.runtests import RUNTIME_VARS
- from tests.support.unit import TestCase, skipIf
- ROSTER = """
- localhost:
- host: 127.0.0.1
- port: 2827
- self:
- host: 0.0.0.0
- port: 42
- """
- @skipIf(not salt.utils.path.which("ssh"), "No ssh binary found in path")
- class SSHPasswordTests(ShellCase):
- @slowTest
- def test_password_failure(self):
- """
- Check password failures when trying to deploy keys
- """
- opts = salt.config.client_config(self.get_config_file_path("master"))
- opts["list_hosts"] = False
- opts["argv"] = ["test.ping"]
- opts["selected_target_option"] = "glob"
- opts["tgt"] = "localhost"
- opts["arg"] = []
- roster = os.path.join(RUNTIME_VARS.TMP_CONF_DIR, "roster")
- handle_ssh_ret = [
- {
- "localhost": {
- "retcode": 255,
- "stderr": "Permission denied (publickey).\r\n",
- "stdout": "",
- }
- },
- ]
- expected = {"localhost": "Permission denied (publickey)"}
- display_output = MagicMock()
- with patch(
- "salt.roster.get_roster_file", MagicMock(return_value=roster)
- ), patch(
- "salt.client.ssh.SSH.handle_ssh", MagicMock(return_value=handle_ssh_ret)
- ), patch(
- "salt.client.ssh.SSH.key_deploy", MagicMock(return_value=expected)
- ), patch(
- "salt.output.display_output", display_output
- ):
- client = ssh.SSH(opts)
- ret = next(client.run_iter())
- with self.assertRaises(SystemExit):
- client.run()
- display_output.assert_called_once_with(expected, "nested", opts)
- self.assertIs(ret, handle_ssh_ret[0])
- class SSHRosterDefaults(TestCase):
- def test_roster_defaults_flat(self):
- """
- Test Roster Defaults on the flat roster
- """
- tempdir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
- expected = {
- "self": {"host": "0.0.0.0", "user": "daniel", "port": 42},
- "localhost": {"host": "127.0.0.1", "user": "daniel", "port": 2827},
- }
- try:
- root_dir = os.path.join(tempdir, "foo", "bar")
- os.makedirs(root_dir)
- fpath = os.path.join(root_dir, "config")
- with salt.utils.files.fopen(fpath, "w") as fp_:
- fp_.write(
- """
- roster_defaults:
- user: daniel
- """
- )
- opts = salt.config.master_config(fpath)
- with patch("salt.roster.get_roster_file", MagicMock(return_value=ROSTER)):
- with patch(
- "salt.template.compile_template",
- MagicMock(return_value=salt.utils.yaml.safe_load(ROSTER)),
- ):
- roster = salt.roster.Roster(opts=opts)
- self.assertEqual(roster.targets("*", "glob"), expected)
- finally:
- if os.path.isdir(tempdir):
- shutil.rmtree(tempdir)
- class SSHSingleTests(TestCase):
- def setUp(self):
- self.tmp_cachedir = tempfile.mkdtemp(dir=RUNTIME_VARS.TMP)
- self.argv = [
- "ssh.set_auth_key",
- "root",
- "hobn+amNAXSBTiOXEqlBjGB...rsa root@master",
- ]
- self.opts = {
- "argv": self.argv,
- "__role": "master",
- "cachedir": self.tmp_cachedir,
- "extension_modules": os.path.join(self.tmp_cachedir, "extmods"),
- }
- self.target = {
- "passwd": "abc123",
- "ssh_options": None,
- "sudo": False,
- "identities_only": False,
- "host": "login1",
- "user": "root",
- "timeout": 65,
- "remote_port_forwards": None,
- "sudo_user": "",
- "port": "22",
- "priv": "/etc/salt/pki/master/ssh/salt-ssh.rsa",
- }
- def test_single_opts(self):
- """ Sanity check for ssh.Single options
- """
- single = ssh.Single(
- self.opts,
- self.opts["argv"],
- "localhost",
- mods={},
- fsclient=None,
- thin=salt.utils.thin.thin_path(self.opts["cachedir"]),
- mine=False,
- **self.target
- )
- self.assertEqual(single.shell._ssh_opts(), "")
- self.assertEqual(
- single.shell._cmd_str("date +%s"),
- "ssh login1 "
- "-o KbdInteractiveAuthentication=no -o "
- "PasswordAuthentication=yes -o ConnectTimeout=65 -o Port=22 "
- "-o IdentityFile=/etc/salt/pki/master/ssh/salt-ssh.rsa "
- "-o User=root date +%s",
- )
- def test_run_with_pre_flight(self):
- """
- test Single.run() when ssh_pre_flight is set
- and script successfully runs
- """
- target = self.target.copy()
- target["ssh_pre_flight"] = os.path.join(RUNTIME_VARS.TMP, "script.sh")
- single = ssh.Single(
- self.opts,
- self.opts["argv"],
- "localhost",
- mods={},
- fsclient=None,
- thin=salt.utils.thin.thin_path(self.opts["cachedir"]),
- mine=False,
- **target
- )
- cmd_ret = ("Success", "", 0)
- mock_flight = MagicMock(return_value=cmd_ret)
- mock_cmd = MagicMock(return_value=cmd_ret)
- patch_flight = patch("salt.client.ssh.Single.run_ssh_pre_flight", mock_flight)
- patch_cmd = patch("salt.client.ssh.Single.cmd_block", mock_cmd)
- patch_exec_cmd = patch(
- "salt.client.ssh.shell.Shell.exec_cmd", return_value=("", "", 1)
- )
- patch_os = patch("os.path.exists", side_effect=[True])
- with patch_os, patch_flight, patch_cmd, patch_exec_cmd:
- ret = single.run()
- mock_cmd.assert_called()
- mock_flight.assert_called()
- assert ret == cmd_ret
- def test_run_with_pre_flight_stderr(self):
- """
- test Single.run() when ssh_pre_flight is set
- and script errors when run
- """
- target = self.target.copy()
- target["ssh_pre_flight"] = os.path.join(RUNTIME_VARS.TMP, "script.sh")
- single = ssh.Single(
- self.opts,
- self.opts["argv"],
- "localhost",
- mods={},
- fsclient=None,
- thin=salt.utils.thin.thin_path(self.opts["cachedir"]),
- mine=False,
- **target
- )
- cmd_ret = ("", "Error running script", 1)
- mock_flight = MagicMock(return_value=cmd_ret)
- mock_cmd = MagicMock(return_value=cmd_ret)
- patch_flight = patch("salt.client.ssh.Single.run_ssh_pre_flight", mock_flight)
- patch_cmd = patch("salt.client.ssh.Single.cmd_block", mock_cmd)
- patch_exec_cmd = patch(
- "salt.client.ssh.shell.Shell.exec_cmd", return_value=("", "", 1)
- )
- patch_os = patch("os.path.exists", side_effect=[True])
- with patch_os, patch_flight, patch_cmd, patch_exec_cmd:
- ret = single.run()
- mock_cmd.assert_not_called()
- mock_flight.assert_called()
- assert ret == cmd_ret
- def test_run_with_pre_flight_script_doesnot_exist(self):
- """
- test Single.run() when ssh_pre_flight is set
- and the script does not exist
- """
- target = self.target.copy()
- target["ssh_pre_flight"] = os.path.join(RUNTIME_VARS.TMP, "script.sh")
- single = ssh.Single(
- self.opts,
- self.opts["argv"],
- "localhost",
- mods={},
- fsclient=None,
- thin=salt.utils.thin.thin_path(self.opts["cachedir"]),
- mine=False,
- **target
- )
- cmd_ret = ("Success", "", 0)
- mock_flight = MagicMock(return_value=cmd_ret)
- mock_cmd = MagicMock(return_value=cmd_ret)
- patch_flight = patch("salt.client.ssh.Single.run_ssh_pre_flight", mock_flight)
- patch_cmd = patch("salt.client.ssh.Single.cmd_block", mock_cmd)
- patch_exec_cmd = patch(
- "salt.client.ssh.shell.Shell.exec_cmd", return_value=("", "", 1)
- )
- patch_os = patch("os.path.exists", side_effect=[False])
- with patch_os, patch_flight, patch_cmd, patch_exec_cmd:
- ret = single.run()
- mock_cmd.assert_called()
- mock_flight.assert_not_called()
- assert ret == cmd_ret
- def test_run_with_pre_flight_thin_dir_exists(self):
- """
- test Single.run() when ssh_pre_flight is set
- and thin_dir already exists
- """
- target = self.target.copy()
- target["ssh_pre_flight"] = os.path.join(RUNTIME_VARS.TMP, "script.sh")
- single = ssh.Single(
- self.opts,
- self.opts["argv"],
- "localhost",
- mods={},
- fsclient=None,
- thin=salt.utils.thin.thin_path(self.opts["cachedir"]),
- mine=False,
- **target
- )
- cmd_ret = ("", "", 0)
- mock_flight = MagicMock(return_value=cmd_ret)
- mock_cmd = MagicMock(return_value=cmd_ret)
- patch_flight = patch("salt.client.ssh.Single.run_ssh_pre_flight", mock_flight)
- patch_cmd = patch("salt.client.ssh.shell.Shell.exec_cmd", mock_cmd)
- patch_cmd_block = patch("salt.client.ssh.Single.cmd_block", mock_cmd)
- patch_os = patch("os.path.exists", return_value=True)
- with patch_os, patch_flight, patch_cmd, patch_cmd_block:
- ret = single.run()
- mock_cmd.assert_called()
- mock_flight.assert_not_called()
- assert ret == cmd_ret
- def test_execute_script(self):
- """
- test Single.execute_script()
- """
- single = ssh.Single(
- self.opts,
- self.opts["argv"],
- "localhost",
- mods={},
- fsclient=None,
- thin=salt.utils.thin.thin_path(self.opts["cachedir"]),
- mine=False,
- winrm=False,
- **self.target
- )
- exp_ret = ("Success", "", 0)
- mock_cmd = MagicMock(return_value=exp_ret)
- patch_cmd = patch("salt.client.ssh.shell.Shell.exec_cmd", mock_cmd)
- script = os.path.join(RUNTIME_VARS.TMP, "script.sh")
- with patch_cmd:
- ret = single.execute_script(script=script)
- assert ret == exp_ret
- assert mock_cmd.call_count == 2
- assert [
- call("/bin/sh '{0}'".format(script)),
- call("rm '{0}'".format(script)),
- ] == mock_cmd.call_args_list
- def test_shim_cmd(self):
- """
- test Single.shim_cmd()
- """
- single = ssh.Single(
- self.opts,
- self.opts["argv"],
- "localhost",
- mods={},
- fsclient=None,
- thin=salt.utils.thin.thin_path(self.opts["cachedir"]),
- mine=False,
- winrm=False,
- tty=True,
- **self.target
- )
- exp_ret = ("Success", "", 0)
- mock_cmd = MagicMock(return_value=exp_ret)
- patch_cmd = patch("salt.client.ssh.shell.Shell.exec_cmd", mock_cmd)
- patch_send = patch("salt.client.ssh.shell.Shell.send", return_value=("", "", 0))
- patch_rand = patch("os.urandom", return_value=b"5\xd9l\xca\xc2\xff")
- with patch_cmd, patch_rand, patch_send:
- ret = single.shim_cmd(cmd_str="echo test")
- assert ret == exp_ret
- assert [
- call("/bin/sh '$HOME/.35d96ccac2ff.py'"),
- call("rm '$HOME/.35d96ccac2ff.py'"),
- ] == mock_cmd.call_args_list
- def test_run_ssh_pre_flight(self):
- """
- test Single.run_ssh_pre_flight
- """
- target = self.target.copy()
- target["ssh_pre_flight"] = os.path.join(RUNTIME_VARS.TMP, "script.sh")
- single = ssh.Single(
- self.opts,
- self.opts["argv"],
- "localhost",
- mods={},
- fsclient=None,
- thin=salt.utils.thin.thin_path(self.opts["cachedir"]),
- mine=False,
- winrm=False,
- tty=True,
- **target
- )
- exp_ret = ("Success", "", 0)
- mock_cmd = MagicMock(return_value=exp_ret)
- patch_cmd = patch("salt.client.ssh.shell.Shell.exec_cmd", mock_cmd)
- patch_send = patch("salt.client.ssh.shell.Shell.send", return_value=exp_ret)
- exp_tmp = os.path.join(
- tempfile.gettempdir(), os.path.basename(target["ssh_pre_flight"])
- )
- with patch_cmd, patch_send:
- ret = single.run_ssh_pre_flight()
- assert ret == exp_ret
- assert [
- call("/bin/sh '{0}'".format(exp_tmp)),
- call("rm '{0}'".format(exp_tmp)),
- ] == mock_cmd.call_args_list
- @skipIf(salt.utils.platform.is_windows(), "SSH_PY_SHIM not set on windows")
- def test_cmd_run_set_path(self):
- """
- test when set_path is set
- """
- target = self.target
- target["set_path"] = "$PATH:/tmp/path/"
- single = ssh.Single(
- self.opts,
- self.opts["argv"],
- "localhost",
- mods={},
- fsclient=None,
- thin=salt.utils.thin.thin_path(self.opts["cachedir"]),
- mine=False,
- **self.target
- )
- ret = single._cmd_str()
- assert re.search("\\" + target["set_path"], ret)
- @skipIf(salt.utils.platform.is_windows(), "SSH_PY_SHIM not set on windows")
- def test_cmd_run_not_set_path(self):
- """
- test when set_path is not set
- """
- target = self.target
- single = ssh.Single(
- self.opts,
- self.opts["argv"],
- "localhost",
- mods={},
- fsclient=None,
- thin=salt.utils.thin.thin_path(self.opts["cachedir"]),
- mine=False,
- **self.target
- )
- ret = single._cmd_str()
- assert re.search('SET_PATH=""', ret)
|