版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/88071818
一 点睛
实现堡垒机模式下的文件上传,原理是通过paramiko的SFTPClient将文件从办公设备上传至堡垒机指定的临时目录,如/tmp,再通过SSHClient的invoke_shell方法开启ssh会话,执行scp命令,将/tmp下的指 定文件复制到目标业务服务器上。
二 原理图
三 原理说明
使用sftp.put()方法上传文件至堡垒机临时目录,再 通过send()方法执行scp命令,将堡垒机临时目录下的文件复制到目标主机。
四 代码
#coding=utf-8
#!/usr/bin/env python
import paramiko
import os,sys,time
hostname="192.168.0.120" # 定义业务服务器信息
username="root"
password="waDY820828"
blip="192.168.0.101" # 定义堡垒机信息
bluser="root"
blpasswd="waDY820828"
tmpdir="/tmp"
remotedir="/data"
localpath="1_2_2.py" # 本地源文件路径
tmppath=tmpdir+"/1_2_2.py" # 堡垒机临时路径
remotepath=remotedir+"/1_2_2.py" # 业务主机目标路径
port=22
passinfo='\'s password: '
paramiko.util.log_to_file('syslogin.log')
t = paramiko.Transport((blip, port))
t.connect(username=bluser, password=blpasswd)
sftp =paramiko.SFTPClient.from_transport(t)
sftp.put(localpath, tmppath) # 上传本地源文件到堡垒机临时路径
sftp.close()
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=blip,username=bluser,password=blpasswd)
#new session
channel=ssh.invoke_shell()
channel.settimeout(10)
buff = ''
resp = ''
# scp中转临时文件到目标主机
channel.send('scp '+tmppath+' '+username+'@'+hostname+':'+remotepath+'\n')
while not buff.endswith(passinfo):
try:
resp = channel.recv(9999)
except Exception,e:
print 'Error info:%s connection time.' % (str(e))
channel.close()
ssh.close()
sys.exit()
buff += resp
if not buff.find('yes/no')==-1:
channel.send('yes\n')
buff=''
channel.send(password+'\n')
buff=''
while not buff.endswith('# '):
resp = channel.recv(9999)
if not resp.find(passinfo)==-1:
print 'Error info: Authentication failed.'
channel.close()
ssh.close()
sys.exit()
buff += resp
print buff
channel.close()
ssh.close()
五 运行
E:\Python\python_auto_maintain\venv\Scripts\python.exe E:/Python/python_auto_maintain/6_3_3.py
1_2_2.py 100% 512 0.5KB/s 00:00
[root@slave2 ~]#
六 执行结果
文件已拷贝到业务主机