This article mainly shares the learning materials of the python paramiko module with everyone. It has certain reference value. Interested friends can refer to it.
paramiko is a module written in python language. Follow The SSH2 protocol supports encryption and authentication to connect to remote servers. paramiko supports Linux, Solaris, BSD, MacOS X, Windows and other platforms to connect from one platform to another through SSH. Using this module, you can easily perform ssh connection and sftp protocol for sftp file transfer.
First let us clarify the following nouns:
SSHClient: packages Channel, Transport, SFTPClient
Channel: is a Type Socket, a secure SSH transmission channel;
Transport: is an encrypted session (but the Session of such an object is not established), and creates an encrypted tunnels. This tunnels It's called Channel;
Session: is the object that keeps the connection between client and Server. Use connect()/start_client()/start_server() to start the session.
Download and install
pycrypto. Since the paramiko module depends internally on pycrypto, download and install pycrypto first
pip3 install pycrypto
pip3 install paramiko
Specific module usage
SSHClient:
Remote connections are divided into two types: (1) Connection based on username and password (2) Connection based on public key and secret key
Remote operation is done using paramiko. In fact, it is essentially divided into two types: (1) Only use SSHClient (2) Create a transport yourself
Connect based on username and password
import paramiko # 创建SSH对象 ssh = paramiko.SSHClient() # 允许连接不在know_hosts文件中的主机 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 连接服务器 ssh.connect(hostname='host', port=22, username='root', password='123') # 执行命令 stdout命令结果,stderr错误 stdin, stdout, stderr = ssh.exec_command('ls') # 获取命令结果 result = stdout.read() # 关闭连接 ssh.close()
SSHClient encapsulation Transport
import paramiko transport = paramiko.Transport(('hostname', 22)) transport.connect(username='root', password='123') ssh = paramiko.SSHClient() ssh._transport = transport stdin, stdout, stderr = ssh.exec_command('df') print(stdout.read()) transport.close()
Connect based on public key
##
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='host', port=22, username='root', key=private_key) # 执行命令 stdin, stdout, stderr = ssh.exec_command('df') # 获取命令结果 result = stdout.read() # 关闭连接 ssh.close()SSHClient encapsulates 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:
is used to connect to the remote server and perform upload and download functions . Upload and download based on username and passwordimport paramiko transport = paramiko.Transport(('hostname',22)) transport.connect(username='root',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()Upload and download based on public key
import paramiko private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa') transport = paramiko.Transport(('hostname', 22)) transport.connect(username='root', 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()Demo: Implement remote command execution and file upload
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()
The above is the detailed content of Learning sharing about paramiko module in python. For more information, please follow other related articles on the PHP Chinese website!

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

Forloopsareadvantageousforknowniterationsandsequences,offeringsimplicityandreadability;whileloopsareidealfordynamicconditionsandunknowniterations,providingcontrolovertermination.1)Forloopsareperfectforiteratingoverlists,tuples,orstrings,directlyacces

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment
