python之paramiko模組資料總結

2021-10-07 06:43:08 字數 2087 閱讀 2289

目錄

1、前言

2、paramiko模組安裝方法

3、常用函式介紹(著重使用方法)

3.1 sshclient類

pip/pip3 install paramiko
基礎配置:

引入paramiko庫,引用sshclient函式並建立sshclient,賦給ssh:

import paramiko

ssh = paramiko.sshclient()

(1)ssh遠端連線伺服器

connect(hostname, port=22, username=none, password=none, pkey=none, key_filename=none, timeout=none, allow_agent=true, look_for_keys=true, compress=false, sock=none, gss_auth=false, gss_kex=false, gss_deleg_creds=true, gss_host=none, banner_timeout=none, auth_timeout=none, gss_trust_dns=true, passphrase=none)
引數說明:

例如:

ssh.connect(ip,22,username,passwd,timeout=5)
此處ip、username、passwd都作為變數;

(2)遠端主機沒有本地主機金鑰或hostkeys物件時的連線方法,需要配置set_missing_host_key_policy(policy)

引數常見取值有3種,分別如下:

例如:

ssh.set_missing_host_key_policy(paramiko.autoaddpolicy())
(3)遠端執行命令,該命令的輸入與輸出流為標準輸入(stdin)、輸出(stdout)、錯誤(stderr)的python檔案對像

exec_command(command, bufsize=-1, timeout=none, get_pty=false, environment=none)
引數說明:

例如:

stdin,stdout,stderr = ssh.exec_command(cmd,bufsize,timeout) 

#stdin.write('y'+'\n') #這樣通過標準輸入輸入命令???

#print stdout.read() #輸出標準輸出。

備註:在ssh server上執行命令,開啟新的channel並執行命令,該命令返回的input,output資料流都是file-like物件。可以使用read,readline,readlines方法來將file-like資料變成string型別。stdin標準輸入表示執行了cmd命令後的輸入???

(4)在遠端伺服器上生成新的互動式shell

invoke_shell(term='vt100', width=80, height=24, width_pixels=0, height_pixels=0, environment=none)
例如:

在ssh server端建立乙個互動式的shell,且可以按自己的需求配置偽終端,可以在invoke_shell()函式中新增引數配置

chan = ssh.invoke_shell()
chan.send(cmd) #利用send函式傳送cmd到ssh server,新增做回車來執行shell命令(cmd中需要有\n命令才能執行)。注意不同的情況,如果執行完telnet命令後,telnet的換行符是\r\n

(5)通過recv函式獲取回顯:

chan.recv(bufsize) #
(6)關閉ssh連線

ssh.close()

python實戰之paramiko模組

目錄 paramiko是用python語言寫的乙個模組,遵循ssh2協議,支援以加密和認證的方式,進行遠端伺服器的連線。由於使用的是python這樣的能夠跨平台執行的語言,所以所有python支援的平台,如linux,solaris,bsd,macos x,windows等,paramiko都可以支...

python ssh之paramiko模組使用

1.安裝 sudo pip install paramiko 2.連線到linux伺服器 方法一 paramiko.util.log to file ssh.log 寫日誌檔案 client paramiko.sshclient client.set missing host key policy ...

python安裝paramiko模組

參考 一 依賴模組 pycrypto the python cryptography toolkit wget wget 三 安裝 1 安裝pycrypto tar zxvf pycrypto 2.0.1.tar.gz cd pycrypto 2.0.1 python setup.py build ...