安装paramiko第三方模块
ssh是一个协议,OpenSSH是其中一个开源实现,paramiko是Python的一个库,实现了SSHv2协议(底层使用cryptography)。
有了Paramiko以后,我们就可以在Python代码中直接使用SSH协议对远程服务器执行操作,而不是通过ssh命令对远程服务器进行操作。
由于paramiko属于第三方库,所以需要我们先安装。
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.18',
username='root',
password='redhat'
)
#执行操作
#标准输入 标准输出 标准错误
stdin,stdout,stderr = client.exec_command('route -n')
#获取命令的执行结果
print(stdout.read().decode('utf-8'))
#关闭连接
client.close()
批量连接主机
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
# stdin,stdout,stderr = client.exec_command(cmd)
# print(stdout.read().decode('utf-8'))
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)
文件的上传和下载
'''给远程主机上传一个文件'''
from paramiko.ssh_exception import NoValidConnectionsError,AuthenticationException
import paramiko
def put(hostname,password,local_name,remote_name):
try:
transport = paramiko.Transport((hostname,22))
transport.connect(username='root',password=password)
sftp = paramiko.SFTPClient.from_transport(transport)
except AuthenticationException as e:
return '主机%s密码错误' %(hostname)
except Exception as e:
return '未知错误: ',e
else:
sftp.put(local_name,remote_name) ##上传文件
try:
# 如果远程主机有这个文件则返回一个对象,否则抛出异常
sftp.file(remote_name)
print("上传成功.")
except IOError:
print("上传失败!")
finally:
transport.close()
put('172.25.254.16','westos','/home/kiosk/passwd','/mnt/test') ##远程主机ip,密码,本地文件,上传后的文件保存位置
'''从远程主机下载文件'''
from paramiko.ssh_exception import NoValidConnectionsError,AuthenticationException
import paramiko
import os
def get(hostname,password,remote_name,local_name):
try:
transport = paramiko.Transport((hostname,22))
transport.connect(username='root',password=password)
sftp = paramiko.SFTPClient.from_transport(transport)
except AuthenticationException as e:
return '主机%s密码错误' %(hostname)
except Exception as e:
return '未知错误: ',e
else:
#sftp.put(local_name,remote_name) ##上传文件
sftp.get(remote_name,local_name) ##下载文件
if os.path.exists(local_name):
print('下载成功.')
else:
print('下载失败')
finally:
transport.close()
get('172.25.254.16','westost','/tmp/passwd','/tmp/test.tex)