Python运维自动化开发之Paramiko模块

本章讲解使用Python语言的paramiko模块编写服务器批量管理脚本,可完成一些常规任务,例如自动化部署软件、批量执行命令、文件传输等。除了Paramiko模块,还有相同作用的fabric和pexpect模块。

Paramiko模块是基于Python实现的SSH远程安全连接,用于SSH远程执行命令、文件传输等功能。默认Python没有自带,需要手动安装:pip install paramiko
如果安装失败,可以尝试yum安装:yum install python-paramiko
示例:

1、SSH密码认证远程执行命令

#!/usr/bin/python
# -*- coding: utf-8 -*-
import paramiko
import sys
hostname = '192.168.1.215'port = 22username = 'root'password = '123456'client = paramiko.SSHClient()  # 绑定实例
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname, port, username, password, timeout=5)
stdin, stdout, stderr = client.exec_command('df -h')   # 执行bash命令
result = stdout.read()
error = stderr.read()
# 判断stderr输出是否为空,为空则打印执行结果,不为空打印报错信息if not error:
   print resultelse:
   print error
client.close()

2、私钥认证远程执行命令

#!/usr/bin/python
# -*- coding: utf-8 -*-
import paramiko
import sys
hostname = '192.168.1.215'port = 22username = 'root'key_file = '/root/.ssh/id_rsa'cmd = " ".join(sys.argv[1:])
def ssh_conn(command):
    client = paramiko.SSHClient()
    key = paramiko.RSAKey.from_private_key_file(key_file)
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(hostname, port, username, pkey=key)
    stdin, stdout, stderr = client.exec_command(command)  # 标准输入,标准输出,错误输出
    result = stdout.read()
    error = stderr.read()    if not error:
        print result    else:
        print error
    client.close()if __name__ == "__main__":
    ssh_conn(cmd)

3、上传文件到远程服务器

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, sys
import paramiko
hostname = '192.168.1.215'port = 22username = 'root'password = '123456'local_path = '/root/test.txt'remote_path = '/opt/test.txt'if not os.path.isfile(local_path):
    print local_path + " file not exist!"
    sys.exit(1)try:
    s = paramiko.Transport((hostname, port))
    s.connect(username = username, password=password)
except Exception as e:
    print e
    sys.exit(1)
sftp = paramiko.SFTPClient.from_transport(s)
# 使用put()方法把本地文件上传到远程服务器
sftp.put(local_path, remote_path)       
# 简单测试是否上传成功try:
    # 如果远程主机有这个文件则返回一个对象,否则抛出异常               
    sftp.file(remote_path) 
    print "上传成功."except IOError:
    print "上传失败!"finally:
    s.close()

4、从远程服务器下载文件

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, sys
import paramiko
hostname = '192.168.1.215'port = 22username = 'root'password = '123456'local_path = '/root/test.txt'remote_path = '/opt/test.txt'try:
    s = paramiko.Transport((hostname, port))
    s.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(s)
except Exception as e:
    print e
    sys.exit(1)try:
    # 判断远程服务器是否有这个文件
    sftp.file(remote_path)
    # 使用get()方法从远程服务器拉去文件
    sftp.get(remote_path, local_path)       
except IOError as e:
    print remote_path + "remote file not exist!"
    sys.exit(1)finally:
    s.close()
# 测试是否下载成功if os.path.isfile(local_path):
    print "下载成功."else:
    print "下载失败!"

5、上传目录到远程服务器

paramiko模块并没有实现直接上传目录的类,已经知道了如何上传文件,再写一个上传目录的代码就简单了,利用os库的os.walk()方法遍历目录,再一个个上传:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import os, sys
import paramiko
hostname = '192.168.1.215'port = 22username = 'root'password = '123456'local_path = '/root/abc'remote_path = '/opt/abc'# 去除路径后面正斜杠if local_path[-1] == '/':
    local_path = local_path[0:-1]if remote_path[-1] == '/':
    remote_path = remote_path[0:-1]
file_list = []if os.path.isdir(local_path):    for root, dirs, files in os.walk(local_path):        for file in files:
            # 获取文件绝对路径
            file_path = os.path.join(root, file) 
            file_list.append(file_path)else:
    print path + "Directory not exist!"
    sys.exit(1)try:
    s = paramiko.Transport((hostname, port))
    s.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(s)
except Exception as e:
    print efor local_file in file_list:
    # 替换目标目录
    remote_file = local_file.replace(local_path, remote_path)
    remote_dir = os.path.dirname(remote_file)
    # 如果远程服务器没目标目录则创建    try:
        sftp.stat(remote_dir)
    except IOError:
        sftp.mkdir(remote_dir)
    print "%s -> %s" % (local_file, remote_file)
    sftp.put(local_file, remote_file)
s.close()

sftp是安全文件传输协议,提供一种安全的加密方法,sftp是SSH的一部分,SFTPClient类实现了sftp客户端,通过已建立的SSH通道传输文件,与其他的操作,如下:
Python运维自动化开发之Paramiko模块

Python运维自动化开发之Paramiko模块

上一篇:网工Python之路之paramiko 模块实验(一)初来乍到


下一篇:运维少年系列 python and cisco (3)