Paramiko module is a very important module in Python, his function is mainly divided into two large pieces of function. One is the Impersonate SSH feature to log on to the remote host to execute the command. One is to simulate the SFTP feature transfer file.
Paramiko supports password login mode and password-free private key login mode.
Password Login mode code is as follows:
#!/usr/bin/env python# coding:utf-8import paramiko# Create ssh object ssh = Paramiko. Sshclient () # A policy that accesses unknown hosts, allowing connections to host Ssh.set_missing_host_key_policy (Paramiko) that are not in the Know_hosts file. Autoaddpolicy ()) # Connect server Ssh.connect (hostname= ' 172.16.1.101 ', port=22, username= ' WGW ', password= ' 123456 ') # Execute command stdin, stdout, stderr = Ssh.exec_command (' df ') # gets the command result = Stdout.read () #打印远程命令的执行结果print result# close Connection ssh.close ()
The above code is very simple, a bit of operation and maintenance of the foundation must be able to see clearly. The only thing to note is that when encountering an unknown host, the SSH processing strategy. This should be set well. Otherwise, the hosts that are not in the Know_hosts file will be rejected when they first log on.
The code to log in using the SSH key is as follows:
#!/usr/bin/env python# coding:utf-8import paramiko# Specifies the storage location of the private key file that is used to log on to other hosts Private_key = Paramiko. Rsakey.from_private_key_file ('/home/auto/.ssh/id_rsa ') # create ssh object ssh = Paramiko. Sshclient () # allows connections to host Ssh.set_missing_host_key_policy (Paramiko) that are not in the Know_hosts file. Autoaddpolicy ()) # When connecting to a server by Pkey keyword instead of password keyword ssh.connect (hostname= ' 172.16.1.101 ', port=22, username= ' WGW ', Pkey =private_key) # Execute command stdin, stdout, stderr = Ssh.exec_command (' df ') # get command result = Stdout.read () # Close connection Ssh.close ()
The user and password login through the secret key is very similar, just define the location of the private key file and then reference the Pkey keyword.
The code for uploading and downloading files using the password and SFTP commands is as follows:
Import Paramikotransport = Paramiko. Transport (' hostname ', ()) Transport.connect (username= ' Wupeiqi ', password= ' 123 ') sftp = Paramiko. Sftpclient.from_transport (transport) # upload location.py to Server/tmp/test.pysftp.put ('/tmp/location.py ', '/tmp/test.py ') # download Remove_path to local local_pathsftp.get (' Remove_path ', ' Local_path ') transport.close ()
The code for uploading and downloading files using the key and SFTP commands is as follows:
Import Paramikoprivate_key = Paramiko. Rsakey.from_private_key_file ('/home/auto/.ssh/id_rsa ') #创建transport对象 transport = Paramiko. Transport (' hostname ', ()) #通过connect方法创建远程连接transport. Connect (username= ' WGW ', Pkey=private_key) # Call Sftpclient to fill in the transport object you just created to create an Sftp object sftp = Paramiko. Sftpclient.from_transport (transport) # upload location.py to Server/tmp/test.pysftp.put ('/tmp/location.py ', '/tmp/test.py ') # download Remove_path to local local_pathsftp.get (' Remove_path ', ' Local_path ') transport.close ()
The code is not difficult, but it is possible to implement SSH and SFTP from the code. The method used to create the connection is different.
SSH is created using the Connect method inside Sshclient ().
SSH = Paramiko. Sshclient () ssh.connect (hostname= ' 172.16.1.101 ', port=22, username= ' WGW ', password= ' 123456 ')
SFTP uses the transport () inside of the Connetc method to create the
Transport = Paramiko. Transport (' 172.16.1.101 ', ()) Transport.connect (username= ' WGW ', password= ' 123456 ')
Two are all connect methods what are the differences and connections? Actually Paramiko. Sshclient (). Connect () The internal implementation of this method calls the transport (). Connect () method. So you can think of transport () as a common way to create a connection inside a Paramiko. The Fairy, we're going to rewrite the SSH functionality through the transport method.
Import paramiko# calls the transport method, like the connection function that implements SFTP, creates a connection transport = Paramiko. Transport (' 172.16.1.101 ', ()) Transport.connect (username= ' WGW ', password= ' 123456 ') #这个方法还是必须要加上的还需要调用exec_ The command () method uses SSH = Paramiko. Sshclient () #用这一句代替ssh. Connect () Method Ssh._transport = Transportstdin, stdout, stderr = Ssh.exec_command (' df ') print Stdout.read () Transport.close ()
So if we want to implement a remote operation of the host program, then the program's remote execution commands and transfer files and other functions can be written into a class inside. The schematic code is as follows:
Import paramikoclass my_paramiko (object): def __init__ (Self,ip,port): self.ip=ip Self.port=int (port) #定义登录被管理主机时使用的用户 self.manager= ' admin ' # Specifies the key file location self.key=paramiko used when logging on to each host. Rsakey.from_private_key_file ('/home/wgw/.ssh/id_rsa ') def connect (self): "" " This method is used to call Paramiko to create a connection. "" #创建连接实例 transport = paramiko. Transport ((Self.ip,self.port)) transport.connect (USername=self.manager, pkey=self.key) self.__transport= Transport def cmd (self,user_cmd): " "" This method is used to implement commands on a remote host "" #调用连接方法连接服务器 self.connect () #调用paramiko的SSH方法实现远程执行命令 ssh = paramiko. Sshclient () ssh._transport=self.__transport ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ()) #远程执行命令 ssh.exec_command (user_cmd) #执行命令后管理远程连接 &Nbsp; ssh.close () def excute_upload (self, Local_file,remote_file): "" " This method is used to implement, upload files to remote functions. Requires the user to enter a local file path and a remote file path. "" " # Call connection Method Connection Server self.connect () #调用paramiko的sftp方法实现远程上传命令 sftp = Paramiko. Sftpclient.from_transport (Self.__transport) # Call the Sftp.put method to upload the local file to the server. sftp.put (Local_file,remote_file)
In this way, it is possible to combine functions well.
This article from "Thunderbolt Tofu" blog, declined reprint!
Python Paramiko module