Python之paramiko模块

78 篇文章 3 订阅
24 篇文章 2 订阅

Python之paramiko模块

  • 什么是paramiko模块

paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接(ssh)

  • paramiko模块的示例

ssh远程密码连接一个ip:

import paramiko

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

# 自动选择yes(没有连接过的)
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
client.connect(
    hostname='172.25.254.1',
    username='root',
    password='redhat'
)
# 执行操作
# 标准输入 标准输出 标准错误输出
stdin,stdout,stderr = client.exec_command('')
# 获取命令的执行结果
print(stdout.read().decode('utf-8'))
# 关闭连接
client.close()

ssh批量远程密码连接多个ip:

from paramiko.ssh_exception import\
    NoValidConnectionsError,AuthenticationException

def connect(cmd,hostname,user,password):
    import paramiko
    # 创建一个ssh对象
    client = paramiko.SSHClient()
    # 解决的问题:如果之前没有连接过的ip(主机),会出现
    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('hostname')
    # 获取命令的执行结果
    print(stdout.read().decode('utf-8'))

    # 关闭连接
    client.close()

if __name__ == '__main__':
    with open('hosts') as f:
        for line in f:
            # 172.25.0.250:root:dd
            hostname,username,password = line.strip().split(':')
            res = connect('pwd',hostname,username,password)
            print(hostname.center(50,'*'))
            print('主机名:',res)

创建的密码文件hosts:

172.25.254.250:root:dd
172.25.254.251:root:westos
172.25.254.13:root:westos
172.25.0.101:root:redhat
172.25.0.101:root:yy
172.25.0.19:root:westos

ssh基于公钥和私钥的连接:

要注意的是:我们当前用户(执行此程序的用户)要免密连接的一台主机、
用户拿到的是私钥 要连接的主机要挂载公钥

import paramiko
client = paramiko.SSHClient()
# 创建一个私钥对象
private_key = paramiko.RSAKey.\
    from_private_key_file('/home/kiosk/.ssh/id_rsa')
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
client.connect(
    hostname='172.25.0.250',
    username='root',
    pkey=private_key
)
# 执行操作
# 标准输入 标准输出 标准错误输出
stdin,stdout,stderr = client.exec_command('')
# 获取命令的执行结果
print(stdout.read().decode('utf-8'))
# 关闭连接
client.close()

基于用户和密码的上传和下载文件:

import paramiko
from paramiko import AuthenticationException,SSHException

def put(hostname,password,source_name,target_name):
    try:
        # 类似于ssh+ftp命令
        # 建立与远程主机的通道
        tarnsport = paramiko.Transport((hostname,22))
        # 验证用户名和密码是否正确
        tarnsport.connect(username='root',password=password)
        # 根据创建并验证成功的通道
        sftp = paramiko.SFTPClient.from_transport(tarnsport)
    except AuthenticationException as e:
        return '主机%s密码错误' %(hostname)
    except Exception as e:
        return '未知错误:',e
    else:
        # 上传文件
        sftp.put(source_name,target_name)
        # 下载文件
        # sftp.get('/mnt/name')

    finally:
        # 关闭两台主机建立的通道
        tarnsport.close()

put('172.25.254.250','dd','/etc/passwd','/mnt/172.25.254.250')
  • 自定义一个字体颜色模块
class FontColor:
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARN = '\033[93m'
    FAIL = '\033[91m'

#if __name__ == '__main__':
f = FontColor()
print(f.OKBLUE + 'hello')
print(f.OKGREEN + 'hello')
print(f.WARN + 'hello')
print(f.FAIL + 'hello')

效果如图:
在这里插入图片描述
下次调用:import color

END

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值