"
求python pexpect ssh登陆的封装,要能处理ssh无密码等情形,代码简洁。
linux
centos 6.5
" ![image.png](https://ucc.alicdn.com/pic/developer-ecology/78895a4bf55142aba3422e84b80431db.png)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呢?
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。