求python pexpect ssh登陆的封装,要能处理ssh无密码等情形,python报错-问答-阿里云开发者社区-阿里云

开发者社区> 问答> 正文

求python pexpect ssh登陆的封装,要能处理ssh无密码等情形,python报错

python小菜菜 2020-05-27 14:48:23 99

"

求python pexpect ssh登陆的封装,要能处理ssh无密码等情形,代码简洁。

linux 

centos 6.5

" ![image.png](https://ucc.alicdn.com/pic/developer-ecology/78895a4bf55142aba3422e84b80431db.png)
网络安全 数据安全/隐私保护 Python
分享到
取消 提交回答
全部回答(1)
  • python小菜菜
    2020-05-27 15:37:36

    class Ssh(object):
        
        client = None
    
        @classmethod
        def connect(cls,ip,username="root",password="123456", prompt=']#',
            silent=False):
    
            # Ssh to remote server
            ssh_newkey = 'Are you sure you want to continue connecting'
            child = pexpect.spawn('ssh '+ username + '@'+ ip, maxread=5000)
            
            i = 1
            # Enter password
            while i != 0:
                i = child.expect([prompt, 'assword:*', ssh_newkey, pexpect.TIMEOUT, 
                    'key.*? failed'])
                if not silent:
                    print child.before,child.after,            
                if i == 0: # find prompt
                    pass      
                elif i == 1: # Enter password
                    child.send(password +"\r")  
                if i == 2: # SSH does not have the public key. Just accept it.
                    child.sendline ('yes\r')               
                if i == 3: # Timeout
                    raise Exception('ERROR TIMEOUT! SSH could not login. ')
                if i == 4: # new key
                    print child.before,child.after,
                    os.remove(os.path.expanduser('~')+'/.ssh/known_hosts')                     
    
            Ssh.client = child
            
    
    
    
        @classmethod
        def command(cls,cmd, prompt=']#', silent=False):
            Ssh.client.buffer = ''
            Ssh.client.send(cmd + "\r")
            #Ssh.client.setwinsize(400,400)
            Ssh.client.expect(prompt)
            if not silent:        
                print Ssh.client.before, Ssh.client.after,
            return Ssh.client.before, Ssh.client.after
        
        
        def close(cls,):
            Ssh.client.close()




    ######

    为啥不用paramiko呢?

    0 0
+ 订阅

云安全开发者的大本营

推荐文章
相似问题