Python paramiko.Transport() Examples

The following are 30 code examples of paramiko.Transport(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module paramiko , or try the search function .
Example #1
Source File: ssh.py    From JetPack with Apache License 2.0 10 votes vote down vote up
def ssh_edit_file(adress, user, passw, remotefile, regex, replace):
        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        trans = paramiko.Transport((adress, 22))
        trans.connect(username=user, password=passw)
        sftp = paramiko.SFTPClient.from_transport(trans)
        f_in = sftp.file(remotefile, "r")
        c_in = f_in.read()
        pattern = re.compile(regex, re.MULTILINE | re.DOTALL)
        c_out = pattern.sub(replace, c_in)
        f_out = sftp.file(remotefile, "w")
        f_out.write(c_out)
        f_in.close()
        f_out.close()
        sftp.close()
        trans.close() 
Example #2
Source File: common.py    From codo-cmdb with GNU General Public License v3.0 7 votes vote down vote up
def get_key_file(ssh_key):
    '''根据key内容临时生成一个key文件'''
    #file_path = '/tmp/%s'%shortuuid.uuid()
    file_path = '/tmp/codo_cmdb_id_rsa'
    cmd = 'echo "{}" > {} && chmod 600 {}'.format(ssh_key,file_path,file_path)
    ret,stdout = exec_shell(cmd)
    if ret == 0:
        return file_path
    else:
        return None


# def remote_upload_file(ip,user,pwd,cmd,local_file,remote_file,port=22):
#     '''ssh上传并执行bash for pwd'''
#     t = paramiko.Transport((ip,port))
#     t.connect(username=user, password=pwd)
#     sftp = paramiko.SFTPClient.from_transport(t)
#     sftp.put(local_file,remote_file)
#     ssh = paramiko.SSHClient()
#     ssh._transport = t
#     stdin, stdout, stderr = ssh.exec_command(cmd)
#     show_log = stdout.read().decode('utf-8').strip()
#     t.close()
#     return show_log 
Example #3
Source File: transport.py    From imoocc with GNU General Public License v2.0 7 votes vote down vote up
def __repr__(self):
        """
        Returns a string representation of this object, for debugging.

        @rtype: str
        """
        out = '<paramiko.Transport at %s' % hex(long(id(self)) & 0xffffffffL)
        if not self.active:
            out += ' (unconnected)'
        else:
            if self.local_cipher != '':
                out += ' (cipher %s, %d bits)' % (self.local_cipher,
                                                  self._cipher_info[self.local_cipher]['key-size'] * 8)
            if self.is_authenticated():
                out += ' (active; %d open channel(s))' % len(self._channels)
            elif self.initial_kex_done:
                out += ' (connected; awaiting auth)'
            else:
                out += ' (connecting)'
        out += '>'
        return out 
Example #4
Source File: crypto.py    From gitlab-tools with GNU General Public License v3.0 7 votes vote down vote up
def get_remote_server_key(ip: str, port: int=22) -> paramiko.pkey.PKey:
    """
    Returns PKey for given server
    :param ip: IP or Hostname
    :param port: Port
    :return: Returns PKey
    """

    my_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    my_socket.settimeout(10)
    my_socket.connect((ip, port))

    my_transport = paramiko.Transport(my_socket)
    my_transport.start_client()
    ssh_key = my_transport.get_remote_server_key()

    my_transport.close()
    my_socket.close()
    return ssh_key 
Example #5
Source File: etss_scp_in.py    From HPN-Scripting with MIT License 7 votes vote down vote up
def main():
    target_ip = etss_range(ip)
    for i in target_ip:
        try:
            t = paramiko.Transport((i, port))
            t.connect(username=user, password=passwd)
            sftp = paramiko.SFTPClient.from_transport(t)
            #Download files
            filepath = '/scripts/test.txt'
            localpath = 'test.txt'
            #dirlist = scp.listdir(filepath)
            #print dirlist
            #sftp.get(filepath, localpath)
            #Upload files
            sftp.put(localpath, filepath)
            time.sleep(15)
            print "SFTP connection established to %s" % (i)
            print "File(s) being uploaded ..."
        except:
            sftp.close()
            t.close()
            print "Problem connecting with ip: %s" % (i)
            continue 
Example #6
Source File: sshtunnel.py    From sshtunnel with MIT License 7 votes vote down vote up
def _get_transport(self):
        """ Return the SSH transport to the remote gateway """
        if self.ssh_proxy:
            if isinstance(self.ssh_proxy, paramiko.proxy.ProxyCommand):
                proxy_repr = repr(self.ssh_proxy.cmd[1])
            else:
                proxy_repr = repr(self.ssh_proxy)
            self.logger.debug('Connecting via proxy: {0}'.format(proxy_repr))
            _socket = self.ssh_proxy
        else:
            _socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        if isinstance(_socket, socket.socket):
            _socket.settimeout(SSH_TIMEOUT)
            _socket.connect((self.ssh_host, self.ssh_port))
        transport = paramiko.Transport(_socket)
        transport.set_keepalive(self.set_keepalive)
        transport.use_compression(compress=self.compression)
        transport.daemon = self.daemon_transport

        return transport 
Example #7
Source File: test_sftpclone.py    From sftpclone with MIT License 7 votes vote down vote up
def _start_sftp_server():
    """Start the SFTP local server."""
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.setblocking(False)
    sock.bind(('localhost', 2222))
    sock.listen(10)

    reads = {sock}
    others = set()

    while not event.is_set():
        ready_to_read, _, _ = select.select(reads, others, others, 1)

        if sock in ready_to_read:
            client_socket, address = sock.accept()
            ts = paramiko.Transport(client_socket)

            host_key = paramiko.RSAKey.from_private_key_file(t_path('server_id_rsa'))
            ts.add_server_key(host_key)
            server = StubServer()
            ts.set_subsystem_handler('sftp', paramiko.SFTPServer, StubSFTPServer)
            ts.start_server(server=server)

    sock.close() 
Example #8
Source File: __init__.py    From pub with GNU General Public License v2.0 7 votes vote down vote up
def start_server(host, port, keyfile, level):
    paramiko_level = getattr(paramiko.common, level)
    paramiko.common.logging.basicConfig(level=paramiko_level)


    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
    server_socket.bind((host, port))
    server_socket.listen(BACKLOG)
    print host,port
    while True:
        conn, addr = server_socket.accept()

        host_key = paramiko.RSAKey.from_private_key_file(keyfile)
        transport = paramiko.Transport(conn)
        transport.add_server_key(host_key)
        transport.set_subsystem_handler(
            'sftp', paramiko.SFTPServer, StubSFTPServer)

        server = StubServer()
        transport.start_server(server=server)

        channel = transport.accept()
        while transport.is_active():
            time.sleep(1) 
Example #9
Source File: pshitt.py    From pshitt with GNU General Public License v3.0 6 votes vote down vote up
def handle_client(self, client, addr):
        try:
            t = paramiko.Transport(client)
            t.local_version = self.args.version
            try:
                t.load_server_moduli()
            except Exception:
                raise
            t.add_server_key(self.host_key)
            server = Server()
            server.set_ip_param(addr)
            server.set_logfile(self.logfile)
            try:
                t.start_server(server=server)
            except paramiko.SSHException:
                logging.info('SSH negotiation failed.')
                return
            server.set_transport(t)
            # wait for auth
            chan = t.accept(20)
        except Exception:
            logging.info('SSH connect failure')
            return 
Example #10
Source File: ssh_tunnel.py    From margaritashotgun with MIT License 6 votes vote down vote up
def __init__(self, local_port, remote_address, remote_port, transport):
        """
        type: local_port: int
        param: local_port: local tunnel endpoint ip binding
        type: remote_address: str
        param: remote_address: Remote tunnel endpoing ip binding
        type: remote_port: int
        param: remote_port: Remote tunnel endpoint port binding
        type: transport: :py:class:`paramiko.Transport`
        param: transport: Paramiko ssh transport
        """
        super(Forward, self).__init__()
        self.local_port = local_port
        self.remote_address = remote_address
        self.remote_port = remote_port
        self.transport = transport 
Example #11
Source File: sshtunnel.py    From sshtunnel with MIT License 6 votes vote down vote up
def _stop_transport(self):
        """ Close the underlying transport when nothing more is needed """
        try:
            self._check_is_started()
        except (BaseSSHTunnelForwarderError,
                HandlerSSHTunnelForwarderError) as e:
            self.logger.warning(e)
        for _srv in self._server_list:
            tunnel = _srv.local_address
            if self.tunnel_is_up[tunnel]:
                self.logger.info('Shutting down tunnel {0}'.format(tunnel))
                _srv.shutdown()
            _srv.server_close()
            # clean up the UNIX domain socket if we're using one
            if isinstance(_srv, _UnixStreamForwardServer):
                try:
                    os.unlink(_srv.local_address)
                except Exception as e:
                    self.logger.error('Unable to unlink socket {0}: {1}'
                                      .format(self.local_address, repr(e)))
        self.is_alive = False
        if self.is_active:
            self._transport.close()
            self._transport.stop_thread()
        self.logger.debug('Transport is closed') 
Example #12
Source File: main.py    From lambda-s3-sftp with MIT License 6 votes vote down vote up
def connect_to_SFTP(hostname, port, username, password, pkey):
    transport = paramiko.Transport((hostname, port))
    transport.connect(
        username=username,
        password=password,
        pkey=pkey
    )
    sftp = paramiko.SFTPClient.from_transport(transport)

    return sftp, transport 
Example #13
Source File: tcp_ssh.py    From honeypot with GNU General Public License v2.0 6 votes vote down vote up
def handle_tcp_ssh(socket, dstport):
	try:
		t = paramiko.Transport(socket)
		t.local_version = 'SSH-2.0-OpenSSH_6.6.1p1 Ubuntu-2ubuntu2'
		t.load_server_moduli() # It can be safely commented out if it does not work on your system

		t.add_server_key(host_key_rsa)
		t.add_server_key(host_key_dss)

		server = Server(socket.getpeername())
		t.start_server(server=server)

		t.join()

	except Exception as err:
		#print(traceback.format_exc())
		pass

	try:
		print("-- SSH TRANSPORT CLOSED --")
		t.close()
	except:
		pass

	socket.close() 
Example #14
Source File: ssh.py    From ryu with Apache License 2.0 6 votes vote down vote up
def __init__(self, sock, addr):
        super(SshServer, self).__init__()

        # tweak InternalApi and RootCmd for non-bgp related commands
        self.api = InternalApi(log_handler=logging.StreamHandler(sys.stderr))
        setattr(self.api, 'sshserver', self)
        self.root = RootCmd(self.api)
        self.root.subcommands['help'] = self.HelpCmd
        self.root.subcommands['quit'] = self.QuitCmd

        transport = paramiko.Transport(sock)
        transport.load_server_moduli()
        host_key = self._find_ssh_server_key()
        transport.add_server_key(host_key)
        self.transport = transport
        transport.start_server(server=self) 
Example #15
Source File: sftp.py    From yunbk with MIT License 6 votes vote down vote up
def __init__(self, host, username, password, remote_dir, port=None, keeps=None):
        super(SFTPBackend, self).__init__(keeps)
        self.host = host
        self.port = port or 22
        self.username = username
        self.password = password
        self.remote_dir = remote_dir

        # 这一步会建立连接
        try:
            self.transport = paramiko.Transport((self.host, self.port))
            # 登录验证
            self.transport.connect(username=self.username, password=self.password)
            self.sftp = paramiko.SFTPClient.from_transport(self.transport)
        except:
            # 这个的关闭,并不会关闭transport的连接
            if self.sftp:
                self.sftp.close()

            # 所以如果登录失败,要记得关闭连接
            if self.transport:
                self.transport.close()

            t, v, tb = sys.exc_info()
            reraise(t, v, tb) 
Example #16
Source File: transport.py    From imoocc with GNU General Public License v2.0 6 votes vote down vote up
def __repr__(self):
        """
        Returns a string representation of this object, for debugging.

        @rtype: str
        """
        out = '<paramiko.Transport at %s' % hex(long(id(self)) & 0xffffffffL)
        if not self.active:
            out += ' (unconnected)'
        else:
            if self.local_cipher != '':
                out += ' (cipher %s, %d bits)' % (self.local_cipher,
                                                  self._cipher_info[self.local_cipher]['key-size'] * 8)
            if self.is_authenticated():
                out += ' (active; %d open channel(s))' % len(self._channels)
            elif self.initial_kex_done:
                out += ' (connected; awaiting auth)'
            else:
                out += ' (connecting)'
        out += '>'
        return out 
Example #17
Source File: transport.py    From imoocc with GNU General Public License v2.0 6 votes vote down vote up
def __repr__(self):
        """
        Returns a string representation of this object, for debugging.
        """
        out = '<paramiko.Transport at %s' % hex(long(id(self)) & xffffffff)
        if not self.active:
            out += ' (unconnected)'
        else:
            if self.local_cipher != '':
                out += ' (cipher %s, %d bits)' % (self.local_cipher,
                                                  self._cipher_info[self.local_cipher]['key-size'] * 8)
            if self.is_authenticated():
                out += ' (active; %d open channel(s))' % len(self._channels)
            elif self.initial_kex_done:
                out += ' (connected; awaiting auth)'
            else:
                out += ' (connecting)'
        out += '>'
        return out 
Example #18
Source File: 6_3_print_remote_cpu_info.py    From Python-Network-Programming-Cookbook-Second-Edition with MIT License 6 votes vote down vote up
def print_remote_cpu_info(hostname, port, username, password):
    client = paramiko.Transport((hostname, port))
    client.connect(username=username, password=password)
    
    stdout_data = []
    stderr_data = []
    session = client.open_channel(kind='session')
    session.exec_command(COMMAND)
    while True:
        if session.recv_ready():
            stdout_data.append(session.recv(RECV_BYTES))
        if session.recv_stderr_ready():
            stderr_data.append(session.recv_stderr(RECV_BYTES))
        if session.exit_status_ready():
            break
    
    print ('exit status: ', session.recv_exit_status())
    print (b''.join(stdout_data))
    print (b''.join(stderr_data))
    
    session.close()
    client.close() 
Example #19
Source File: minisftp.py    From iOSSecAudit with GNU General Public License v3.0 6 votes vote down vote up
def sftp_conn(self):
        """"""
        try:
            self.transport = paramiko.Transport((self.host, self.port)) 
            self.transport.connect(username = self.username, password = self.password) 
            self.sftp = paramiko.SFTPClient.from_transport(self.transport)
            return True
        except paramiko.AuthenticationException:
            G.log(G.ERROR, "SFTP Authentication failed when connecting to %s" % self.host)
            return False
        except:
            G.log(G.ERROR, "SFTP Could not SSH to %s, waiting for it to start" % self.host)
            return False

    
    #---------------------------------------------------------------------- 
Example #20
Source File: SSH_transport.py    From Mastering-Python-for-Networking-and-Security with MIT License 6 votes vote down vote up
def ssh_command(ip, user, passwd, command):
    transport = paramiko.Transport(ip)
    try:
        transport.start_client()
    except Exception as e:
        print(e)
    
    try:
        transport.auth_password(username=user,password=passwd)
    except Exception as e:
        print(e)
        
    if transport.is_authenticated():
        print(transport.getpeername())
        channel = transport.opem_session()
        channel.exec_command(command)
        response = channel.recv(1024)
        print('Command %r(%r)-->%s' % (command,user,response)) 
Example #21
Source File: psc_ha_pairing.py    From ansible-module-chaperone with Apache License 2.0 6 votes vote down vote up
def create_psc_session(module, psc_ip, password):
    try:
        #Transport connection to the PSC
        transport = paramiko.Transport(psc_ip, 22)
        transport.connect(username='root', password=password)
        sftp = paramiko.SFTPClient.from_transport(transport)
    except:
        module.fail_json(msg='Transport connection to the PSC failed.')
    try:
        # SSH connect to PSC
        ssh = paramiko.SSHClient()
        ssh.load_system_host_keys()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(psc_ip, 22, 'root', password)
    except:
        module.fail_json(msg='SSH connection to the PSC failed.')
    return sftp, ssh 
Example #22
Source File: sshtunnel.py    From sshtunnel with MIT License 6 votes vote down vote up
def _create_tunnels(self):
        """
        Create SSH tunnels on top of a transport to the remote gateway
        """
        if not self.is_active:
            try:
                self._connect_to_gateway()
            except socket.gaierror:  # raised by paramiko.Transport
                msg = 'Could not resolve IP address for {0}, aborting!' \
                    .format(self.ssh_host)
                self.logger.error(msg)
                return
            except (paramiko.SSHException, socket.error) as e:
                template = 'Could not connect to gateway {0}:{1} : {2}'
                msg = template.format(self.ssh_host, self.ssh_port, e.args[0])
                self.logger.error(msg)
                return
        for (rem, loc) in zip(self._remote_binds, self._local_binds):
            try:
                self._make_ssh_forward_server(rem, loc)
            except BaseSSHTunnelForwarderError as e:
                msg = 'Problem setting SSH Forwarder up: {0}'.format(e.value)
                self.logger.error(msg) 
Example #23
Source File: hammr_utils.py    From hammr with Apache License 2.0 5 votes vote down vote up
def upload_binary_to_client(hostname, port, username, password, file_src_path, binary_path, id_file):
    try:
        t = paramiko.Transport((hostname, port))
        pkey = None
        if id_file:
            pkey = paramiko.RSAKey.from_private_key_file(id_file)
            t.connect(username=username, pkey=pkey)
        else:
            t.connect(username=username, password=password)
        sftp = paramiko.SFTPClient.from_transport(t)

        # upload binary
        sftp.put(file_src_path, binary_path)
        t.close()

        client = paramiko.SSHClient()
        client.load_system_host_keys()
        client.set_missing_host_key_policy(paramiko.MissingHostKeyPolicy())
        client.connect(hostname, port, username, password, pkey)

    except paramiko.AuthenticationException as e:
        raise Exception("Authentification error: " + e[0])
    except Exception, e:
        try:
            t.close()
            client.close()
        except:
            pass
        raise Exception("Caught exception when uploading binary [" + binary_path + "]: " + str(e)) 
Example #24
Source File: transport.py    From imoocc with GNU General Public License v2.0 5 votes vote down vote up
def getpeername(self):
        """
        Return the address of the remote side of this Transport, if possible.
        This is effectively a wrapper around C{'getpeername'} on the underlying
        socket.  If the socket-like object has no C{'getpeername'} method,
        then C{("unknown", 0)} is returned.

        @return: the address if the remote host, if known
        @rtype: tuple(str, int)
        """
        gp = getattr(self.sock, 'getpeername', None)
        if gp is None:
            return ('unknown', 0)
        return gp() 
Example #25
Source File: ssh_listener.py    From OWASP-Honeypot with Apache License 2.0 5 votes vote down vote up
def handle_connections(client, client_addr):
    transport = paramiko.Transport(client)
    transport.add_server_key(HOST_KEY)
    server_handler = SSHServerHandler(client_addr)

    transport.start_server(server=server_handler)

    channel = transport.accept(1)
    if channel is not None:
        channel.close() 
Example #26
Source File: SFTP_controller.py    From whipFTP with MIT License 5 votes vote down vote up
def connect_to(self, Host, Username = ' ', Password = ' ', Port = 22): 
        self.transport = paramiko.Transport((Host, Port))
        self.transport.connect(username = Username, password = Password)
        self.ftp = paramiko_sftp_client.from_transport(self.transport)
        self.ftp.go_to_home(Username) 
Example #27
Source File: test_ssh.py    From poseidon with MIT License 5 votes vote down vote up
def run(self):
        self.socks, addr = self.sock.accept()
        self.ts = paramiko.Transport(self.socks)
        host_key = paramiko.RSAKey.from_private_key_file(
            get_path('test_rsa.key'))
        self.ts.add_server_key(host_key)
        server = NullServer()
        self.ts.start_server(self.event, server) 
Example #28
Source File: utils.py    From citrix-adc-ansible-modules with GNU General Public License v3.0 5 votes vote down vote up
def copy_sslcertificate_to_cpx():
    transport = paramiko.Transport(DOCKER_IP, 22)
    transport.connect(username='root', password='linux')
    sftp = paramiko.SFTPClient.from_transport(transport)
    here = os.path.dirname(os.path.realpath(__file__))
    for file in ['server.crt', 'server.key', 'server2.key', 'server2.crt']:
        sftp.put(os.path.join(here, 'datafiles', file), os.path.join('/nsconfig/ssl', file)) 
Example #29
Source File: 6_2_copy_remote_file_over_sftp.py    From Python-Network-Programming-Cookbook-Second-Edition with MIT License 5 votes vote down vote up
def copy_file(hostname, port, username, password, src, dst):
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    print (" Connecting to %s \n with username=%s... \n" %(hostname,username))
    t = paramiko.Transport(hostname, port)
    t.connect(username=username,password=password)
    sftp = paramiko.SFTPClient.from_transport(t)
    print ("Copying file: %s to path: %s" %(src, dst))
    sftp.put(src, dst)
    sftp.close()
    t.close() 
Example #30
Source File: honeypot.py    From SSH-Honeypot with MIT License 5 votes vote down vote up
def handleConnection(client):
    transport = paramiko.Transport(client)
    transport.add_server_key(HOST_KEY)

    server_handler = SSHServerHandler()

    transport.start_server(server=server_handler)

    channel = transport.accept(1)
    if not channel is None:
        channel.close()