"
求python pexpect ssh登陆的封装,要能处理ssh无密码等情形,代码简洁。
linux
centos 6.5
" 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呢?
云安全开发者的大本营