How to use the paramiko.util function in paramiko

To help you get started, we’ve selected a few paramiko examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Komodo / KomodoEdit / contrib / paramiko / paramiko / pkey.py View on Github external
def _write_private_key(self, tag, f, data, password=None):
        f.write('-----BEGIN %s PRIVATE KEY-----\n' % tag)
        if password is not None:
            cipher_name = list(self._CIPHER_TABLE.keys())[0]
            cipher = self._CIPHER_TABLE[cipher_name]['cipher']
            keysize = self._CIPHER_TABLE[cipher_name]['keysize']
            blocksize = self._CIPHER_TABLE[cipher_name]['blocksize']
            mode = self._CIPHER_TABLE[cipher_name]['mode']
            salt = os.urandom(blocksize)
            key = util.generate_key_bytes(md5, salt, password, keysize)
            if len(data) % blocksize != 0:
                n = blocksize - len(data) % blocksize
                #data += os.urandom(n)
                # that would make more sense ^, but it confuses openssh.
                data += zero_byte * n
            data = cipher.new(key, mode, salt).encrypt(data)
            f.write('Proc-Type: 4,ENCRYPTED\n')
            f.write('DEK-Info: %s,%s\n' % (cipher_name, u(hexlify(salt)).upper()))
            f.write('\n')
        s = u(encodebytes(data))
        # re-wrap to 64-char lines
        s = ''.join(s.split('\n'))
        s = '\n'.join([s[i: i + 64] for i in range(0, len(s), 64)])
        f.write(s)
        f.write('\n')
        f.write('-----END %s PRIVATE KEY-----\n' % tag)
github paramiko / paramiko / paramiko / server.py View on Github external
def _run(self):
        try:
            self.__transport._log(
                DEBUG, "Starting handler for subsystem %s" % self.__name
            )
            self.start_subsystem(self.__name, self.__transport, self.__channel)
        except Exception as e:
            self.__transport._log(
                ERROR,
                'Exception in subsystem handler for "{0}": {1}'.format(
                    self.__name, e
                ),
            )
            self.__transport._log(ERROR, util.tb_strings())
        try:
            self.finish_subsystem()
        except:
            pass
github sganis / golddrive / golddrive / lib / lib / paramiko / transport.py View on Github external
def _parse_debug(self, m):
        m.get_boolean()  # always_display
        msg = m.get_string()
        m.get_string()  # language
        self._log(DEBUG, 'Debug msg: {}'.format(util.safe_string(msg)))
github robotframework / SSHLibrary / src / SSHLibrary / pythonclient.py View on Github external
def enable_logging(path):
        paramiko.util.log_to_file(path)
        return True
github leffss / devops / apps / webssh / sshd / sftpinterface.py View on Github external
import errno
import os
import paramiko
from paramiko.common import WARNING
from .sshinterface import transport_keepalive
import traceback
from django.conf import settings
import threading
from django.core.cache import cache
from webssh.models import TerminalSession
import time
import logging
import warnings
warnings.filterwarnings("ignore")
paramiko.util.log_to_file('./paramiko.log', level=WARNING)
from util.tool import gen_rand_char, terminal_log
logging.basicConfig(level=logging.INFO, format='[%(asctime)s] - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# ssh_client ===>>          proxy_ssh             ==>> ssh_server
# ssh_client ===>> (proxy_server -> proxy_client) ==>> ssh_server

try:
    terminal_exipry_time = settings.CUSTOM_TERMINAL_EXIPRY_TIME
except BaseException:
    terminal_exipry_time = 60 * 30


class SFTPInterface(paramiko.SFTPServerInterface):
    def __init__(self, proxy_ssh, *largs, **kwargs):
        self.sftp_closed = False
        self.char = gen_rand_char(16)
github Altinity / clickhouse-cluster-manager / clickhouse-cluster-manager.py View on Github external
# do actions would be taken
            for file in self.files_to_copy:
                print("DRY: copy %(file)s to %(hostname)s:%(port)s/%(dir)s as %(username)s:%(password)s" % {
                    'file': file,
                    'hostname': self.hostname,
                    'port': self.port,
                    'dir': self.dir_remote,
                    'username': self.username,
                    'password': '***'
                })
            # no actual actions would be taken - nothing to do in this method any more
            return

        # build dictionary of known hosts
        try:
            host_keys = paramiko.util.load_host_keys(os.path.expanduser('~/.ssh/known_hosts'))
        except:
            # can't open known_hosts file, assume it's empty
            host_keys = {}

        if self.hostname in host_keys:
            # already known host
            hostkeytype = host_keys[self.hostname].keys()[0]
            hostkey = host_keys[self.hostname][hostkeytype]
            print('Using host key of type ' + hostkeytype)

        # connect
        try:
            print('Establishing SSH connection to:', self.hostname, self.port, '...')
            transport = paramiko.Transport((self.hostname, self.port))
            transport.start_client()
        except:
github eden3d / ansible-mikrotik-utils / src / ansible_mikrotik_utils / module.py View on Github external
import sys
import socket

from re import compile as compile_regex

from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import env_fallback, get_exception
from ansible.module_utils.shell import Shell, ShellError

from ansible_mikrotik_utils.config import MikrotikConfig

from paramiko import AuthenticationException, SSHException, util
from getpass import getuser

if __debug__:
    paramiko.util.log_to_file('/dev/stderr')

# Constants
# =============================================================================

CLI_PROMPTS_RE = [
    compile_regex(r"\[([\w\-]+)@([\.\w\-]+)\]\s(\/(\w+\s?)*)?\>"),
]

CLI_ERRORS_RE = [
    compile_regex(r"failure: (.*)"),
    compile_regex(r"bad command name ([\w\-]+) \(line \d+ column \d+\)"),
    compile_regex(r"syntax error \(line \d+ column \d+\)"),
    compile_regex(r"expected end of command \(line \d+ column \d+\)"),
    compile_regex(r"expected command name \(line \d+ column \d+\)"),

]
github linkedin / kafka-tools / kafka / tools / assigner.py View on Github external
def get_partition_sizes(cluster, args):
  # Set up an SSH client for connecting to the brokers, and silence the logs
  client = paramiko.SSHClient()
  plogger = paramiko.util.logging.getLogger()
  plogger.setLevel(logging.WARNING)
  client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  client.load_system_host_keys()

  # Get broker partition sizes
  sizes = {}
  size_re = re.compile("^([0-9]+)\s+.*?\/([a-z0-9_-]+)-([0-9]+)\s*$", re.I)
  for broker in cluster.brokers:
    log.info("Getting partition sizes for {0}".format(cluster.brokers[broker].hostname))
    client.connect(cluster.brokers[broker].hostname, allow_agent=True)
    stdin, stdout, stderr = client.exec_command('du -sk {0}/*'.format(args.datadir))
    for ln in stdout.readlines():
      m = size_re.match(ln)
      if m:
        size = int(m.group(1))
        topic = m.group(2)
github paramiko / paramiko / paramiko / transport.py View on Github external
self._channels = ChannelMap()
        self.channel_events = {}       # (id -> Event)
        self.channels_seen = {}        # (id -> True)
        self._channel_counter = 0
        self.default_max_packet_size = default_max_packet_size
        self.default_window_size = default_window_size
        self._forward_agent_handler = None
        self._x11_handler = None
        self._tcp_handler = None

        self.saved_exception = None
        self.clear_to_send = threading.Event()
        self.clear_to_send_lock = threading.Lock()
        self.clear_to_send_timeout = 30.0
        self.log_name = 'paramiko.transport'
        self.logger = util.get_logger(self.log_name)
        self.packetizer.set_log(self.logger)
        self.auth_handler = None
        self.global_response = None     # response Message from an arbitrary global request
        self.completion_event = None    # user-defined event callbacks
        self.banner_timeout = 15        # how long (seconds) to wait for the SSH banner
        self.handshake_timeout = 15     # how long (seconds) to wait for the handshake to finish after SSH banner sent.


        # server mode:
        self.server_mode = False
        self.server_object = None
        self.server_key_dict = {}
        self.server_accepts = []
        self.server_accept_cv = threading.Condition(self.lock)
        self.subsystem_table = {}
github OpenMDAO / OpenMDAO-Framework / openmdao.devtools / src / openmdao / devtools / tstrelease.py View on Github external
import sys
import os
import shutil
import urllib2
import subprocess
from optparse import OptionParser

from fabric.api import run, env, local, put, cd, get, settings
from fabric.state import connections
#testing
import paramiko.util

paramiko.util.log_to_file('paramiko.log')

#----------------------------------------------------------------------------------
# Part of script needed to test releases
# This will only be run from storm, since the release script is always run from storm
# Run this from the scripts directory
def _getrelease(site_url, version):
    """Grabs the specified openmdao release installer script from the specified 
    website, so it can be tested on our dev platforms. The script will be placed in
    the current directory.
    """
    script_url =  '%s/downloads/%s/go-openmdao.py' % (site_url, version)

    try:  
        resp = urllib2.urlopen(script_url)
    except IOError, e:
        if hasattr(e, 'reason'):