日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python paramiko_python中的paramiko模块

發布時間:2025/4/5 python 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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模块的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。