4. 批量远程密码连接
- from paramiko.ssh_exception import NoValidConnectionsError
- from paramiko.ssh_exception import AuthenticationException
- def connect(cmd,hostname,port=22,username='root',passwd='westos'):
- import paramiko
- ##1.创建一个ssh对象
- client = paramiko.SSHClient()
- #2.解决问题:如果之前没有,连接过的ip,会出现选择yes或者no的操作,
- ##自动选择yes
- client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
- #3.连接服务器
- try:
- client.connect(hostnamehostname=hostname,
- portport=port,
- usernameusername=username,
- password=passwd)
- print('正在连接主机%s......'%(hostname))
- except NoValidConnectionsError as e: ###用户不存在时的报错
- print("连接失败")
- except AuthenticationException as t: ##密码错误的报错
- print('密码错误')
- else:
- #4.执行操作
- stdin,stdout, stderr = client.exec_command(cmd)
- #5.获取命令执行的结果
- result=stdout.read().decode('utf-8')
- print(result)
- #6.关闭连接
- finally:
- client.close()
- with open('ip.txt') as f: #ip.txt为本地局域网内的一些用户信息
- for line in f:
- lineline = line.strip() ##去掉换行符
- hostname,port,username,passwd= line.split(':')
- print(hostname.center(50,'*'))
- connect('uname', hostname, port,username,passwd)
(编辑:惠州站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|