Python运维实战

1 paramiko 安装

  1. 依赖系统库安装(Linux)

    yum install -y openssl‑devel bzip2‑devel expat‑devel gdbm‑devel readline‑devel sqlite‑devel libffi‑devel gcc gcc‑c++

  2. 编译安装 Python3,建立软链接。

  3. 配置 pip 国内镜像源(pip.conf),加速下载。

  4. 安装模块:pip install paramiko

2 两大核心组件

2.1 SSHClient 类(用于执行远程 shell 命令)

  1. connect():建立 SSH 连接 参数:hostname主机,port端口默认 22,username用户名,password密码;支持私钥pkey、超时timeout等。
  2. set_missing_host_key_policy():处理未知主机密钥策略
  • AutoAddPolicy:自动添加主机密钥(日常脚本最常用)
  • RejectPolicy:默认策略,拒绝未知主机
  • WarningPolicy:告警后接受未知主机
  1. exec_command(command):执行远程命令 返回三元组:stdin, stdout, stderr;stdout 获取标准输出,stderr 获取错误输出。
  2. invoke_shell():开启交互式 shell 通道,堡垒机跳板必须使用该方法
  3. close():关闭 SSH 会话连接
案例 1:单台服务器执行远程命令

连接主机,执行free -m查看内存,读取 stdout 输出打印结果,最后关闭连接。

复制代码
import paramiko as pk

hostname = '10.1.8.150'
port = 22
username = 'root'
password = '123'
#日志
pk.util.log_to_file('syslogin.log')

#创建客户端
ssh_client = pk.SSHClient()

#设置连接策略
ssh_client.set_missing_host_key_policy(pk.AutoAddPolicy())

#连接服务器
ssh_client.connect(hostname=hostname,port=port,username=username,password=password,allow_agent=False)

#执行指令,获取信息
stdin, stdout, stderr = ssh_client.exec_command('free -m')

#解析输出质量
for line in stdout:
    print(line)

#关闭输入
stdin.close()

#关闭客户端
ssh_client.close()
案例 2:多服务器巡检脚本
  • 封装函数实现单台主机采集;

  • 循环遍历多台主机;

  • 获取内存空闲值,收集到列表;

  • 对数据排序;

  • 将结果写入本地 txt或csv 文件保存。

    import paramiko as pk
    import datetime

    def get_info(ip,port,usr,pwd):
    client = pk.SSHClient()
    client.set_missing_host_key_policy(pk.AutoAddPolicy())
    client.connect(ip,port,usr,pwd)
    stdin, stdout, stderr = client.exec_command("free -m | grep Mem | awk '{print $4}'")
    return stdout, stderr

    #主机清单
    host_list = ['10.1.8.150','10.1.8.250']
    infos=[]

    #巡检主机信息
    for i in host_list:
    mem,err = get_info(i,22,"root","123")
    for line in mem:
    infos.append(int(line))
    print(infos)

    #排序(可选)
    infos.sort(reverse=True)
    print(infos)

    new_list=[]
    for i in infos:
    new_list.append(str(i)+'\n')
    print(new_list)

    with open('D:\test\xunjian.csv','a') as f:
    f.write('\n==== ' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' ====\n')
    f.writelines(new_list)
    with open('D:\test\xunjian.txt','a') as f:
    f.write('\n==== ' + datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') + ' ====\n')
    f.writelines(new_list)
    print('巡检完成')

2.2 SFTPClient 类(SFTP,远程文件传输)

  1. from_transport(t):基于 transport 传输对象创建 sftp 会话
  2. put(localpath, remotepath):上传本地文件到远程服务器
  3. get(remotepath, localpath):下载远程文件保存到本地
  4. 目录 / 文件管理方法
  • mkdir():远程服务器创建目录
  • remove():删除文件
  • rename():重命名文件 / 目录
  • stat():获取远程文件属性信息
  • listdir():获取远程目录下所有文件名列表
案例:SFTP 文件操作

建立 transport 连接,创建 sftp 对象;完成文件上传、下载、创建目录、重命名、删除、查看目录列表。

复制代码
import paramiko as pk
#四要素
host = '10.1.8.150'
port = 22
user = 'root'
pwd = '123'

try:
    #建立传输通道
    t=pk.Transport(host,port)
    #建立拦截
    t.connect(username=user,password=pwd)
    #SFTP客户端
    sftp=pk.SFTPClient.from_transport(t)
    #文件上传
    sftp.put('syslogin.log','/root/abc/syslogin1.log')
    print('文件上传成功!')
    # #文件下载
    sftp.get('/root/abc/syslogin1.log','D:\\test\\syslogin1.log')
    print('文件下载成功!')
    #创建目录
    sftp.mkdir('fengkai')
    print('创建成功!')
    #重命名
    sftp.rename('fengkai','fengkai1111')
    print('修改成功!')
    # #删除目录
    sftp.rmdir('fengkai1111')
    print('删除成功!')
    #查看状态
    print(sftp.stat('./abc/syslogin.log'))

    #查看文件列表
    print(sftp.listdir('./abc'))

    t.close()
    print('SFTP连接关闭!')
except Exception as e:
    print(e)

3 堡垒机跳板实战

场景 1:堡垒机跳转执行业务服务器命令

业务流程:

  1. SSHClient 登录堡垒机;

  2. invoke_shell()打开交互式 shell 通道;

  3. channel.send()发送ssh username@业务IP;

  4. 程序接收返回缓冲区,判断yes/no确认、密码提示符;

  5. send 发送密码完成登录业务主机;

  6. send 发送业务命令,接收输出打印结果;

  7. 关闭 channel、ssh 连接。

    import paramiko as pk
    import os,sys,time

    #堡垒机/业务主机的四要素
    blip='10.1.8.150'
    host='10.1.8.250'
    bluser=user='root'
    blpwd=pwd='123'
    port=22

    #提示密码输入
    passinfo=''s password: '

    #日志
    pk.util.log_to_file('system.log')

    #登陆堡垒机
    ssh=pk.SSHClient()
    ssh.set_missing_host_key_policy(pk.AutoAddPolicy())
    ssh.connect(hostname=blip,port=port,username=bluser,password=blpwd)

    #启动ssh会话,并设置超时时间
    channel=ssh.invoke_shell()
    channel.settimeout(10)

    #回应内容
    buff=''
    resp=''

    #远程登陆
    channel.send('ssh '+user+'@'+host+'\n')

    #连接业务服务器
    while not buff.endswith(passinfo):
    try:
    resp=channel.recv(9999).decode('utf-8')
    except Exception as e:
    print('远程登陆失败!',e)
    channel.close()
    ssh.close()
    sys.exit()
    #内容累加
    buff+=resp
    #第一次连接
    if not buff.find('yes/no')==-1:
    channel.send('yes\n')
    buff=''
    #发送密码
    channel.send(pwd+'\n')
    buff=''
    while not buff.endswith(']# '):
    resp=channel.recv(9999).decode('utf-8')
    if not resp.find(passinfo)==-1:
    print('密码验证失败!')
    channel.close()
    ssh.close()
    sys.exit()
    buff+=resp

    #成功登陆业务服务器,开始发送指令
    channel.send('ip -br a\n')
    buff=''
    try:
    while buff.find('# ')==-1:
    resp=channel.recv(9999).decode('utf-8')
    buff+=resp
    except Exception as e:
    print('命令执行失败!',e)
    channel.close()
    ssh.close()
    sys.exit()
    #内容输出
    print(buff)
    channel.close()
    ssh.close()

场景 2:堡垒机中转上传文件

业务流程:

  1. 使用 SFTPClient 把本地文件上传至堡垒机临时目录(如 /tmp);

  2. SSHClient 登录堡垒机,invoke_shell 打开交互通道;

  3. send 发送scp命令,将堡垒机临时文件拷贝到后端业务服务器;

  4. 处理密码交互,完成中转上传。

    #使用之前场景1 的代码,结合SFTP 文件操作的代码做融合
    import paramiko as pk
    import os,sys,time,re

    #堡垒机/业务主机的四要素
    blip='10.1.8.150'
    host='10.1.8.250'
    bluser=user='root'
    blpwd=pwd='123'

    #堡垒机临时目录
    tmdir='/tmp'
    #业务服务器创建目录
    remotedir='/data'
    #本地文件路径
    localpath='D:\test\222.txt'
    #堡垒机临时路径
    tmppath=tmdir+'/222.txt'
    #业务服务器文件路径
    remotepath=remotedir+'/222.txt'

    port=22

    #提示密码输入
    passinfo=''s password: '
    #【新增】提示符正则:主机 PS1 带 ANSI 颜色码,提示符实际结尾是 "]#" + \x1b[0m + 空格,
    #原来的 buff.endswith(']# ') 永远匹配不上,导致 recv 超时。
    #这里改成正则匹配:# 或 后面允许跟任意个 ANSI 颜色码再结尾 prompt_re=re.compile(r'[#\$](\x1b\[[0-9;]*m)*\s*')

    #日志
    pk.util.log_to_file('system.log')

    t=pk.Transport(blip,port)
    t.connect(username=bluser,password=blpwd)
    sftp=pk.SFTPClient.from_transport(t)
    #本地文件上传到堡垒机
    sftp.put(localpath,tmppath)
    sftp.close()

    #登陆堡垒机
    ssh=pk.SSHClient()
    ssh.set_missing_host_key_policy(pk.AutoAddPolicy())
    ssh.connect(hostname=blip,port=port,username=bluser,password=blpwd)

    #启动ssh会话,并设置超时时间
    channel=ssh.invoke_shell()
    channel.settimeout(30) #【修改】10 秒偏短,放宽到 30 秒

    #回应内容
    buff=''
    resp=''

    #远程登陆,并执行scp命令
    channel.send('scp '+tmppath+' '+user+'@'+host+':'+remotepath+'\n')

    #连接业务服务器
    while not buff.endswith(passinfo):
    try:
    resp=channel.recv(9999).decode('utf-8')
    except Exception as e:
    print('远程登陆失败!',e)
    channel.close()
    ssh.close()
    sys.exit()
    #【新增】对端关闭兜底
    if not resp:
    print('连接被对端关闭!')
    channel.close()
    ssh.close()
    sys.exit()
    #内容累加
    buff+=resp
    #第一次连接
    if not buff.find('yes/no')==-1:
    channel.send('yes\n')
    buff=''
    #发送密码
    channel.send(pwd+'\n')
    buff=''
    #【修改】endswith(']# ') 改为正则匹配提示符(容忍 # 后面的 ANSI 颜色码)
    while not prompt_re.search(buff):
    resp=channel.recv(9999).decode('utf-8')
    #【新增】recv 返回空串说明对端关闭连接,不处理会死循环
    if not resp:
    print('连接被对端关闭!')
    channel.close()
    ssh.close()
    sys.exit()
    if not resp.find(passinfo)==-1:
    print('密码验证失败!')
    channel.close()
    ssh.close()
    sys.exit()
    buff+=resp

    #成功登陆业务服务器,开始发送指令

    channel.send('ip -br a\n')

    buff=''

    try:

    while buff.find('# ')==-1:

    resp=channel.recv(9999).decode('utf-8')

    buff+=resp

    except Exception as e:

    print('命令执行失败!',e)

    channel.close()

    ssh.close()

    sys.exit()

    #内容输出
    print(buff)
    channel.close()
    ssh.close()

注意事项

  1. 完成连接后务必调用 close 关闭连接,释放资源;
  2. 开启日志:paramiko.util.log_to_file("syslogin.log")记录 ssh 日志,方便排错;
  3. invoke_shell()交互式需要处理缓冲区 recv 接收返回数据,判断提示符完成交互;
  4. put/get 必须指定完整文件名,不能只写目录。

思维导图

相关推荐
用户454284510628134 分钟前
一张 3000×2000 的 PSD 为什么 86MB:从体积构成到上传墙
python
那明眸似水1 小时前
LVS高可用负载均衡集群部署实训
运维·负载均衡·lvs
用户298698530141 小时前
使用 Python 提取 Word 文档中的文本与图片
后端·python·api
MSTcheng.1 小时前
【LinuxIO篇】Linux学习第二十三弹——fopen和open有什么区别?从 FILE* 到 fd,讲透 Linux 文件 IO
linux·运维·学习·io·系统调用·fd
charliejohn1 小时前
计算机考研 408 网络 DNS 概念
运维·服务器·网络
用户0332126663672 小时前
使用 Python 在 PDF 中创建表单域
python
BullSmall2 小时前
Jenkins Git插件报错?6步修复+预防指南
运维·jenkins
ShineWinsu2 小时前
对于Qt:重写事件步骤的解析
开发语言·c++·qt·客户端·事件·鼠标事件·步骤
分布式存储与RustFS2 小时前
向量库快照只落在本地盘:换节点恢复时把 RustFS 桶当副本源
运维·云原生·开源·对象存储·分布式存储·s3·性能基准