自动化运维模块(二)paramiko实现批量远程密码连接
代码如下:
from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException
import paramiko
def connect(cmd, hostname, user, password):
# 创建一个ssh对象
client = paramiko.SSHClient()
# 自动选择yes
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# 连接的服务器
client.connect(
hostname=hostname,
username=user,
password=password
)
except NoValidConnectionsError as e:
return '主机%s连接失败' % (hostname)
except AuthenticationException as e:
return '主机%s密码错误' % (hostname)
except Exception as e:
return '未知错误:', e
# 执行操作
# 标准输入 标准正确输出 标准错误输出
stdin, stdout, stderr = client.exec_command(cmd)
# 获取命令的执行结果
print(stdout.read().decode('utf-8'))
# 关闭连接
client.close()
with open('hosts') as f:
for line in f:
# 172.25.254.254:root:dd
hostname, username, password = line.strip().split(':')
res = connect('hostname', hostname, username, password)
print(hostname.center(50, '*'))
print('主机名:', )
编写文件hosts,格式自己定义:
172.25.254.250:root:dd
172.25.254.54:root:westos
172.25.254.11:root:westos
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnL5YTMwQzNwcTM2AjMwAjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
输出结果:
因为没有写返回值,所以主机名为none。