欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

python paramiko_python中的paramiko模块

发布时间:2025/4/5 52 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python paramiko_python中的paramiko模块 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

paramiko是用python语言写的一个模块,遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接。paramiko支持Linux, Solaris, BSD, MacOS X, Windows等平台通过SSH从一个平台连接到另外一个平台。利用该模块,可以方便的进行ssh连接和sftp协议进行sftp文件传输。

paramiko常用的类与方法:

1、SSHClient类

SHClient类是SSH服务会话的高级表示,封装了传输、通道以及SFTPClient的校验、建立方法,通常用于执行命令。

1)connect方法

connect(self,hostname,port=22,username=None,password=None,pkey=None,key_filename=None,timeout=None,allow_agent=True,look_for_keys=True,compress=False)

参数说明:

hostname:连接目标的主机地址

port:连接目录的端口,默认为22

username:用户名

password:密码

pkey:私钥方式用户验证

key_filename:私钥文件名

timeout:连接超时时间

allow_agent:是否允许使用ssh代理

look_for_keys:是否允许搜索私钥文件

compress:打开时是否压缩

2)exec_command方法

exec_command(self,command,bufsize=-1)

参数说明:

command:执行的的指令

bufsize:文件缓冲区大小,-1不限制

3)load_system_host_keys方法

load_system_host_keys(self,filename=None)

参数说明:

filename:指定远程主机的公钥文件,默认为.ssh目录下的known_hosts文件

4)set_missing_host_key_policy方法

ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

参数说明:

AutoAddPolicy:自动添加主机名及密钥到本地并保存,不依赖load_system_host_keys()配置,即如果known_hosts里没有远程主机的公钥时,默认连接会提示yes/no,自动yes

RejectPolicy:自动拒绝未知主机名和密钥,依赖load_system_host_keys()

WarnningPlicy:功能与AutoAddPolicy相同,但是未知主机会提示yes/no

2、SFTPClient类

根据SSH传输协议的sftp会话,实现远程文件上传、下载等操作。

1)from_transport方法

classmethod from_transport(cls,t)

参数说明:

t:一个已通过验证的传输对象

示例:

>>> importparamiko

>>> a = paramiko.Transport((“127.0.0.1″,2222))

>>> a.connect(username=”root”, password=’123456′)

>>> sftp = paramiko.SFTPClient.from_transport(a)

2)put方法

put(self,localpath,remotepath,callback=None,confirm=True)

参数说明:

localpath:上传源文件的本地路径

remotepath:目标路径

callback:获取接收与总传输字节数

confirm:上传完毕后是否调用stat()方法,以便确认文件大小

示例:

>>> localpath=’ftp-test.log’

>>> remotepath=’/data/ftp-test.log’

>>> sftp.put(localpath,remotepath)

3)get方法

get(self, remotepath, localpath, callback=None)

参数说明:

remotepath:需要下载的远程文件

localpath:本地存储路径

callback:同put方法

4)其他方法

mkdir:用于创建目录

remove:删除目录

rename:重命名

stat:获取文件信息

listdir:获取目录列表

代码示例

Paramiko ssh客户端:

#!/usr/bin/python

importparamiko

importos,sys

ssh_host = sys.argv[1] ssh_port = 22

user = 'root'password = 'xxxxxx'cmd = sys.argv[2]

paramiko.util.log_to_file('/tmp/test') #使用paramiko记录日志

s = paramiko.SSHClient() #绑定一个实例

s.load_system_host_keys() #加载known_hosts文件

s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #远程连接如果提示yes/no时,默认为yes

s.connect(ssh_host,ssh_port,user,password,timeout=5) #连接远程主机

stdin,stdout,stderr = s.exec_command(cmd) #执行指令,并将命令本身及命令的执行结果赋值到标准办入、标准输出或者标准错误

cmd_result = stdout.read(),stderr.read() #取得执行的输出

for line incmd_result:

printline

s.close()

使用ssh密钥连接:

pkey_file = '/home/breeze/.ssh/id_rsa'key =paramiko.RSAKey.from_private_key_file(pkey_file)

s.connect(host,port,username,pkey=key,timeout=5)

stdin,stdout,stderr = s.exec_command(cmd)

Paramiko SFTP传送文件:

#!/usr/bin/python

importos,sys

importparamiko

host = sys.argv[1]

rfilename = sys.argv[2]

lfilename =os.path.basename(rfilename)

user = 'root'password = 'xxxx'paramiko.util.log_to_file('/tmp/test')

t = paramiko.Transport((host,22))

t.connect(username=user,password=password)

sftp =paramiko.SFTPClient.from_transport(t)

sftp.get(rfilename,lfilename)

#sftp.put('paramiko1.py','/tmp/paramiko1.py')

t.close()

使用interactive模块实现SSH交互:

interactive.py模块内容如下:

#!/usr/bin/python

importsocket

importsys

#windows does not have termios...

try:

importtermios

importtty

has_termios =True

exceptImportError:

has_termios =False

definteractive_shell(chan):

ifhas_termios:

posix_shell(chan)

else:

windows_shell(chan)

defposix_shell(chan):

importselect

oldtty =termios.tcgetattr(sys.stdin)

try:

tty.setraw(sys.stdin.fileno())

tty.setcbreak(sys.stdin.fileno())

chan.settimeout(0.0)

whileTrue:

r, w, e =select.select([chan, sys.stdin], [], [])

if chan inr:

try:

x = chan.recv(1024)

if len(x) ==0:

print '\r\n*** EOF\r\n',

breaksys.stdout.write(x)

sys.stdout.flush()

exceptsocket.timeout:

pass

if sys.stdin inr:

x = sys.stdin.read(1)

if len(x) ==0:

breakchan.send(x)

finally:

termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldtty)

#thanks to Mike Looijmans for this code

defwindows_shell(chan):

importthreading

sys.stdout.write("Line-buffered terminal emulation. Press F6 or ^Z to send EOF.\r\n\r\n")

defwriteall(sock):

whileTrue:

data = sock.recv(256)

if notdata:

sys.stdout.write('\r\n*** EOF ***\r\n\r\n')

sys.stdout.flush()

breaksys.stdout.write(data)

sys.stdout.flush()

writer = threading.Thread(target=writeall, args=(chan,))

writer.start()

try:

whileTrue:

d = sys.stdin.read(1)

if notd:

breakchan.send(d)

exceptEOFError:

#user hit ^Z or F6

pass

inter_ssh.py交互脚本如下:

#!/usr/bin/python#_*_coding:utf8_*_

importparamiko

importinteractive

#记录日志

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.128.82',port=22,username='root',password='cheyian')

#建立交互式shell连接

channel=ssh.invoke_shell()

#建立交互式管道

interactive.interactive_shell(channel)

#关闭连接

channel.close()

ssh.close()

总结

以上是生活随笔为你收集整理的python paramiko_python中的paramiko模块的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。