paramiko(基于ssh用于连接远程服务器)

paramiko(基于ssh用于连接远程服务器)

1.ssh的linux远程连接过程

ssh username@ip passwd

#解决的问题:如果只前没有连接过的ip 会出现
"""
[root@foundation0 .ssh]# ssh [email protected]
The authenticity of host '172.25.254.36 (172.25.254.36)' can't be established.
ECDSA key fingerprint is bc:f5:f7:4b:39:41:d8:27:61:b0:56:55:e5:05:a9:5b.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '172.25.254.36' (ECDSA) to the list of known hosts.
[email protected]'s password: 
Last login: Sun Jan 12 10:16:28 2020
[root@foundation54 ~]# exit
logout
Connection to 172.25.254.36 closed.
[root@foundation0 .ssh]# ssh [email protected]
[email protected]'s password: 

"""

parammiko
基于ssh用于连接远程服务操作包:
远程执行命令
上传命令

import paramiko

# 创建一个ssh对象
client = paramiko.SSHClient()

# 自动选择yes
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# 连接的服务器
client.connect(
    hostname='172.25.254.11',
    username='root',
    password='westos'
)

# 执行操作
# 标准输入 标准正确输出 标准错误输出
stdin,stdout,stderr = client.exec_command('hostname')
# 获取命令的执行结果
print(stdout.read().decode('utf-8'))

# 关闭连接
client.close()

2.paramiko批量远程密码连接

from paramiko.ssh_exception import NoValidConnectionsError, AuthenticationException
import paramiko


def connect(cmd, hostname, user, password):
    # 创建一个ssh对象
    client = paramiko.SSHClient()
    # 自动选择yes
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        # 连接的服务器
        client.connect(
            hostname=hostname,
            username=user,
            password=password
        )

    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'))
    # 关闭连接
    client.close()

with open('hosts') as f:
    for line in f:
        # 172.25.254.254:root:dd
        hostname, username, password = line.strip().split(':')
        print(hostname.center(50, '*'))
        print('用户名:%s' % (username))
        res = connect('hostname', hostname, username, password)

3.paramiko批量远程上传和下载

import paramiko
transport = paramiko.Transport(('172.25.60.250', 22))
transport.connect(username='root', password='westos')
sftp = paramiko.SFTPClient.from_transport(transport)
# 上传文件, 包含文件名(将当前电脑中的文件上传到地址为172.25.60.250的电脑中)
sftp.put('/home/kiosk/Desktop/test/passwd1', '/home/kiosk/Desktop/haha')
transport.close()

import paramiko
transport = paramiko.Transport(('172.25.254.13', 22))
transport.connect(username='root', password='westos')
sftp = paramiko.SFTPClient.from_transport(transport)
# 下载文件文件, 包含文件名(将ip地址为172.25.60.250电脑中的文件下载到当前的文件夹中)
sftp.get('/home/kiosk/dd1', 'dd1')
transport.close()

你可能感兴趣的:(paramiko(基于ssh用于连接远程服务器))