赞
踩
ssh.close()
paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接。paramiko支持Linux, Solaris, BSD, MacOS X, Windows等平台通过SSH从一个平台连接到另外一个平台。
利用该模块,可以方便的进行ssh连接和sftp协议进行sftp文件传输。
paramiko是一个基于SSH用于连接远程服务器并执行相关操作(SSHClient和SFTPClinet,即一个是远程连接,一个是上传下载服务),使用该模块可以对远程服务器进行命令或文件操作,值得一说的是,
fabric和ansible内部的远程管理就是使用的paramiko来实现。
pycrypto,由于 paramiko 模块内部依赖pycrypto,所以先下载安装pycrypto
pip3 install pycrypto
pip3 install paramiko
一、paramiko模块的安装
paramiko模块依赖PyCrypto模块,而PyCrypto需要GCC库编译,不过一般发行版的源里带有该模块。这里以centos6为例,直接借助以下命令可以直接完成安装:
yum install gcc python-crypto python-paramiko python-devel -y
windows版下可以安装windows版的GCC(MinGW),然后编辑安装pycrypto和paramiko ,下载安成后,直接运行python.exe setup.py build 和 python.exe setup.py install 就可以了。
二、paramiko的连接
使用paramiko模块有两种连接方式,一种是通过paramiko.SSHClient()函数,另外一种是通过paramiko.Transport()函数。
(1)基于用户名和密码的连接
import paramiko
# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname='c1.salt.com', port=22, username='GSuser', password='123')
# 执行命令
stdin, stdout, stderr = ssh.exec_command('ls')
# 获取命令结果
result = stdout.read()
# 关闭连接
ssh.close()
SSHClient 封装 Transport
import paramiko
transport = paramiko.Transport(('hostname', 22))
transport.connect(username='GSuser', password='123')
ssh = paramiko.SSHClient()
ssh._transport = transport
stdin, stdout, stderr = ssh.exec_command('df')
print(stdout.read())
transport.close()
(2)基于公钥秘钥连接
import paramiko
private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')
# 创建SSH对象
ssh = paramiko.SSHClient()
# 允许连接不在know_hosts文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname='c1.salt.com', port=22, username='wupeiqi', key=private_key)
# 执行命令
stdin, stdout, stderr = ssh.exec_command('df')
# 获取命令结果
result = stdout.read()
# 关闭连接
ssh.close()
SSHClient 封装Transport
import paramiko
private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')
transport = paramiko.Transport(('hostname', 22))
transport.connect(username='wupeiqi', pkey=private_key)
ssh = paramiko.SSHClient()
ssh._transport = transport
stdin, stdout, stderr = ssh.exec_command('df')
transport.close()
SFTPClient:
用于连接远程服务器并进行上传下载功能。
(1)基于用户名密码上传下载
import paramiko
transport = paramiko.Transport(('hostname',22))
transport.connect(username='GSuser',password='123')
sftp = paramiko.SFTPClient.from_transport(transport)
# 将location.py 上传至服务器 /tmp/test.py
sftp.put('/tmp/location.py', '/tmp/test.py')
# 将remove_path 下载到本地 local_path
sftp.get('remove_path', 'local_path')
transport.close()
(2)基于公钥秘钥上传下载
import paramiko
private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa')
transport = paramiko.Transport(('hostname', 22))
transport.connect(username='GSuser', pkey=private_key )
sftp = paramiko.SFTPClient.from_transport(transport)
# 将location.py 上传至服务器 /tmp/test.py
sftp.put('/tmp/location.py', '/tmp/test.py')
# 将remove_path 下载到本地 local_path
sftp.get('remove_path', 'local_path')
transport.close()
下面是两种使用paramiko连接到linux服务器的代码
方式一:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("某IP地址",22,"用户名", "口令")
上面的第二行代码的作用是允许连接不在know_hosts文件中的主机。
方式二:
t = paramiko.Transport((“主机”,”端口”))
t.connect(username = “用户名”, password = “口令”)
如果连接远程主机需要提供密钥,上面第二行代码可改成:
t.connect(username = “用户名”, password = “口令”, hostkey=”密钥”)
从widnows端下载linux服务器上的文件
#!/usr/bin/python
import paramiko
t = paramiko.Transport((“主机”,”端口”))
t.connect(username = “用户名”, password = “口令”)
sftp = paramiko.SFTPClient.from_transport(t)
remotepath=’/var/log/system.log’
localpath=’/tmp/system.log’
sftp.get(remotepath, localpath)
t.close()
从widnows端上传文件到linux服务器
#!/usr/bin/python
import paramiko
t = paramiko.Transport((“主机”,”端口”))
t.connect(username = “用户名”, password = “口令”)
sftp = paramiko.SFTPClient.from_transport(t)
remotepath=’/var/log/system.log’
localpath=’/tmp/system.log’
sftp.put(localpath,remotepath)
t.close()
windows对linux运行任意命令,并将结果输出
如果linux服务器开放了22端口,在windows端,我们可以使用paramiko远程连接到该服务器,并执行任意命令,然后通过 print或其它方式得到该结果,
#!/usr/bin/python
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("某IP地址",22,"用户名", "口令")
stdin, stdout, stderr = ssh.exec_command("你的命令")
print stdout.readlines()
ssh.close()
单个文件小传下载的示例:
import paramiko
#建立一个加密的管道
scp=paramiko.Transport(('192.168.0.102',22))
#建立连接
scp.connect(username='root',password='361way')
#建立一个sftp客户端对象,通过ssh transport操作远程文件
sftp=paramiko.SFTPClient.from_transport(scp)
#Copy a remote file (remotepath) from the SFTP server to the local host
sftp.get('/root/testfile','/tmp/361way')
#Copy a local file (localpath) to the SFTP server as remotepath
sftp.put('/root/crash-6.1.6.tar.gz','/tmp/crash-6.1.6.tar.gz')
scp.close()
一个目录下多个文件上传下载的示例:
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import paramiko,datetime,os
hostname='192.168.0.102'
username='root'
password='361way'
port=22
local_dir='/tmp/getfile'
remote_dir='/tmp/abc'
try:
t=paramiko.Transport((hostname,port))
t.connect(username=username,password=password)
sftp=paramiko.SFTPClient.from_transport(t)
#files=sftp.listdir(dir_path)
files=sftp.listdir(remote_dir)
for f in files:
print ''
print '#########################################'
print 'Beginning to download file from %s %s ' % (hostname,datetime.datetime.now())
print 'Downloading file:',os.path.join(remote_dir,f)
sftp.get(os.path.join(remote_dir,f),os.path.join(local_dir,f))#下载
#sftp.put(os.path.join(local_dir,f),os.path.join(remote_dir,f))#上传
print 'Download file success %s ' % datetime.datetime.now()
print ''
print '##########################################'
t.close()
except Exception:
print "connect error!"
利用paramiko实现ssh的交互式连接
以下是通过paramiko模块直接用ssh协议登陆到远程服务器的操作代码,这里先定义一个interactive模块,代码如下:
import socket
import sys
# windows does not have termios...
try:
import termios
import tty
has_termios = True
except ImportError:
has_termios = False
def interactive_shell(chan):
if has_termios:
posix_shell(chan)
else:
windows_shell(chan)
def posix_shell(chan):
import select
oldtty = termios.tcgetattr(sys.stdin)
try:
tty.setraw(sys.stdin.fileno())
tty.setcbreak(sys.stdin.fileno())
chan.settimeout(0.0)
while True:
r, w, e = select.select([chan, sys.stdin], [], [])
if chan in r:
try:
x = chan.recv(1024)
if len(x) == 0:
print 'rn*** EOFrn',
break
sys.stdout.write(x)
sys.stdout.flush()
except socket.timeout:
pass
if sys.stdin in r:
x = sys.stdin.read(1)
if len(x) == 0:
break
chan.send(x)
finally:
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
# thanks to Mike Looijmans for this code
def windows_shell(chan):
import threading
sys.stdout.write("Line-buffered terminal emulation. Press F6 or ^Z to send EOF.rnrn")
def writeall(sock):
while True:
data = sock.recv(256)
if not data:
sys.stdout.write('rn*** EOF ***rnrn')
sys.stdout.flush()
break
sys.stdout.write(data)
sys.stdout.flush()
writer = threading.Thread(target=writeall, args=(chan,))
writer.start()
try:
while True:
d = sys.stdin.read(1)
if not d:
break
chan.send(d)
except EOFError:
# user hit ^Z or F6
pass
import paramiko
import interactive
#记录日志
paramiko.util.log_to_file('/tmp/test')
#建立ssh连接
ssh=paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('192.168.0.102',port=22,username='root',password='xxxxxx',compress=True)
#建立交互式shell连接
channel=ssh.invoke_shell()
#建立交互式管道
interactive.interactive_shell(channel)
#关闭连接
channel.close()
ssh.close()
实现远程命令执行和文件上传
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import paramiko
class SSHConnection(object):
def __init__(self, host='192.168.12.68', port=22, username='locojoy',pwd='123321QQ!'):
self.host = host
self.port = port
self.username = username
self.pwd = pwd
self.__k = None
def run(self):
self.connect() # 连接远程服务器
self.upload('db.py','/tmp/1.py') # 将本地的db.py文件上传到远端服务器的/tmp/目录下并改名为1.py
self.cmd('df') # 执行df 命令
self.close() # 关闭连接
def connect(self):
transport = paramiko.Transport((self.host, self.port))
transport.connect(username=self.username, password=self.pwd)
self.__transport = transport
def close(self):
self.__transport.close()
def upload(self,local_path,target_path):
sftp = paramiko.SFTPClient.from_transport(self.__transport)
sftp.put(local_path,target_path)
def cmd(self, command):
ssh = paramiko.SSHClient()
ssh._transport = self.__transport
# 执行命令
stdin, stdout, stderr = ssh.exec_command(command)
# 获取命令结果
result = stdout.read()
print(result)
return result
obj = SSHConnection()
obj.run()
paramiko在堡垒机中的应用
简单实例:远程连接一台主机,操作命令,linux版本,输入终端为回车则发送命令。不支持tab补全功能
import paramiko, sys, os, socket, select, getpass
from paramiko.py3compat import u # 在python3中是这样使用的,如果在Python2中则注释这行
# 这个程序依赖于终端,只能在Liunx下运行,windows用其他的方式
tran = paramiko.Transport(('192.168.12.68', 22,))
tran.start_client()
tran.auth_password('locojoy', '123321QQ!')
# 打开一个通道
chan = tran.open_session()
# 获取一个终端
chan.get_pty()
# 激活器
chan.invoke_shell()
# 原始的方法利用终端进行收发消息
# 利用sys.stdin,肆意妄为执行操作
# 用户在终端输入内容,并将内容发送至远程服务器
# 远程服务器执行命令,并将结果返回
# 用户终端显示内容
while True:
# 监视用户输入和服务器返回数据
# sys.stdin 处理用户输入
# chan 是之前创建的通道,用于接收服务器返回信息
# 通过select监听终端(输入输出),一旦变化,就将拿到的数据发送给服务器
# 通过监听socket句柄,如果有变化表示服务器要给我发消息
readable, writeable, error = select.select([chan, sys.stdin, ],[],[],1)
# 通过select.select 监听chan(打开的通道(和远程服务器连接的状态)), sys.stdin(输入),一旦变化就写入readable
# 当chan变化时,加入到readable,远程服务器发送内容过来
if chan in readable:
try:
x = u(chan.recv(1024)) # Python3用这个
# x = chan.recv(1024) Python2使用这个
if len(x) == 0:
print('\r\n*** EOF\r\n')
break
sys.stdout.write(x) # 写入缓冲区
sys.stdout.flush() # 刷新,将缓冲区内容显示出来
except socket.timeout:
pass
# 当sys.stdin 放入readable中时,将获取到的内容发送到远程服务器
if sys.stdin in readable:
inp = sys.stdin.readline()
chan.sendall(inp)
chan.close()
tran.close()
(2)每按一个键就发送记录,并支持tab自动补全
import paramiko, sys, os, socket, select, getpass, termios, tty
from paramiko.py3compat import u
tran = paramiko.Transport(('10.211.55.4', 22,))
tran.start_client()
tran.auth_password('wupeiqi', '123')
# 打开一个通道
chan = tran.open_session()
# 获取一个终端
chan.get_pty()
# 激活器
chan.invoke_shell()
# 获取原tty属性
oldtty = termios.tcgetattr(sys.stdin)
try:
# 为tty设置新属性
# 默认当前tty设备属性:
# 输入一行回车,执行
# CTRL+C 进程退出,遇到特殊字符,特殊处理。
# 这是为原始模式,不认识所有特殊符号
# 放置特殊字符应用在当前终端,如此设置,将所有的用户输入均发送到远程服务器
tty.setraw(sys.stdin.fileno()) # 恢复终端原始状态,每按一个键就发送
chan.settimeout(0.0)
while True:
# 监视 用户输入 和 远程服务器返回数据(socket)
# 阻塞,直到句柄可读
r, w, e = select.select([chan, sys.stdin], [], [], 1)
if chan in r: # 获取服务返回的内容
try:
x = u(chan.recv(1024))
if len(x) == 0:
print('\r\n*** EOF\r\n')
break
sys.stdout.write(x)
sys.stdout.flush()
except socket.timeout:
pass
if sys.stdin in r: # 发送命令
x = sys.stdin.read(1) # 读取一个字符
if len(x) == 0:
break
chan.send(x) # 发送一个字符
finally:
# 重新设置终端属性,将终端状态还原
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)
chan.close()
tran.close()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。