Python远程连接主机之paramiko模块

python基础

浏览数:43

2019-10-9

  Python的paramiko模块能够连接远程主机,并在该主机上执行命令,和该主机之间进行文件传输。paramiko支持用明文密码登录远程主机和秘钥登录。使用之前要安装一下这个模块哈,pip install paramiko,不会安装可以百度哈。

(1)密码登录

#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Author: "Liuyouyuan"
# Date: 2018/1/23

import paramiko

def run_cmd(host, port, user, passwd, cmd):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=host, port=port, username=user, password=passwd)
    stdin, stdout, stderr = ssh.exec_command(cmd)

    stdout = stdout.read()
    stderr = stderr.read()
    ssh.close()
    if not stderr:
        print(stdout.decode())
    else:
        print(stderr.decode())

if __name__ == '__main__':
    HOST = "10.129.205.151"
    PORT = 22
    USER = "root"
    PASSWD = "******"
    cmd = "df -h"
    run_cmd(HOST, PORT, USER, PASSWD, cmd)

 来看执行结果:

Filesystem           Size  Used Avail Use% Mounted on
/dev/mapper/cl-root   17G  6.8G   11G  40% /
devtmpfs             897M     0  897M   0% /dev
tmpfs                912M   84K  912M   1% /dev/shm
tmpfs                912M  9.0M  903M   1% /run
tmpfs                912M     0  912M   0% /sys/fs/cgroup
/dev/sda1           1014M  173M  842M  18% /boot
tmpfs                183M   16K  183M   1% /run/user/42
tmpfs                183M     0  183M   0% /run/user/0

(2)秘钥登录

def run_cmd_pkey(host, port, user, rsa_file):
    """
    linux 端创建秘钥  ssh-keygen
    把要连的机子的公钥改名 mv id_rsa.pub authorized_keys
    想要连接哪台机器就直接把公钥copy到该机器的用户home下 格式:/root/.ssh
    """
    private_key = paramiko.RSAKey.from_private_key_file(rsa_file)  # 指定私钥所在文件
    ssh = paramiko.SSHClient()                                     # 创建ssh对象

    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())               # 允许连接不在know_hosts文件中的主机
    ssh.connect(hostname=host, port=port, username=user, pkey=private_key)  # 连接服务器
    stdin, stdout, stderr = ssh.exec_command("df")                          # 执行命令

    stdout = stdout.read()
    stderr = stderr.read()
    ssh.close()                  # 关闭连接
    if not stderr:
        print(stdout.decode())
    else:
        print(stderr.decode())

(3)上传下载文件明文密码版本

import paramiko
def ssh_transfer_file(host, port, user, passwd, local_file, remote_file):
    transport = paramiko.Transport(host, port)
    transport.connect(username=user, password=passwd)
    sftp = paramiko.SFTPClient.from_transport(transport)
    # sftp.put(local_file, remote_file)            # 从本地上传文件到远程主机
    sftp.get(remote_file, local_file)              # 从远程主机下载到本地
    transport.close()


if __name__ == '__main__':
    HOST = "10.129.205.151"
    PORT = 22
    USER = "root"
    PASSWD = "******"
    cmd = "df -h"
    remote_file = "/data/download/nginx-1.12.0.tar.gz"
    local_file = "nginx-1.12.0.tar.gz"
    ssh_transfer_file(HOST, PORT, USER, PASSWD, local_file, remote_file)

 先测试下下载功能。

首先看下远程主机上的文件:


[root@liuyouyuan download]# ll /data/download
total 17444
drwxr-xr-x.  9 lyy  lyy       186 Jul 19  2017 nginx-1.12.0
-rw-r--r--.  1 root root   980831 Apr 12  2017 nginx-1.12.0.tar.gz
drwxr-xr-x. 18  501  501     4096 Jul 19  2017 Python-3.6.1
-rw-r--r--.  1 root root 16872064 Mar 21  2017 Python-3.6.1.tar.xz

然后运行代码后看看本地:

这就已经把nginx压缩包下载到本地了。上传功能就不做演示了,有兴趣的可以自己测试一下哈。

(4)上传下载文件秘钥版

def ssh_transfer_file_pkey(host, port, user, rsa_file, local_file, remote_file):
    private_key = paramiko.RSAKey.from_private_key_file(rsa_file)   # 指定私钥所在文件
    transport = paramiko.Transport(host, port)
    transport.connect(username=user, pkey=private_key)
    sftp = paramiko.SFTPClient.from_transport(transport)

    sftp.put(local_file, remote_file)             # 从本地上传文件到远程主机
    # sftp.get(remote_file, local_file)           # 从远程主机下载到本地
    transport.close()

 是不是比较简单呢?

作者:ZingpLiu