一、paramiko远程密码连接
题目要求:
基于ssh用于连接远程服务器做操作:远程执行命令
代码块:
import paramiko
#创建一个ssh对象
client = paramiko.SSHClient()
"""
The authenticity of host '172.25.254.254 (172.25.254.254)' can't be established.
ECDSA key fingerprint is 4c:98:51:43:65:46:66:fd:af:5b:ea:cc:d9:97:c0:74.
Are you sure you want to continue connecting (yes/no)?
"""
#自动选择yes
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#连接服务器
client.connect(
hostname='172.25.254.110',
username='root',
password='redhat'
)
#执行操作
#标准输入 标准输出 标准错误
stdin,stdout,stderr = client.exec_command('route -n')
#获取命令的执行结果
print(stdout.read().decode('utf-8'))
#关闭连接
client.close()
程序及运行结果:
二、paramiko批量连接主机
题目要求:
批量连接主机,若能连接请获取主机名,若不能请返回错误原因
操作如下:
为了获取批量的主机ip、用户一及用户密码,我们可以将其写在一个文件中,为方便获取,如下所示:
代码块:
from paramiko.ssh_exception import NoValidConnectionsError,AuthenticationException
def connect(cmd,hostname,user,password):
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(
hostname=hostname,
username=user,
password=password
)
stdin, stdout, stderr = client.exec_command(cmd)
a = stdout.read().decode('utf-8')
print(stdout.read().decode('utf-8'))
return a
except NoValidConnectionsError as e:
return '主机%s连接失败' %(hostname)
except AuthenticationException as e:
return '主机%s密码错误' %(hostname)
except Exception as e:
return '未知错误:',e
finally:
client.close()
with open('/tmp/hosts') as f:
for line in f:
hostname,username,password = line.strip().split(':')
res = connect('hostname',hostname,username,password)
# print(hostname.center(50,'*'))
print('主机名:', res)
程序及运行结果: