开发者社区> 问答> 正文

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

"

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

linux 

centos 6.5

" ![image.png](https://ucc.alicdn.com/pic/developer-ecology/78895a4bf55142aba3422e84b80431db.png)

展开
收起
python小菜菜 2020-05-27 14:48:23 902 0
1 条回答
写回答
取消 提交回答
  • 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呢?

    2020-05-27 15:37:36
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
From Python Scikit-Learn to Sc 立即下载
Data Pre-Processing in Python: 立即下载
双剑合璧-Python和大数据计算平台的结合 立即下载