Пример #1
0
def main(*argv):
    parser = ArgumentParser(usage=USAGE)
    parser.add_argument("-v",
                        "--verbose",
                        action='store_true',
                        default=False,
                        help="more verbose output")
    parser.add_argument("-n",
                        "--dry-run",
                        action='store_true',
                        default=False,
                        help="DEBUG ONLY: minimal interactions with node,"
                        " that are expected to be ON;"
                        "won't check on and off and reset; "
                        "won't load any image on node")
    parser.add_argument("-s",
                        "--speedy",
                        action='store_true',
                        default=False,
                        help="DEBUG ONLY: will only load one image")
    add_selector_arguments(parser)

    args = parser.parse_args(argv)

    selector = selected_selector(args, defaults_to_all=True)
    nightly = Nightly(selector,
                      dry_run=args.dry_run,
                      verbose=args.verbose,
                      speedy=args.speedy)

    # turn off asyncssh info message unless verbose
    if not args.verbose:
        set_log_level(logging.ERROR)

    return 0 if nightly.run() else 1
Пример #2
0
    async def _remote_connection(self,
                                 host: str,
                                 addr: Optional[str] = None,
                                 ) -> "SSHClientConnection":
        if not self.cons.get(host):
            if not addr and host in self.mgr.inventory:
                addr = self.mgr.inventory.get_addr(host)

            if not addr:
                raise OrchestratorError("host address is empty")

            assert self.mgr.ssh_user
            n = self.mgr.ssh_user + '@' + addr
            logger.debug("Opening connection to {} with ssh options '{}'".format(
                n, self.mgr._ssh_options))

            asyncssh.set_log_level('DEBUG')
            asyncssh.set_debug_level(3)

            with self.redirect_log(host, addr):
                try:
                    conn = await asyncssh.connect(addr, username=self.mgr.ssh_user, client_keys=[self.mgr.tkey.name], known_hosts=None, config=[self.mgr.ssh_config_fname], preferred_auth=['publickey'])
                except OSError:
                    raise
                except asyncssh.Error:
                    raise
                except Exception:
                    raise
            self.cons[host] = conn

        self.mgr.offline_hosts_remove(host)
        conn = self.cons.get(host)
        return conn
Пример #3
0
    def test_logging(self):
        """Test AsyncSSH logging"""

        asyncssh.set_log_level('INFO')

        with self.assertLogs(level='INFO') as log:
            logger.info('Test')

        self.assertEqual(len(log.records), 1)
        self.assertEqual(log.records[0].msg, 'Test')
Пример #4
0
    def test_logging(self):
        """Test AsyncSSH logging"""

        asyncssh.set_log_level('INFO')

        with self.assertLogs(level='INFO') as log:
            logger.info('Test')

        self.assertEqual(len(log.records), 1)
        self.assertEqual(log.records[0].msg, 'Test')
Пример #5
0
    def test_connection_log(self):
        """Test connection-level logger"""

        asyncssh.set_log_level('INFO')

        with (yield from self.connect()) as conn:
            with self.assertLogs(level='INFO') as log:
                conn.logger.info('Test')

        self.assertEqual(len(log.records), 1)
        self.assertRegex(log.records[0].msg, r'\[conn=\d+\] Test')
Пример #6
0
    def test_connection_log(self):
        """Test connection-level logger"""

        asyncssh.set_log_level('INFO')

        with (yield from self.connect()) as conn:
            with self.assertLogs(level='INFO') as log:
                conn.logger.info('Test')

        self.assertEqual(len(log.records), 1)
        self.assertRegex(log.records[0].msg, r'\[conn=\d+\] Test')
Пример #7
0
async def start_server():
    asyncssh.set_log_level('DEBUG')
    asyncssh.set_debug_level(2)
    await asyncssh.create_server(MySSHServer,
                                 '',
                                 8022,
                                 server_host_keys=[
                                     '/etc/ssh/ssh_host_ecdsa_key',
                                     '/etc/ssh/ssh_host_rsa_key',
                                 ],
                                 process_factory=handle_client)
Пример #8
0
    def test_packet_logging(self):
        """Test packet logging"""

        asyncssh.set_log_level('DEBUG')
        asyncssh.set_debug_level(3)

        with self.assertLogs(level='DEBUG') as log:
            logger.packet(0, bytes(range(0x10, 0x30)), 'CONTROL')

        self.assertEqual(log.records[0].msg, '[pktid=0] CONTROL\n' +
                         '  00000000: 10 11 12 13 14 15 16 17 18 ' +
                         '19 1a 1b 1c 1d 1e 1f  ................\n' +
                         '  00000010: 20 21 22 23 24 25 26 27 28 ' +
                         '29 2a 2b 2c 2d 2e 2f   !"#$%%&\'()*+,-./')
Пример #9
0
    def test_packet_logging(self):
        """Test packet logging"""

        asyncssh.set_log_level('DEBUG')
        asyncssh.set_debug_level(3)

        with self.assertLogs(level='DEBUG') as log:
            logger.packet(0, bytes(range(0x10, 0x30)), 'CONTROL')

        self.assertEqual(log.records[0].msg, '[pktid=0] CONTROL\n' +
                         '  00000000: 10 11 12 13 14 15 16 17 18 ' +
                         '19 1a 1b 1c 1d 1e 1f  ................\n' +
                         '  00000010: 20 21 22 23 24 25 26 27 28 ' +
                         '29 2a 2b 2c 2d 2e 2f   !"#$%%&\'()*+,-./')
Пример #10
0
def main():
    """Run server here."""

    for logger in [
            logging.getLogger(name) for name in logging.root.manager.loggerDict
    ]:
        logger.setLevel(logging.DEBUG)

    logging.basicConfig(level=logging.DEBUG)
    asyncssh.set_log_level("DEBUG")

    loop = asyncio.get_event_loop()
    loop.run_until_complete(
        start_server(ServerConfig.load(prefix="here"), namespace={}))
    loop.run_forever()
Пример #11
0
    def test_stream_log(self):
        """Test stream-level logger"""

        asyncssh.set_log_level('INFO')

        with (yield from self.connect()) as conn:
            stdin, _, _ = yield from conn.open_session()

            with self.assertLogs(level='INFO') as log:
                stdin.logger.info('Test')

            stdin.write_eof()
            yield from stdin.channel.wait_closed()

        self.assertEqual(len(log.records), 1)
        self.assertRegex(log.records[0].msg, r'\[conn=\d+, chan=0\] Test')
Пример #12
0
    def test_stream_log(self):
        """Test stream-level logger"""

        asyncssh.set_log_level('INFO')

        with (yield from self.connect()) as conn:
            stdin, _, _ = yield from conn.open_session()

            with self.assertLogs(level='INFO') as log:
                stdin.logger.info('Test')

            stdin.write_eof()
            yield from stdin.channel.wait_closed()

        self.assertEqual(len(log.records), 1)
        self.assertRegex(log.records[0].msg, r'\[conn=\d+, chan=0\] Test')
Пример #13
0
def main(args):
    """ Entry Point """
    global ca, config

    logging.basicConfig()
    config = json.load(open(args.config, 'r'))
    asyncssh.set_log_level(config.get('loglevel', 10))

    ca = load_ca(config['ca'])

    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(start_server())
    except (OSError, asyncssh.Error) as exc:
        sys.exit('Error starting server: ' + str(exc))

    loop.run_forever()
Пример #14
0
    def test_channel_log(self):
        """Test channel-level logger"""

        asyncssh.set_log_level('INFO')

        with (yield from self.connect()) as conn:
            for i in range(2):
                chan, _ = yield from conn.create_session(SSHClientSession)

                with self.assertLogs(level='INFO') as log:
                    chan.logger.info('Test')

                chan.write_eof()
                yield from chan.wait_closed()

                self.assertEqual(len(log.records), 1)
                self.assertRegex(log.records[0].msg,
                                 r'\[conn=\d+, chan=%s\] Test' % i)
Пример #15
0
    def test_debug_levels(self):
        """Test log debug levels"""

        asyncssh.set_log_level('DEBUG')

        for debug_level in range(1, 4):
            with self.subTest(debug_level=debug_level):
                asyncssh.set_debug_level(debug_level)

                with self.assertLogs(level='DEBUG') as log:
                    logger.debug1('DEBUG')
                    logger.debug2('DEBUG')
                    logger.packet(None, b'', 'DEBUG')

                self.assertEqual(len(log.records), debug_level)

                for record in log.records:
                    self.assertEqual(record.msg, record.levelname)
Пример #16
0
    def test_process_log(self):
        """Test process-level logger"""

        asyncssh.set_log_level('INFO')

        with (yield from self.connect()) as conn:
            process = yield from conn.create_process()

            with self.assertLogs(level='INFO') as log:
                process.logger.info('Test')

            process.stdin.write_eof()
            yield from process.wait()

        asyncssh.set_log_level('WARNING')

        self.assertEqual(len(log.records), 1)
        self.assertRegex(log.records[0].msg, r'\[conn=\d+, chan=0\] Test')
Пример #17
0
    def test_process_log(self):
        """Test process-level logger"""

        asyncssh.set_log_level('INFO')

        with (yield from self.connect()) as conn:
            process = yield from conn.create_process()

            with self.assertLogs(level='INFO') as log:
                process.logger.info('Test')

            process.stdin.write_eof()
            yield from process.wait()

        asyncssh.set_log_level('WARNING')

        self.assertEqual(len(log.records), 1)
        self.assertRegex(log.records[0].msg, r'\[conn=\d+, chan=0\] Test')
Пример #18
0
    def test_channel_log(self):
        """Test channel-level logger"""

        asyncssh.set_log_level('INFO')

        with (yield from self.connect()) as conn:
            for i in range(2):
                chan, _ = yield from conn.create_session(SSHClientSession)

                with self.assertLogs(level='INFO') as log:
                    chan.logger.info('Test')

                chan.write_eof()
                yield from chan.wait_closed()

                self.assertEqual(len(log.records), 1)
                self.assertRegex(log.records[0].msg,
                                 r'\[conn=\d+, chan=%s\] Test' % i)
Пример #19
0
    def test_debug_levels(self):
        """Test log debug levels"""

        asyncssh.set_log_level('DEBUG')

        for debug_level in range(1, 4):
            with self.subTest(debug_level=debug_level):
                asyncssh.set_debug_level(debug_level)

                with self.assertLogs(level='DEBUG') as log:
                    logger.debug1('DEBUG')
                    logger.debug2('DEBUG')
                    logger.packet(None, b'', 'DEBUG')

                self.assertEqual(len(log.records), debug_level)

                for record in log.records:
                    self.assertEqual(record.msg, record.levelname)
Пример #20
0
except ImportError:
    try:
        from colored import bg
        BACK_RESET = bg(0)
        BACK_BLUE = bg(27)
        BACK_GREEN = bg(119)
    except ImportError:
        BACK_RESET = ''
        BACK_BLUE = ''
        BACK_GREEN = ''

# https://www.pythoncentral.io/sqlalchemy-orm-examples/
# db = sqlite3.connect('session.db')

logging.getLogger().setLevel(logging.DEBUG)
asyncssh.set_log_level(logging.DEBUG)
log = logging.getLogger('sshame')
asyncssh.set_debug_level(2)


def configure_logging():
    global log
    # logging.getLogger("asyncssh").setLevel(logging.DEBUG)
    # logging.getLogger("asyncio").setLevel(logging.DEBUG)
    log.setLevel(logging.DEBUG)
    # create file handler which logs even debug messages
    fh = logging.FileHandler('sshame.log')
    fh.setLevel(logging.DEBUG)
    # create console handler with a higher log level
    ch = logging.StreamHandler()
    ch.setLevel(logging.INFO)
Пример #21
0
"""Module for connections."""
import asyncio
import logging
from asyncio import LimitOverrunError, TimeoutError

import asyncssh

_LOGGER = logging.getLogger(__name__)

_PATH_EXPORT_COMMAND = "PATH=$PATH:/bin:/usr/sbin:/sbin"
asyncssh.set_log_level('WARNING')


class SshConnection:
    """Maintains an SSH connection to an ASUS-WRT router."""
    def __init__(self, host, port, username, password, ssh_key):
        """Initialize the SSH connection properties."""

        self._connected = False
        self._host = host
        self._port = port or 22
        self._username = username
        self._password = password
        self._ssh_key = ssh_key
        self._client = None

    async def async_run_command(self, command, retry=False):
        """Run commands through an SSH connection.

        Connect to the SSH server if not currently connected, otherwise
        use the existing connection.
Пример #22
0
"""Module for connections."""
import asyncio
from asyncio import IncompleteReadError
import logging
from asyncio import LimitOverrunError, TimeoutError
from math import floor

import asyncssh

_LOGGER = logging.getLogger(__name__)

_PATH_EXPORT_COMMAND = "PATH=$PATH:/bin:/usr/sbin:/sbin"
asyncssh.set_log_level("WARNING")


class SshConnection:
    """Maintains an SSH connection to an ASUS-WRT router."""
    def __init__(self, host, port, username, password, ssh_key):
        """Initialize the SSH connection properties."""
        self._host = host
        self._port = port or 22
        self._username = username
        self._password = password
        self._ssh_key = ssh_key
        self._client = None

    async def async_run_command(self, command, retry=False):
        """Run commands through an SSH connection.
        Connect to the SSH server if not currently connected, otherwise
        use the existing connection.
        """
Пример #23
0
from container import ContainerPool
from sshserver import SSHServer

# logging config
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)-18s %(name)-20s %(levelname)-8s %(message)s',
    datefmt='%d-%m %H:%M:%S',
    handlers=[
        logging.FileHandler("sshproxy.log", mode='w'),
        logging.StreamHandler()
    ])

main_logger = logging.getLogger('main')
main_logger.setLevel(logging.INFO)
asyncssh.set_log_level(logging.WARNING)

# async ssh setup
os.environ['PYLXD_WARNINGS'] = 'none'

# config setup
container_pool_config = json.load(open('config/container_pool.json'))
container_ssh_config = json.load(open('config/container_ssh.json'))
container_config = json.load(open('config/container.json'))

# pool creation
pool = ContainerPool(container_pool_config, container_config)

# async io loop
loop = asyncio.get_event_loop()
Пример #24
0
import asyncio
import asyncssh
import asyncpg
import logging

asyncssh.set_log_level(40)
logging.basicConfig(
	filename='pirit_info.log',
	level=logging.INFO, 
	format='%(message)s',
	datefmt='%Y-%m-%d %H:%M:%S'
	)


def message(command, data):
	"""
		Формирует пакет для ККМ
	@params:
		command   - Команда, 2 символа (str)
		data	  - Данные, разденены запятой (str)
	"""
	data = [x for x in data]
	for n, i in enumerate(data):
		if i == ',':
			data[n] = 28
			continue
		data[n] = ord(i)
	frame = bytearray()
	frame += 'PIRI'.encode()			# пароль
	frame.append(0x21)				  # id пакета
	frame.append(ord(command[0]))	   # первый байт команды