1、导入paramiko 模块#!/usr/bin/pythonimport paramiko
2、创建 ssh 连接函数def ssh_connect( _host, _username巳呀屋饔, _password ): try: _ssh_fd = paramiko.SSHCli髫潋啜缅ent() _ssh_fd.set_missing_host_key_policy( paramiko.AutoAddPolicy() ) _ssh_fd.connect( _host, username = _username, password = _password ) except Exception, e: print( 'ssh %s@%s: %s' % (_username, _host, e) ) exit() return _ssh_fd
3、创建命令执行函数def ssh_exec_cmd( _ssh_fd, _cmd ): return _ssh_fd.exec_command( _cmd )
4、创建关闭 ssh 函数def ssh_close( _ssh_fd ): _ssh_fd.close()
5、使用示例if __name__ == '__main__': sshd = s衡痕贤伎sh_connect( '192.168.134.220', 'root', '1' ) stdin, stdout, stderr = ssh_exec_cmd( sshd, 'ls' ) err_list = stderr.readlines() if len( err_list ) > 0: print 'ERROR:' + err_list[0] exit() for item in stdout.readlines(): print item, ssh_close( sshd )