python模块之 paramiko

python模块之 paramiko

安装

该模块提供了ssh及sft进行远程登录服务器执行命令和上传下载文件功能,为第三方软件包,需要安装

pip install paramiko --user

1基于用户名和密码的sshclient方式登录

#建立一个sshclient对象
import paramiko
ssh=paramiko.SSHClient()
#允许将信任的主机自动加入到host_allow列表,需放在connect方法前面
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#调用connect方法链接服务器
ssh.connect(hostname='xxx.xx.xx.xxx',port=22,username='xxxx',password='xxxx')
#执行命令
stdin,stdout,stderr=ssh.exec_command('df hl')
#结果在stdout,有错误在stderr
print stdout.read().decode()
#关闭链接
ssh.close()

2基于用户名和密码的transport方式登录

方法一只能单一的链接、执行命令、关闭这一套操作,需要登录服务器实现一系列的操作(比如文件上传下载)则需要用如下方法

import paramiko
trans=paramiko.Transport(('xxx.xxx.xx.xxx',22))
#建立链接
trans.connect(username='xxx',password='xxxx')
ssh=paramiko.SSHClient()
ssh._transport=trans
#执行命令
stdin,stdout,stderr=ssh.exec_command('df -lh')
print stdout.read().decode()
#文件传输
#实例化一个sftp对象,指定链接的通道
sftp=paramiko.SFTPClient.from_transport(trans)
#发送文件
sftp.get(remotepath,localpath)
#关闭链接
trans.close()

3基于公钥密钥的SSHClient方式登录

# 指定本地的RSA私钥文件,如果建立密钥对时设置的有密码,password为设定的密码,如无不用指定password参数
pkey=paramiko.RSAKey.from_private_key_file('/home/xxx.rsa',password='xxxx')
#建立链接
ssh=paramiko.SSHClient()
ssh.connect(hostname='xxxxxx',
                     port=22,
                     username='xxx'
                     pkey=pkey)
 #执行命令
 stdin,stdout,stderr=ssh.exec_command('df -lh')
 print stdout.read().decode()
 #关闭
 ssh.close()

4基于密钥的Transport方式登录

# 指定本地的RSA私钥文件,如果建立密钥对时设置的有密码,password为设定的密码,如无不用指定password参数
pkey = paramiko.RSAKey.from_private_key_file('/home/super/.ssh/id_rsa', password='12345')
# 建立连接
trans = paramiko.Transport(('192.168.2.129', 22))
trans.connect(username='super', pkey=pkey)

# 将sshclient的对象的transport指定为以上的trans
ssh = paramiko.SSHClient()
ssh._transport = trans

# 执行命令,和传统方法一样
stdin, stdout, stderr = ssh.exec_command('df -hl')
print(stdout.read().decode())

# 关闭连接
trans.close()

实现输入命令立马返回

import paramiko
import os
import select
import sys

# 建立一个socket
trans = paramiko.Transport(('192.168.2.129', 22))
# 启动一个客户端
trans.start_client()

# 如果使用rsa密钥登录的话
'''
default_key_file = os.path.join(os.environ['HOME'], '.ssh', 'id_rsa')
prikey = paramiko.RSAKey.from_private_key_file(default_key_file)
trans.auth_publickey(username='super', key=prikey)
'''
# 如果使用用户名和密码登录
trans.auth_password(username='super', password='super')
# 打开一个通道
channel = trans.open_session()
# 获取终端
channel.get_pty()
# 激活终端,这样就可以登录到终端了,就和我们用类似于xshell登录系统一样
channel.invoke_shell()
# 下面就可以执行你所有的操作,用select实现
# 对输入终端sys.stdin和 通道进行监控,
# 当用户在终端输入命令后,将命令交给channel通道,这个时候sys.stdin就发生变化,select就可以感知
# channel的发送命令、获取结果过程其实就是一个socket的发送和接受信息的过程
while True:
    readlist, writelist, errlist = select.select([channel, sys.stdin,], [], [])
    # 如果是用户输入命令了,sys.stdin发生变化
    if sys.stdin in readlist:
        # 获取输入的内容
        input_cmd = sys.stdin.read(1)
        # 将命令发送给服务器
        channel.sendall(input_cmd)

    # 服务器返回了结果,channel通道接受到结果,发生变化 select感知到
    if channel in readlist:
        # 获取结果
        result = channel.recv(1024)
        # 断开连接后退出
        if len(result) == 0:
            print("\r\n**** EOF **** \r\n")
            break
        # 输出到屏幕
        sys.stdout.write(result.decode())
        sys.stdout.flush()

# 关闭通道
channel.close()
# 关闭链接
trans.close()

注:转载于https://blog.csdn.net/songfreeman/article/details/50920767

脚本

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import paramiko
import argparse
import os
import sys


class ssh_cmd():
    def __init__(self,host,user,port=22,passwd=None,key_file=None):
        self.trans = paramiko.Transport(host, port)
        if key_file:
            privatekey = os.path.expanduser(key_file)
            key =paramiko.RSAKey.from_private_key_file(privatekey)
            self.trans.connect(username=user,pkey=key)
        else:
            self.trans.connect(username=user,password=passwd)

        self.ssh = paramiko.SSHClient()
        self.ssh._transport = self.trans
    def remote(self,site,local_file,remote_file):
        sftp = paramiko.SFTPClient.from_transport(self.trans)
        print local_file,site,remote_file
        if 'put' in site:
            sftp.put(localpath=local_file, remotepath=remote_file)

        elif 'get' in site:
            sftp.get(localpath=local_file, remotepath=remote_file)
        self.trans.close()

    def cmd(self,cmd):
        print(cmd)
        stdin, stdout, stderr = self.ssh.exec_command(cmd)

        if stderr:
            sys.stderr.write(stderr.read())

        if stdout:
            sys.stdout.write(stdout.read())

        self.trans.close()


def ssh_run():
    parser = argparse.ArgumentParser()

    parser.add_argument('-host','--hostname',type=str,help='the hosturl or hostip ',required=True)
    parser.add_argument('-p','--port',type=int,help='the host ssh port',default=22)
    parser.add_argument('-u','--user',type=str,help='the user name',required=True)
    parser.add_argument('-passwd','--password',type=str, help='the passwd for user')
    parser.add_argument('-k','--key',type=str,help='the path of key file')
    parser.add_argument('-s','--site',type=str,choices=['put', 'get'], help='the site of transfering file')
    parser.add_argument('-c','--cmd',type=str,help='the cmd will exec on remote')
    parser.add_argument('-lf','--local_file',type=str, help='the path of local file')
    parser.add_argument('-rf','--remote_file',type=str,help='the path of remote file')

    args = parser.parse_args()
    if args.password:
        ssh = ssh_cmd(host=args.hostname, port=args.port, user=args.user, passwd=args.password)
    else:
        ssh = ssh_cmd(host=args.hostname, port=args.port, user=args.user, key_file=args.key)

    if args.site:
        ssh.remote(args.site,args.local_file,args.remote_file)

    if args.cmd:
        ssh.cmd(args.cmd)

if __name__ == '__main__':
    ssh_run()





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值