python类Transport()的实例源码

ssh_tools.py 文件源码 项目:OpsManage 作者: welliamcao 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def thread(self,model,queue,cmd=None,
               cmd_args=None,localPath=None,
               remotePath=None,remoteFile=None):           
        if model == 'command':         
            self.sshConn = paramiko.SSHClient()
            self.sshConn.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
            self.sshConn.connect(hostname = self.hostname,port=self.port,
                                 username=self.username, password=self.password)          
            self.threads = SSH(ssh=self.sshConn,hostname=self.hostname,
                           queue=queue,model=model,cmd=cmd,
                           cmd_args=cmd_args,localPath=localPath,
                           remotePath=remotePath,remoteFile=remoteFile)

        elif model in ['upload','download']:
            self.sshConn = paramiko.Transport((self.hostname,self.port))
            self.sshConn.connect(username=self.username, password=self.password)         
            self.threads = SSH(ssh=self.sshConn,hostname=self.hostname,
                           queue=queue,model=model,cmd=cmd,
                           cmd_args=cmd_args,localPath=localPath,
                           remotePath=remotePath,remoteFile=remoteFile)
transport.py 文件源码 项目:watchmen 作者: lycclsltt 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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
transport.py 文件源码 项目:watchmen 作者: lycclsltt 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def atfork(self):
        """
        Terminate this Transport without closing the session.  On posix
        systems, if a Transport is open during process forking, both parent
        and child will share the underlying socket, but only one process can
        use the connection (without corrupting the session).  Use this method
        to clean up a Transport object without disrupting the other process.

        @since: 1.5.3
        """
        self.close()
transport.py 文件源码 项目:watchmen 作者: lycclsltt 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def load_server_moduli(filename=None):
        """
        I{(optional)}
        Load a file of prime moduli for use in doing group-exchange key
        negotiation in server mode.  It's a rather obscure option and can be
        safely ignored.

        In server mode, the remote client may request "group-exchange" key
        negotiation, which asks the server to send a random prime number that
        fits certain criteria.  These primes are pretty difficult to compute,
        so they can't be generated on demand.  But many systems contain a file
        of suitable primes (usually named something like C{/etc/ssh/moduli}).
        If you call C{load_server_moduli} and it returns C{True}, then this
        file of primes has been loaded and we will support "group-exchange" in
        server mode.  Otherwise server mode will just claim that it doesn't
        support that method of key negotiation.

        @param filename: optional path to the moduli file, if you happen to
            know that it's not in a standard location.
        @type filename: str
        @return: True if a moduli file was successfully loaded; False
            otherwise.
        @rtype: bool

        @note: This has no effect when used in client mode.
        """
        Transport._modulus_pack = ModulusPack(rng)
        # places to look for the openssh "moduli" file
        file_list = [ '/etc/ssh/moduli', '/usr/local/etc/moduli' ]
        if filename is not None:
            file_list.insert(0, filename)
        for fn in file_list:
            try:
                Transport._modulus_pack.read_file(fn)
                return True
            except IOError:
                pass
        # none succeeded
        Transport._modulus_pack = None
        return False
sftptransfer.py 文件源码 项目:core-python 作者: yidao620c 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def transfer_file(hostname_, port_, username_, password_, fdir_, fname_):
    try:
        print('Establishing SSH connection to:', hostname_, port_, '...')
        t = paramiko.Transport((hostname_, port_))
        t.start_client()

        if not t.is_authenticated():
            print('Trying password login...')
            t.auth_password(username=username_, password=password_)

        sftp = paramiko.SFTPClient.from_transport(t)

        local_file = os.path.join(fdir_, fname_)
        remote_file = DIR_REMOTE + '/' + fname_
        try:
            print('start transport...')
            sftp.put(local_file, remote_file)
        except:
            LOG.error('error...')
            raise
        t.close()
        LOG.info('??????????zip??...')
        os.remove(local_file)
    except Exception as e:
        print(e)
        try:
            LOG.info('end transport and close it...')
            t.close()
        except:
            pass
ssh.py 文件源码 项目:SameKeyProxy 作者: xzhou 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def init_ssh_client(self):
        self.log.debug("SSHProtocol: Initializing the destination transport")
        self.destt = paramiko.Transport(self.destination)
        try:
            self.destt.start_client()
        except paramiko.SSHException:
            self.log.error("*** SSH negotiation failed.")
            return
utils.py 文件源码 项目:netscaler-ansible-modules 作者: citrix 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
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))
6_3_print_remote_cpu_info.py 文件源码 项目:Python-Network-Programming-Cookbook-Second-Edition 作者: PacktPublishing 项目源码 文件源码 阅读 14 收藏 0 点赞 0 评论 0
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()
io_tools.py 文件源码 项目:serenytics-python-client 作者: codacy-badger 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
def connect_to_sftp_server(username, password, hostname, port):
    t = paramiko.Transport((hostname, port))
    t.connect(username=username, password=password)
    return paramiko.SFTPClient.from_transport(t)
execute.py 文件源码 项目:pytrip 作者: pytrip 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _get_sftp_client(self):
        """ returns a sftp client object and the corresponding transport socket.
        Both must be closed after use.
        """
        transport = paramiko.Transport((self.servername, 22))
        # transport.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # If no password is supplied, try to look for a private key
        if self.password is "" or None:
            rsa_keypath = os.path.expanduser(self.rsakey_local_path)
            if not os.path.isfile(rsa_keypath):
                # login with provided username + empty password
                try:
                    transport.connect(username=self.username, password="")
                except Exception:
                    logger.error("Cannot connect to " + self.servername)
                    logger.error("Check username, password or key in " + self.rsakey_local_path)
                    raise
            else:
                # login with provided username + private key
                rsa_key = paramiko.RSAKey.from_private_key_file(rsa_keypath)
                try:
                    transport.connect(username=self.username, pkey=rsa_key)
                except Exception:
                    logger.error("Cannot connect to " + self.servername)
                    logger.error("Check username and your key in " + self.rsakey_local_path)
                    raise
        else:
            # login with provided username + password
            transport.connect(username=self.username, password=self.password)

        sftp = paramiko.SFTPClient.from_transport(transport)

        return sftp, transport
server.py 文件源码 项目:netconf-proxy 作者: fortinet-solutions-cse 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
def __init__ (self,
                  server_ctl,
                  session_class,
                  extra_args,
                  server,
                  newsocket,
                  addr,
                  debug):
        self.session_class = session_class
        self.extra_args = extra_args
        self.server = server
        self.client_socket = newsocket
        self.client_addr = addr
        self.debug = debug
        self.server_ctl = server_ctl
        self.sessions = []

        try:
            if self.debug:
                logger.debug("%s: Opening SSH connection", str(self))

            self.ssh = ssh.Transport(self.client_socket)
            self.ssh.add_server_key(self.server.host_key)
            self.ssh.start_server(server=self.server_ctl)
        except ssh.AuthenticationException as error:
            self.client_socket.close()
            self.client_socket = None
            logger.error("Authentication failed:  %s", str(error))
            raise

        self.lock = threading.Lock()
        self.running = True
        self.thread = threading.Thread(None,
                                       self._accept_chan_thread,
                                       name="SSHAcceptThread")
        self.thread.daemon = True
        self.thread.start()
ssh.py 文件源码 项目:python-tripleo-helper 作者: redhat-openstack 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _get_transport_via_ip(self):
        for i in range(60):
            try:
                channel = self._client.get_transport().open_channel(
                    'direct-tcpip',
                    (self._hostname, 22),
                    (self.via_ip, 0))
            except ssh_exception.ChannelException:
                LOG.debug('%s creating the direct-tcip connections' % self.description)
                time.sleep(1)
            else:
                transport = paramiko.Transport(channel)
                transport.start_client()
                transport.auth_publickey(self._user, self._private_key)
                return transport
        raise Exception()
lil_sshniffer.py 文件源码 项目:Decept 作者: Cisco-Talos 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def retry_hack(self):
        if retry_hack: #check for global flag first
            self.endpoint.close()
            dstsock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
            dstsock.connect((self.rhost,self.rport))
            self.endpoint = paramiko.Transport(dstsock) 
            self.endpoint.start_client()
lil_sshniffer.py 文件源码 项目:Decept 作者: Cisco-Talos 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def client_handler_helper(sock,address,dst_sock,kill_switch,hijack_flag):
    dt = datetime.datetime.today()
    logfile_name = dt.__str__() + ".log" 
    print_purp("[c.c] Logging to %s" % logfile_name)

    try:
        os.mkdir('logs')
    except:
        pass

    with open("logs/%s"%(logfile_name),"w") as logfile:
        logfile.write("<(^.^)>") 
        logfile.write("Inbound connection from %s:%d\n" %address)
        logfile.write("Posing as: %s:%d\n" % (DST_IP,DST_PORT))   
        logfile.write("_________________\n")    

        # connect outbound ssh connection
        out_trans = paramiko.Transport(dst_sock) 
        out_trans.start_client()
        print_attn("[0.<] Started Transport session....")

        if sniff == True:
            ssh_client_handler(sock,address,out_trans,logfile,kill_switch,hijack_flag)
        else:
            tcp_client_handler(sock,address,out_trans,logfile,kill_switch)
app.py 文件源码 项目:coco 作者: jumpserver 项目源码 文件源码 阅读 13 收藏 0 点赞 0 评论 0
def process_request(self, client, addr):
        rc = self.request_context({'REMOTE_ADDR': addr[0]})
        rc.push()
        logger.info("Get ssh request from %s" % request.environ['REMOTE_ADDR'])
        transport = paramiko.Transport(client, gss_kex=False)
        try:
            transport.load_server_moduli()
        except:
            logger.warning('Failed to load moduli -- gex will be unsupported.')
            raise

        transport.add_server_key(SSHInterface.get_host_key())
        # ?app??????????, ssh_interface ??ssh???????
        ssh_interface = SSHInterface(self, rc)

        try:
            transport.start_server(server=ssh_interface)
        except paramiko.SSHException:
            logger.warning('SSH negotiation failed.')
            sys.exit(1)

        client_channel = transport.accept(20)
        if client_channel is None:
            logger.warning('No ssh channel get.')
            sys.exit(1)

        if request.method == 'shell':
            logger.info('Client asked for a shell.')
            InteractiveServer(self, ssh_interface.user_service, client_channel).run()
        elif request.method == 'command':
            client_channel.send(wr(warning('We are not support command now')))
            client_channel.close()
            sys.exit(2)
        else:
            client_channel.send(wr(warning('Not support the request method')))
            client_channel.close()
            sys.exit(2)
transport.py 文件源码 项目:SublimeRemoteGDB 作者: summerwinter 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def atfork(self):
        """
        Terminate this Transport without closing the session.  On posix
        systems, if a Transport is open during process forking, both parent
        and child will share the underlying socket, but only one process can
        use the connection (without corrupting the session).  Use this method
        to clean up a Transport object without disrupting the other process.

        .. versionadded:: 1.5.3
        """
        self.sock.close()
        self.close()
transport.py 文件源码 项目:SublimeRemoteGDB 作者: summerwinter 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def load_server_moduli(filename=None):
        """
        (optional)
        Load a file of prime moduli for use in doing group-exchange key
        negotiation in server mode.  It's a rather obscure option and can be
        safely ignored.

        In server mode, the remote client may request "group-exchange" key
        negotiation, which asks the server to send a random prime number that
        fits certain criteria.  These primes are pretty difficult to compute,
        so they can't be generated on demand.  But many systems contain a file
        of suitable primes (usually named something like ``/etc/ssh/moduli``).
        If you call `load_server_moduli` and it returns ``True``, then this
        file of primes has been loaded and we will support "group-exchange" in
        server mode.  Otherwise server mode will just claim that it doesn't
        support that method of key negotiation.

        :param str filename:
            optional path to the moduli file, if you happen to know that it's
            not in a standard location.
        :return:
            True if a moduli file was successfully loaded; False otherwise.

        .. note:: This has no effect when used in client mode.
        """
        Transport._modulus_pack = ModulusPack()
        # places to look for the openssh "moduli" file
        file_list = ['/etc/ssh/moduli', '/usr/local/etc/moduli']
        if filename is not None:
            file_list.insert(0, filename)
        for fn in file_list:
            try:
                Transport._modulus_pack.read_file(fn)
                return True
            except IOError:
                pass
        # none succeeded
        Transport._modulus_pack = None
        return False
transport.py 文件源码 项目:SublimeRemoteGDB 作者: summerwinter 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def getpeername(self):
        """
        Return the address of the remote side of this Transport, if possible.
        This is effectively a wrapper around ``'getpeername'`` on the underlying
        socket.  If the socket-like object has no ``'getpeername'`` method,
        then ``("unknown", 0)`` is returned.

        :return:
            the address of the remote host, if known, as a ``(str, int)``
            tuple.
        """
        gp = getattr(self.sock, 'getpeername', None)
        if gp is None:
            return 'unknown', 0
        return gp()
my_paramiko.py 文件源码 项目:blockhouse 作者: yangliw3 项目源码 文件源码 阅读 14 收藏 0 点赞 0 评论 0
def run(host, port, username, password, blockhouseuser_id=""):

    # hostname = "192.168.126.230"
    # port = 6322
    # username = "bwweb"
    # pwd = "123456"

    global blockhouseuser_glo_id
    blockhouseuser_glo_id = blockhouseuser_id


    # ?????,??????????
    tran = paramiko.Transport((host, port,))
    tran.start_client()
    tran.auth_password(username, password)

    # ??????
    chan = tran.open_session()
    # ??????
    chan.get_pty()
    # ???
    chan.invoke_shell()

    interactive_shell(chan)

    chan.close()
    tran.close()
ansible.py 文件源码 项目:_ 作者: zengchunyun 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def connect_server(self):
        """
        ??????
        :return:
        """
        transport = paramiko.Transport((self.host, self.port))
        transport.connect(username=self.username, password=self.password)
        self.__transport = transport


问题


面经


文章

微信
公众号

扫码关注公众号