paramiko SSH 模塊簡單應用。


目的:需要ssh鏈接到Linux主機,執行telnet 命令,抓回顯匹配制定內容。

ssh --->執行telnet到本地端口--->執行類似 ls 的命令。匹配命令執行后的特定回顯字段。

官方文檔地址:http://docs.paramiko.org/en/2.0/api/client.html

准備:pip install paramiko 模塊。

import paramiko
ssh = paramiko.SSHClient() #創建sshclient
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) #目的是接受不在本地Known_host文件下的主機。
ssh.connect(ip,port,username,passwd) #connect 函數可以接受很多參數,本例只列舉4個主要的其他參數請見文檔。

#stdin,stdout,stderr = ssh.exec_command(cmd,bufsize,timeout) #exec_command參數使用只需要執行一次的命令,因為執行完該命令以后,shell會自動回到ssh初始連接的shell狀態下,(表達不好,可以看官方文檔。),stdin,out,err,對應shell下的標准輸入,輸出和錯誤。

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

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

#exec_command(commandbufsize=-1timeout=Noneget_pty=False)

#Execute a command on the SSH server. A new Channel is opened and the requested command is executed. The command’s input and output streams are returned as Python file-like objects representing stdin, stdout, and stderr.在SSH server上執行命令,打開新的channel並執行命令,該命令返回的input,output數據流都是file-like對象。可以使用read,readline,readlines方法來將file-like數據變成string類型。

chan = ssh.invoke_shell() #在SSH server端創建一個交互式的shell,且可以按自己的需求配置偽終端,可以在invoke_shell()函數中添加參數配置。

chan.send(cmd+'\n') #利用send函數發送cmd到SSH server,添加'\n'做回車來執行shell命令。注意不同的情況,如果執行完telnet命令后,telnet的換行符是\r\n

chan.recv(bufsize) #通過recv函數獲取回顯。

 

 

這樣基本的函數與方法已經具備了,需要如何定制,就自己寫個函數就可以了。

Wish U like,Have Fun。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM